inbound_traffic.go 42 KB

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