inbound_traffic.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "maps"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. "gorm.io/gorm"
  18. "gorm.io/gorm/clause"
  19. )
  20. // A client with a renewal day set auto-renews too, so it must not read as
  21. // depleted — otherwise the operator's purge deletes it between cycles (#6239).
  22. const depletedClientsClause = "reset = 0 and reset_day = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  23. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  24. var disabledNodeIDs []int
  25. err = submitTrafficWrite(func() error {
  26. var inner error
  27. needRestart, clientsDisabled, disabledNodeIDs, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  28. return inner
  29. })
  30. if err == nil && len(disabledNodeIDs) > 0 {
  31. s.restartRemoteNodesOnDisable(disabledNodeIDs)
  32. }
  33. return
  34. }
  35. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, []int, error) {
  36. db := database.GetDB()
  37. // Commit durable traffic before best-effort lifecycle maintenance so helper
  38. // failures cannot discard usage already reported by Xray.
  39. if err := db.Transaction(func(tx *gorm.DB) error {
  40. if err := s.addInboundTraffic(tx, inboundTraffics); err != nil {
  41. return err
  42. }
  43. return s.addClientTraffic(tx, clientTraffics)
  44. }); err != nil {
  45. return false, false, nil, err
  46. }
  47. var (
  48. needRestart bool
  49. clientsDisabled bool
  50. disabledNodeIDs []int
  51. disabledClientsCount int64
  52. )
  53. batch := newTrafficMutationBatch()
  54. err := db.Transaction(func(tx *gorm.DB) error {
  55. needRestart0, count, err := s.autoRenewClients(tx, batch)
  56. if err != nil {
  57. return fmt.Errorf("renew clients: %w", err)
  58. }
  59. if count > 0 {
  60. logger.Debugf("%v clients renewed", count)
  61. }
  62. needRestart1, count, nodeIDs, err := s.disableInvalidClients(tx, batch)
  63. if err != nil {
  64. return fmt.Errorf("disable invalid clients: %w", err)
  65. }
  66. if count > 0 {
  67. logger.Debugf("%v clients disabled", count)
  68. disabledClientsCount = count
  69. }
  70. needRestart2, count, err := s.disableInvalidInbounds(tx, batch)
  71. if err != nil {
  72. return fmt.Errorf("disable invalid inbounds: %w", err)
  73. }
  74. if count > 0 {
  75. logger.Debugf("%v inbounds disabled", count)
  76. }
  77. if err := batch.markNodesTx(tx); err != nil {
  78. return err
  79. }
  80. needRestart = needRestart0 || needRestart1 || needRestart2
  81. clientsDisabled = disabledClientsCount > 0
  82. disabledNodeIDs = nodeIDs
  83. return nil
  84. })
  85. if err != nil {
  86. logger.Warning("traffic lifecycle maintenance failed after traffic commit:", err)
  87. return false, false, nil, nil
  88. }
  89. needRestart = needRestart || s.applyTrafficMutationBatch(batch)
  90. return needRestart, clientsDisabled, disabledNodeIDs, nil
  91. }
  92. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  93. if len(traffics) == 0 {
  94. return nil
  95. }
  96. var err error
  97. for _, traffic := range traffics {
  98. if traffic.IsInbound {
  99. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  100. Updates(map[string]any{
  101. "up": gorm.Expr(database.ClampedAddExpr("up"), traffic.Up),
  102. "down": gorm.Expr(database.ClampedAddExpr("down"), traffic.Down),
  103. }).Error
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. }
  109. return nil
  110. }
  111. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  112. if len(traffics) == 0 {
  113. return nil
  114. }
  115. emails := make([]string, 0, len(traffics))
  116. for _, traffic := range traffics {
  117. emails = append(emails, traffic.Email)
  118. }
  119. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  120. // Match purely by email. client_traffics is email-keyed (one shared row per
  121. // email regardless of how many inbounds the client is attached to), and these
  122. // emails come from the local xray's report, so they always belong to a client
  123. // attached to a local inbound. The old `inbound_id NOT IN (node inbounds)`
  124. // filter dropped the local traffic of a client attached to both a node and the
  125. // mother inbound whenever the node inbound happened to be attached first — its
  126. // shared row then carried the node inbound's id (AddClientStat used to use
  127. // OnConflict DoNothing and never refreshed it; it now refreshes inbound_id on
  128. // conflict, but this filter was removed rather than relying on that ordering).
  129. err = tx.Model(xray.ClientTraffic{}).
  130. Where("email IN (?)", emails).
  131. Find(&dbClientTraffics).Error
  132. if err != nil {
  133. return err
  134. }
  135. // Avoid empty slice error
  136. if len(dbClientTraffics) == 0 {
  137. return nil
  138. }
  139. dbClientTraffics, convertedExpiryByEmail, err := s.adjustTraffics(tx, dbClientTraffics)
  140. if err != nil {
  141. return err
  142. }
  143. // Index by email for O(N) merge.
  144. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  145. for i := range traffics {
  146. if traffics[i] != nil {
  147. trafficByEmail[traffics[i].Email] = traffics[i]
  148. }
  149. }
  150. now := time.Now().UnixMilli()
  151. // Use atomic per-row UPDATE instead of read-modify-write Save. tx.Save
  152. // issues UPDATEs in slice order, which varies between concurrent callers;
  153. // on PostgreSQL two transactions locking the same rows in opposite order
  154. // deadlock. An atomic "SET up = up + ?" never holds a row lock across a
  155. // subsequent lock acquisition, so concurrent writers cannot deadlock.
  156. for _, ct := range dbClientTraffics {
  157. t, ok := trafficByEmail[ct.Email]
  158. if !ok || (t.Up == 0 && t.Down == 0) {
  159. continue
  160. }
  161. if err = tx.Exec(
  162. fmt.Sprintf(
  163. `UPDATE client_traffics SET up = %s, down = %s, last_online = %s WHERE email = ?`,
  164. database.ClampedAddExpr("up"),
  165. database.ClampedAddExpr("down"),
  166. database.GreatestExpr("last_online", "?"),
  167. ),
  168. t.Up, t.Down, now, ct.Email,
  169. ).Error; err != nil {
  170. logger.Warning("AddClientTraffic update data ", err)
  171. }
  172. }
  173. // adjustTraffics converts delayed-start rows (negative ExpiryTime → absolute
  174. // deadline) in-memory. Persist that conversion now since the traffic UPDATE
  175. // above only touches up/down/last_online. Only converted emails are written:
  176. // updating every polled row issued one no-op UPDATE per active client per
  177. // poll. Sorted order keeps concurrent writers lock-compatible on Postgres.
  178. for _, email := range slices.Sorted(maps.Keys(convertedExpiryByEmail)) {
  179. if err = tx.Exec(
  180. `UPDATE client_traffics SET expiry_time = ? WHERE email = ? AND expiry_time < 0`,
  181. convertedExpiryByEmail[email], email,
  182. ).Error; err != nil {
  183. logger.Warning("AddClientTraffic update expiry_time ", err)
  184. }
  185. }
  186. return nil
  187. }
  188. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, map[string]int64, error) {
  189. now := time.Now().UnixMilli()
  190. // "Start After First Use" stores a negative expiry (the duration). On the
  191. // first traffic tick it becomes an absolute deadline of now+duration. Compute
  192. // it once per email so every inbound the client is attached to lands on the
  193. // same value (recomputing per inbound would skip all but the first one).
  194. newExpiryByEmail := make(map[string]int64, len(dbClientTraffics))
  195. for traffic_index := range dbClientTraffics {
  196. if dbClientTraffics[traffic_index].ExpiryTime < 0 {
  197. newExpiryByEmail[dbClientTraffics[traffic_index].Email] = now - dbClientTraffics[traffic_index].ExpiryTime
  198. }
  199. }
  200. if len(newExpiryByEmail) == 0 {
  201. return dbClientTraffics, nil, nil
  202. }
  203. delayedEmails := make([]string, 0, len(newExpiryByEmail))
  204. for email := range newExpiryByEmail {
  205. delayedEmails = append(delayedEmails, email)
  206. }
  207. // Resolve the owning inbounds through the client_inbounds link, which is
  208. // authoritative. client_traffics.inbound_id goes stale when an inbound is
  209. // deleted and recreated, which would leave the negative expiry unconverted.
  210. var inboundIds []int
  211. err := tx.Table("client_inbounds").
  212. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  213. Where("clients.email IN (?)", delayedEmails).
  214. Distinct().
  215. Pluck("client_inbounds.inbound_id", &inboundIds).Error
  216. if err != nil {
  217. return nil, nil, err
  218. }
  219. if len(inboundIds) == 0 {
  220. return dbClientTraffics, nil, nil
  221. }
  222. var inbounds []*model.Inbound
  223. err = tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  224. if err != nil {
  225. return nil, nil, err
  226. }
  227. for inbound_index := range inbounds {
  228. settings := map[string]any{}
  229. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  230. clients, ok := settings["clients"].([]any)
  231. if ok {
  232. var newClients []any
  233. for client_index := range clients {
  234. c := clients[client_index].(map[string]any)
  235. email, _ := c["email"].(string)
  236. if newExpiry, ok := newExpiryByEmail[email]; ok {
  237. c["expiryTime"] = newExpiry
  238. c["updated_at"] = now
  239. }
  240. if _, ok := c["created_at"]; !ok {
  241. c["created_at"] = now
  242. }
  243. if _, ok := c["updated_at"]; !ok {
  244. c["updated_at"] = now
  245. }
  246. newClients = append(newClients, any(c))
  247. }
  248. settings["clients"] = newClients
  249. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. inbounds[inbound_index].Settings = string(modifiedSettings)
  254. }
  255. }
  256. for traffic_index := range dbClientTraffics {
  257. if newExpiry, ok := newExpiryByEmail[dbClientTraffics[traffic_index].Email]; ok {
  258. dbClientTraffics[traffic_index].ExpiryTime = newExpiry
  259. }
  260. }
  261. err = tx.Save(inbounds).Error
  262. if err != nil {
  263. logger.Warning("AddClientTraffic update inbounds ", err)
  264. logger.Error(inbounds)
  265. } else {
  266. for _, ib := range inbounds {
  267. if ib == nil {
  268. continue
  269. }
  270. cs, gcErr := s.GetClients(ib)
  271. if gcErr != nil {
  272. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  273. continue
  274. }
  275. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  276. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  277. }
  278. }
  279. }
  280. return dbClientTraffics, newExpiryByEmail, nil
  281. }
  282. // apiUserFromClient prepares a stored client object for the runtime AddUser
  283. // call. The copy matters twice over: the stored object keeps being mutated and
  284. // marshalled back into the inbound's settings, which must not gain an API-only
  285. // key, and shadowsocks clients carry no cipher of their own — it lives on the
  286. // inbound, and without it the API cannot tell which of xray's two shadowsocks
  287. // account types the running inbound expects.
  288. func apiUserFromClient(client map[string]any, cipher string) map[string]any {
  289. user := maps.Clone(client)
  290. if user == nil {
  291. user = map[string]any{}
  292. }
  293. if cipher != "" {
  294. user["cipher"] = cipher
  295. }
  296. return user
  297. }
  298. // Candidates and renewals are not the same set: a skipped candidate keeps its
  299. // counters, so only the clients actually reset may lose their cross-panel rows.
  300. func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMutationBatch) (bool, int64, error) {
  301. // check for time expired
  302. var traffics []*xray.ClientTraffic
  303. now := time.Now().Unix() * 1000
  304. var err error
  305. // Filter to clients that have at least one local inbound. Using
  306. // client_traffics.inbound_id is wrong: it goes stale after an inbound is
  307. // deleted/recreated and always points to the first inbound the client was
  308. // attached to, so it could be a node inbound even when the client also has
  309. // local inbounds. The email-based join through client_inbounds is authoritative.
  310. err = tx.Model(xray.ClientTraffic{}).
  311. Where("(reset > 0 or reset_day > 0) and expiry_time > 0 and expiry_time <= ?", now).
  312. // A prepaid plan stops itself: once as many renewals have fired as the
  313. // operator allowed, the client is left to expire like any other.
  314. Where("reset_max <= 0 or reset_count < reset_max").
  315. Where("email IN (?)", tx.Table("client_inbounds ci").
  316. Select("c.email").
  317. Joins("JOIN clients c ON c.id = ci.client_id").
  318. Joins("JOIN inbounds i ON i.id = ci.inbound_id").
  319. Where("i.node_id IS NULL")).
  320. Find(&traffics).Error
  321. if err != nil {
  322. return false, 0, err
  323. }
  324. // return if there is no client to renew
  325. if len(traffics) == 0 {
  326. return false, 0, nil
  327. }
  328. renewLocation, locErr := (&SettingService{}).GetTimeLocation()
  329. if locErr != nil || renewLocation == nil {
  330. // Falling back to UTC keeps renewals happening; the alternative is
  331. // skipping them entirely because a setting could not be read.
  332. logger.Warning("autoRenewClients: could not read the panel time zone, using UTC:", locErr)
  333. renewLocation = time.UTC
  334. }
  335. var inbound_ids []int
  336. var inbounds []*model.Inbound
  337. needRestart := false
  338. type inboundClientKey struct {
  339. inboundID int
  340. email string
  341. }
  342. var clientsToAdd []struct {
  343. inbound model.Inbound
  344. client map[string]any
  345. }
  346. clientsToAddSet := make(map[inboundClientKey]struct{})
  347. // Resolve the inbounds to renew through the client_inbounds link rather than
  348. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  349. // recreated and would otherwise skip the renew entirely.
  350. renewEmails := make([]string, 0, len(traffics))
  351. for _, traffic := range traffics {
  352. renewEmails = append(renewEmails, traffic.Email)
  353. }
  354. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  355. var ids []int
  356. if err = tx.Table("client_inbounds").
  357. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  358. Where("clients.email IN ?", batch).
  359. Distinct().
  360. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  361. return false, 0, err
  362. }
  363. inbound_ids = append(inbound_ids, ids...)
  364. }
  365. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  366. // per tick instead of N times across chunk boundaries.
  367. inbound_ids = uniqueInts(inbound_ids)
  368. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  369. // are touched in a single tick.
  370. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  371. var page []*model.Inbound
  372. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  373. return false, 0, err
  374. }
  375. inbounds = append(inbounds, page...)
  376. }
  377. // Index the expired traffics by email so each client is an O(1) lookup
  378. // instead of a linear scan of every expired row (O(clients × expired) per
  379. // inbound, quadratic at scale). Pointers keep the in-place mutation below.
  380. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  381. // Keep the pre-renewal quota state: the shared pointer becomes enabled while
  382. // processing the first inbound, while an already-enabled row paired with
  383. // disabled settings represents an operator-disabled client we must preserve.
  384. trafficWasEnabled := make(map[string]bool, len(traffics))
  385. for i := range traffics {
  386. trafficByEmail[traffics[i].Email] = traffics[i]
  387. trafficWasEnabled[traffics[i].Email] = traffics[i].Enable
  388. }
  389. renewedEmails := make([]string, 0, len(traffics))
  390. for inbound_index := range inbounds {
  391. settings := map[string]any{}
  392. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  393. clients, _ := settings["clients"].([]any)
  394. if len(clients) == 0 {
  395. continue
  396. }
  397. cipher := ""
  398. if inbounds[inbound_index].Protocol == model.Shadowsocks {
  399. cipher, _ = settings["method"].(string)
  400. }
  401. for client_index := range clients {
  402. c := clients[client_index].(map[string]any)
  403. email, _ := c["email"].(string)
  404. traffic, ok := trafficByEmail[email]
  405. if !ok {
  406. continue
  407. }
  408. // One allowance per period, not per tick: a client away for three
  409. // cycles must not catch up three of them against a prepaid cap.
  410. newExpiryTime := traffic.ExpiryTime
  411. if traffic.ResetDay <= 0 && traffic.Reset <= 0 {
  412. // Unreachable while the selection filter holds: a zero step below
  413. // would spin forever on the single traffic writer and hang the panel.
  414. continue
  415. }
  416. at := time.UnixMilli(newExpiryTime)
  417. // Inclusive end-of-day expiries share the next billing midnight; snap without
  418. // spending an allowance so the first charged step is a full month (#6300).
  419. if traffic.ResetDay > 0 {
  420. boundary := nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
  421. if !at.Before(boundary.Add(-time.Second)) && at.Before(boundary) {
  422. at = boundary
  423. newExpiryTime = at.UnixMilli()
  424. }
  425. }
  426. renewals := 0
  427. for newExpiryTime < now {
  428. if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
  429. break
  430. }
  431. if traffic.ResetDay > 0 {
  432. // Calendar mode: step whole months in the panel's zone, so the
  433. // renewal date does not drift the way a fixed 30-day step does.
  434. at = nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
  435. newExpiryTime = at.UnixMilli()
  436. } else {
  437. newExpiryTime += (int64(traffic.Reset) * 86400000)
  438. }
  439. renewals++
  440. }
  441. if renewals > 0 {
  442. traffic.ExpiryTime = newExpiryTime
  443. traffic.ResetCount += renewals
  444. }
  445. c["expiryTime"] = traffic.ExpiryTime
  446. if traffic.ExpiryTime <= now {
  447. // Cap ran out mid-catch-up and the client is still expired: enabling it
  448. // for disableInvalidClients to undo adds and removes an xray user for nothing.
  449. clients[client_index] = any(c)
  450. continue
  451. }
  452. if renewals > 0 {
  453. traffic.Down = 0
  454. traffic.Up = 0
  455. renewedEmails = append(renewedEmails, email)
  456. }
  457. if !trafficWasEnabled[email] {
  458. traffic.Enable = true
  459. c["enable"] = true
  460. key := inboundClientKey{inboundID: inbounds[inbound_index].Id, email: email}
  461. if _, planned := clientsToAddSet[key]; !planned {
  462. clientsToAddSet[key] = struct{}{}
  463. clientsToAdd = append(clientsToAdd,
  464. struct {
  465. inbound model.Inbound
  466. client map[string]any
  467. }{
  468. inbound: *inbounds[inbound_index],
  469. client: apiUserFromClient(c, cipher),
  470. })
  471. }
  472. }
  473. clients[client_index] = any(c)
  474. }
  475. settings["clients"] = clients
  476. newSettings, err := json.MarshalIndent(settings, "", " ")
  477. if err != nil {
  478. return false, 0, err
  479. }
  480. inbounds[inbound_index].Settings = string(newSettings)
  481. }
  482. err = tx.Save(inbounds).Error
  483. if err != nil {
  484. return false, 0, err
  485. }
  486. for _, ib := range inbounds {
  487. if ib == nil {
  488. continue
  489. }
  490. cs, gcErr := s.GetClients(ib)
  491. if gcErr != nil {
  492. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  493. continue
  494. }
  495. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  496. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  497. }
  498. }
  499. err = tx.Save(traffics).Error
  500. if err != nil {
  501. return false, 0, err
  502. }
  503. // A renewed client starts a fresh quota window: drop the cross-panel rows
  504. // too, or the stale pushed totals would re-deplete it immediately.
  505. if err = clearGlobalTraffic(tx, renewedEmails...); err != nil {
  506. return false, 0, err
  507. }
  508. for _, clientToAdd := range clientsToAdd {
  509. if clientToAdd.inbound.NodeID != nil {
  510. mutationBatch.addNode(*clientToAdd.inbound.NodeID)
  511. continue
  512. }
  513. mutationBatch.localPlans = append(mutationBatch.localPlans, trafficLocalApplyPlan{
  514. action: trafficAddUser, inbound: clientToAdd.inbound, client: clientToAdd.client,
  515. })
  516. }
  517. return needRestart, int64(len(renewedEmails)), nil
  518. }
  519. // AddClientStat inserts a per-client accounting row, or refreshes the
  520. // config-derived columns on an email conflict. Xray reports traffic per
  521. // email, so the surviving row also acts as the shared accumulator for
  522. // inbounds that re-use the same identity — every call for that identity
  523. // (one per attached inbound) carries the same enable/expiry/reset/total,
  524. // so re-asserting them here is idempotent for that legitimate case.
  525. //
  526. // The conflict path matters on its own for a second reason: an inbound
  527. // delete detaches its clients (InboundService.DelInbound) without deleting
  528. // their client_traffics row, by design — mirroring ClientService.Detach,
  529. // which intentionally leaves a fully-detached client's row in place so a
  530. // later Attach can resume it with its accumulated traffic intact. If that
  531. // same email is instead reused for a freshly (re)created client, the new
  532. // config's enable/expiry/reset/total must win over whatever the orphaned
  533. // row still holds; DoNothing left them stale indefinitely (#5958).
  534. //
  535. // up/down are deliberately excluded from the refresh: they are the
  536. // accumulated traffic totals, and zeroing them here would erase real usage
  537. // every time an existing, actively-used client is attached to one more
  538. // inbound. One tradeoff this does not resolve: a genuinely new client that
  539. // happens to reuse an orphaned email still inherits that row's leftover
  540. // up/down, since nothing at this call site can tell the two cases apart.
  541. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  542. clientTraffic := xray.ClientTraffic{
  543. InboundId: inboundId,
  544. Email: client.Email,
  545. Total: client.TotalGB,
  546. ExpiryTime: client.ExpiryTime,
  547. Enable: client.Enable,
  548. Reset: client.Reset,
  549. ResetDay: client.ResetDay,
  550. ResetMax: client.ResetMax,
  551. }
  552. return tx.Clauses(clause.OnConflict{
  553. Columns: []clause.Column{{Name: "email"}},
  554. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_max"}),
  555. }).Create(&clientTraffic).Error
  556. }
  557. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  558. result := tx.Model(xray.ClientTraffic{}).
  559. Where("email = ?", email).
  560. Updates(map[string]any{
  561. "enable": client.Enable,
  562. "email": client.Email,
  563. "total": client.TotalGB,
  564. "expiry_time": client.ExpiryTime,
  565. "reset": client.Reset,
  566. "reset_day": client.ResetDay,
  567. "reset_max": client.ResetMax,
  568. })
  569. err := result.Error
  570. return err
  571. }
  572. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  573. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  574. return err
  575. }
  576. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  577. return err
  578. }
  579. if err := clearGlobalTraffic(tx, email); err != nil {
  580. return err
  581. }
  582. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  583. }
  584. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  585. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  586. return err
  587. }
  588. const chunk = 400
  589. for start := 0; start < len(emails); start += chunk {
  590. end := min(start+chunk, len(emails))
  591. batch := emails[start:end]
  592. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  593. return err
  594. }
  595. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  596. return err
  597. }
  598. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  599. return err
  600. }
  601. }
  602. return nil
  603. }
  604. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  605. err := submitTrafficWrite(func() error {
  606. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  607. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  608. return err
  609. }
  610. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  611. return err
  612. }
  613. if err := tx.Model(xray.ClientTraffic{}).
  614. Where("email = ?", clientEmail).
  615. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  616. return err
  617. }
  618. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  619. })
  620. })
  621. if err == nil {
  622. s.resetMtprotoClientQuota(clientEmail)
  623. }
  624. return err
  625. }
  626. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  627. var resetInbound *model.Inbound
  628. err = submitTrafficWrite(func() error {
  629. var inner error
  630. needRestart, resetInbound, inner = s.resetClientTrafficLocked(id, clientEmail)
  631. return inner
  632. })
  633. if err == nil {
  634. s.resetMtprotoClientQuota(clientEmail)
  635. if resetInbound != nil && resetInbound.NodeID != nil {
  636. // Attempted whatever the node's status: nothing replays a reset, so a
  637. // node still serving after being marked offline must get it now.
  638. if rt, rterr := s.runtimeFor(resetInbound); rterr != nil {
  639. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  640. } else {
  641. ctx, cancel := nodePushContext()
  642. e := rt.ResetClientTraffic(ctx, resetInbound, clientEmail)
  643. cancel()
  644. if e != nil {
  645. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  646. }
  647. }
  648. }
  649. }
  650. return
  651. }
  652. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, *model.Inbound, error) {
  653. needRestart := false
  654. var reenablePlan *trafficLocalApplyPlan
  655. var reenableNodeID *int
  656. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  657. if err != nil {
  658. return false, nil, err
  659. }
  660. if !traffic.Enable {
  661. inbound, err := s.GetInbound(id)
  662. if err != nil {
  663. return false, nil, err
  664. }
  665. clients, err := s.GetClients(inbound)
  666. if err != nil {
  667. return false, nil, err
  668. }
  669. for _, client := range clients {
  670. if client.Email == clientEmail && client.Enable {
  671. cipher := ""
  672. if string(inbound.Protocol) == "shadowsocks" {
  673. var oldSettings map[string]any
  674. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  675. if err != nil {
  676. return false, nil, err
  677. }
  678. cipher, _ = oldSettings["method"].(string)
  679. }
  680. clientMap := map[string]any{
  681. "email": client.Email,
  682. "id": client.ID,
  683. "auth": client.Auth,
  684. "security": client.Security,
  685. "flow": client.Flow,
  686. "password": client.Password,
  687. "cipher": cipher,
  688. "reverse": client.Reverse,
  689. }
  690. if inbound.NodeID != nil {
  691. reenableNodeID = inbound.NodeID
  692. } else {
  693. reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap}
  694. }
  695. break
  696. }
  697. }
  698. }
  699. traffic.Up = 0
  700. traffic.Down = 0
  701. traffic.Enable = true
  702. db := database.GetDB()
  703. now := time.Now().UnixMilli()
  704. inbound, err := s.GetInbound(id)
  705. if err != nil {
  706. return false, nil, err
  707. }
  708. if err := db.Transaction(func(tx *gorm.DB) error {
  709. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  710. return err
  711. }
  712. if err := tx.Save(traffic).Error; err != nil {
  713. return err
  714. }
  715. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  716. return err
  717. }
  718. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  719. return err
  720. }
  721. if err := tx.Model(model.Inbound{}).
  722. Where("id = ?", id).
  723. Update("last_traffic_reset_time", now).Error; err != nil {
  724. return err
  725. }
  726. if reenableNodeID != nil {
  727. return (&NodeService{}).MarkNodeDirtyTx(tx, *reenableNodeID)
  728. }
  729. if inbound != nil && inbound.NodeID != nil {
  730. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  731. }
  732. return nil
  733. }); err != nil {
  734. return false, nil, err
  735. }
  736. if reenablePlan != nil {
  737. rt, err := s.runtimeFor(&reenablePlan.inbound)
  738. if err != nil {
  739. needRestart = true
  740. } else if err := rt.AddUser(context.Background(), &reenablePlan.inbound, reenablePlan.client); err != nil {
  741. logger.Debug("Error in enabling client on", rt.Name(), ":", err)
  742. needRestart = true
  743. } else {
  744. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  745. }
  746. }
  747. return needRestart, inbound, nil
  748. }
  749. func (s *InboundService) ResetAllTraffics() error {
  750. err := submitTrafficWrite(func() error {
  751. return s.resetAllTrafficsLocked()
  752. })
  753. if err == nil {
  754. s.propagateResetAllTrafficsToNodes()
  755. s.resetAllMtprotoQuotas()
  756. }
  757. return err
  758. }
  759. func (s *InboundService) resetAllTrafficsLocked() error {
  760. db := database.GetDB()
  761. now := time.Now().UnixMilli()
  762. return db.Model(model.Inbound{}).
  763. Where("user_id > ?", 0).
  764. Updates(map[string]any{
  765. "up": 0,
  766. "down": 0,
  767. "last_traffic_reset_time": now,
  768. }).Error
  769. }
  770. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  771. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  772. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  773. // stalls traffic accounting and drops the deltas of every concurrent poll.
  774. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  775. nodes, err := (&NodeService{}).GetAll()
  776. if err != nil {
  777. return
  778. }
  779. for _, node := range nodes {
  780. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  781. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  782. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  783. }
  784. }
  785. }
  786. }
  787. func (s *InboundService) ResetInboundTraffic(id int) error {
  788. var inbound *model.Inbound
  789. if err := submitTrafficWrite(func() error {
  790. db := database.GetDB()
  791. if err := db.Model(model.Inbound{}).
  792. Where("id = ?", id).
  793. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  794. return err
  795. }
  796. var err error
  797. inbound, err = s.GetInbound(id)
  798. if err != nil {
  799. return err
  800. }
  801. return nil
  802. }); err != nil {
  803. return err
  804. }
  805. if inbound != nil && inbound.NodeID != nil {
  806. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  807. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  808. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  809. }
  810. } else {
  811. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  812. }
  813. }
  814. return nil
  815. }
  816. func (s *InboundService) DelDepletedClients(id int) (err error) {
  817. db := database.GetDB()
  818. var deletedInbounds []model.Inbound
  819. err = db.Transaction(func(tx *gorm.DB) error {
  820. // Collect depleted emails globally — a shared-email row owned by one
  821. // inbound depletes every sibling that lists the email.
  822. now := time.Now().Unix() * 1000
  823. depletedClause := depletedClientsClause
  824. var depletedRows []xray.ClientTraffic
  825. if err := tx.Model(xray.ClientTraffic{}).
  826. Where(depletedClause, now).
  827. Find(&depletedRows).Error; err != nil {
  828. return err
  829. }
  830. if len(depletedRows) == 0 {
  831. return nil
  832. }
  833. depletedEmails := make(map[string]struct{}, len(depletedRows))
  834. for _, r := range depletedRows {
  835. if r.Email == "" {
  836. continue
  837. }
  838. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  839. }
  840. if len(depletedEmails) == 0 {
  841. return nil
  842. }
  843. var inbounds []*model.Inbound
  844. inboundQuery := tx.Model(model.Inbound{})
  845. if id >= 0 {
  846. inboundQuery = inboundQuery.Where("id = ?", id)
  847. }
  848. if err := inboundQuery.Find(&inbounds).Error; err != nil {
  849. return err
  850. }
  851. for _, inbound := range inbounds {
  852. var settings map[string]any
  853. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  854. return err
  855. }
  856. rawClients, ok := settings["clients"].([]any)
  857. if !ok {
  858. continue
  859. }
  860. newClients := make([]any, 0, len(rawClients))
  861. removed := 0
  862. for _, client := range rawClients {
  863. c, ok := client.(map[string]any)
  864. if !ok {
  865. newClients = append(newClients, client)
  866. continue
  867. }
  868. email, _ := c["email"].(string)
  869. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  870. removed++
  871. continue
  872. }
  873. newClients = append(newClients, client)
  874. }
  875. if removed == 0 {
  876. continue
  877. }
  878. if len(newClients) == 0 {
  879. deletedInbounds = append(deletedInbounds, *inbound)
  880. if err := s.clientService.DetachInbound(tx, inbound.Id); err != nil {
  881. return err
  882. }
  883. if err := tx.Where("inbound_id = ?", inbound.Id).Delete(&model.Host{}).Error; err != nil {
  884. return err
  885. }
  886. if err := tx.Delete(model.Inbound{}, inbound.Id).Error; err != nil {
  887. return err
  888. }
  889. if inbound.NodeID != nil {
  890. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  891. return err
  892. }
  893. }
  894. continue
  895. }
  896. settings["clients"] = newClients
  897. ns, mErr := json.MarshalIndent(settings, "", " ")
  898. if mErr != nil {
  899. return mErr
  900. }
  901. inbound.Settings = string(ns)
  902. if err := tx.Save(inbound).Error; err != nil {
  903. return err
  904. }
  905. survivingClients, gcErr := s.GetClients(inbound)
  906. if gcErr != nil {
  907. return gcErr
  908. }
  909. if err := s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  910. return err
  911. }
  912. if inbound.NodeID != nil {
  913. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  914. return err
  915. }
  916. }
  917. }
  918. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  919. // no out-of-scope inbound still references the email.
  920. if id < 0 {
  921. return tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  922. }
  923. emails := make([]string, 0, len(depletedEmails))
  924. for e := range depletedEmails {
  925. emails = append(emails, e)
  926. }
  927. var stillReferenced []string
  928. emailExpr := database.JSONFieldText("client.value", "email")
  929. stillQuery := fmt.Sprintf(
  930. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  931. emailExpr,
  932. database.JSONClientsFromInbound(),
  933. emailExpr,
  934. )
  935. if err := tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  936. return err
  937. }
  938. stillSet := make(map[string]struct{}, len(stillReferenced))
  939. for _, e := range stillReferenced {
  940. stillSet[e] = struct{}{}
  941. }
  942. toDelete := make([]string, 0, len(emails))
  943. for _, e := range emails {
  944. if _, kept := stillSet[e]; !kept {
  945. toDelete = append(toDelete, e)
  946. }
  947. }
  948. if len(toDelete) > 0 {
  949. if err := tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  950. return err
  951. }
  952. }
  953. return nil
  954. })
  955. if err != nil {
  956. return err
  957. }
  958. for i := range deletedInbounds {
  959. inbound := &deletedInbounds[i]
  960. if rt, rtErr := s.runtimeFor(inbound); rtErr != nil {
  961. logger.Warning("DelDepletedClients: runtime lookup failed after commit:", rtErr)
  962. } else if rtErr = rt.DelInbound(context.Background(), inbound); rtErr != nil && !xray.IsMissingHandlerErr(rtErr) {
  963. logger.Warning("DelDepletedClients: runtime cleanup failed after commit:", rtErr)
  964. }
  965. if inbound.Tag != "" {
  966. if _, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(inbound.Tag); syncErr != nil {
  967. logger.Warning("DelDepletedClients: routing cleanup failed after commit:", syncErr)
  968. }
  969. }
  970. }
  971. return nil
  972. }
  973. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  974. db := database.GetDB()
  975. idQuery := fmt.Sprintf(
  976. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  977. database.JSONClientsFromInbound(),
  978. database.JSONFieldText("client.value", "tgId"),
  979. )
  980. var inboundIds []int
  981. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  982. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  983. return nil, err
  984. }
  985. var inbounds []*model.Inbound
  986. if len(inboundIds) > 0 {
  987. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  988. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  989. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  990. return nil, err
  991. }
  992. }
  993. var emails []string
  994. for _, inbound := range inbounds {
  995. clients, err := s.GetClients(inbound)
  996. if err != nil {
  997. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  998. continue
  999. }
  1000. for _, client := range clients {
  1001. if client.TgID == tgId {
  1002. emails = append(emails, client.Email)
  1003. }
  1004. }
  1005. }
  1006. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  1007. // account owns thousands of clients across inbounds.
  1008. uniqEmails := uniqueNonEmptyStrings(emails)
  1009. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  1010. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1011. var page []*xray.ClientTraffic
  1012. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  1013. if errors.Is(err, gorm.ErrRecordNotFound) {
  1014. continue
  1015. }
  1016. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  1017. return nil, err
  1018. }
  1019. traffics = append(traffics, page...)
  1020. }
  1021. if len(traffics) == 0 {
  1022. logger.Warning("No ClientTraffic records found for emails:", emails)
  1023. return nil, nil
  1024. }
  1025. // Populate UUID and other client data for each traffic record
  1026. for i := range traffics {
  1027. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1028. traffics[i].Enable = client.Enable
  1029. traffics[i].UUID = client.ID
  1030. traffics[i].SubId = client.SubID
  1031. }
  1032. }
  1033. return traffics, nil
  1034. }
  1035. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  1036. // emails. Used in online-API mode for clients that hold a live connection but
  1037. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  1038. // last_online on a non-zero delta, so idle-but-connected clients would
  1039. // otherwise show a stale "last online" while being reported online.
  1040. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  1041. uniq := uniqueNonEmptyStrings(emails)
  1042. if len(uniq) == 0 {
  1043. return nil
  1044. }
  1045. now := time.Now().UnixMilli()
  1046. return submitTrafficWrite(func() error {
  1047. db := database.GetDB()
  1048. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1049. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  1050. return err
  1051. }
  1052. }
  1053. return nil
  1054. })
  1055. }
  1056. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  1057. uniq := uniqueNonEmptyStrings(emails)
  1058. if len(uniq) == 0 {
  1059. return nil, nil
  1060. }
  1061. db := database.GetDB()
  1062. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  1063. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1064. var page []*xray.ClientTraffic
  1065. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  1066. return nil, err
  1067. }
  1068. traffics = append(traffics, page...)
  1069. }
  1070. overlayGlobalTraffic(db, traffics)
  1071. return traffics, nil
  1072. }
  1073. // GetAllClientTraffics returns the full set of client_traffics rows so the
  1074. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  1075. // delta path silently dropped the per-client section whenever no client moved
  1076. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  1077. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  1078. // above the traffic job's snapshot threshold (where the marshaled snapshot
  1079. // would exceed the hub's payload cap and be dropped wholesale) does the job
  1080. // fall back to active-row deltas.
  1081. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  1082. db := database.GetDB()
  1083. var traffics []*xray.ClientTraffic
  1084. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  1085. return nil, err
  1086. }
  1087. overlayGlobalTraffic(db, traffics)
  1088. return traffics, nil
  1089. }
  1090. func (s *InboundService) CountClientTraffics() (int64, error) {
  1091. db := database.GetDB()
  1092. var count int64
  1093. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  1094. return count, err
  1095. }
  1096. type InboundTrafficSummary struct {
  1097. Id int `json:"id" example:"1"`
  1098. Up int64 `json:"up" example:"1048576"`
  1099. Down int64 `json:"down" example:"2097152"`
  1100. Total int64 `json:"total" example:"10737418240"`
  1101. Enable bool `json:"enable" example:"true"`
  1102. }
  1103. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  1104. db := database.GetDB()
  1105. var summaries []InboundTrafficSummary
  1106. if err := db.Model(&model.Inbound{}).
  1107. Select("id, up, down, total, enable").
  1108. Find(&summaries).Error; err != nil {
  1109. return nil, err
  1110. }
  1111. return summaries, nil
  1112. }
  1113. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1114. db := database.GetDB()
  1115. var traffics []*xray.ClientTraffic
  1116. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  1117. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1118. return nil, err
  1119. }
  1120. if len(traffics) == 0 {
  1121. return nil, nil
  1122. }
  1123. overlayGlobalTraffic(db, traffics)
  1124. t := traffics[0]
  1125. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  1126. c := rec.ToClient()
  1127. t.UUID = c.ID
  1128. t.SubId = c.SubID
  1129. return t, nil
  1130. }
  1131. t2, client, err := s.GetClientByEmail(email)
  1132. if err != nil {
  1133. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1134. return nil, err
  1135. }
  1136. if t2 != nil && client != nil {
  1137. t2.UUID = client.ID
  1138. t2.SubId = client.SubID
  1139. return t2, nil
  1140. }
  1141. return nil, nil
  1142. }
  1143. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1144. return submitTrafficWrite(func() error {
  1145. db := database.GetDB()
  1146. err := db.Model(xray.ClientTraffic{}).
  1147. Where("email = ?", email).
  1148. Updates(map[string]any{
  1149. "up": upload,
  1150. "down": download,
  1151. }).Error
  1152. if err != nil {
  1153. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1154. }
  1155. return err
  1156. })
  1157. }
  1158. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1159. db := database.GetDB()
  1160. inbound := &model.Inbound{}
  1161. traffic = &xray.ClientTraffic{}
  1162. // Search for inbound settings that contain the query
  1163. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1164. if err != nil {
  1165. if errors.Is(err, gorm.ErrRecordNotFound) {
  1166. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1167. return nil, err
  1168. }
  1169. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1170. return nil, err
  1171. }
  1172. traffic.InboundId = inbound.Id
  1173. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1174. if err != nil {
  1175. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1176. return nil, err
  1177. }
  1178. for _, client := range clients {
  1179. if (client.ID == query || client.Password == query) && client.Email != "" {
  1180. traffic.Email = client.Email
  1181. break
  1182. }
  1183. }
  1184. if traffic.Email == "" {
  1185. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1186. return nil, gorm.ErrRecordNotFound
  1187. }
  1188. // Retrieve ClientTraffic based on the found email
  1189. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1190. if err != nil {
  1191. if errors.Is(err, gorm.ErrRecordNotFound) {
  1192. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1193. return nil, err
  1194. }
  1195. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1196. return nil, err
  1197. }
  1198. return traffic, nil
  1199. }