inbound_traffic.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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 reset_weekday = 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 or reset_weekday > 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, renewals := catchUpClientRenewal(traffic, now, renewLocation)
  417. if renewals > 0 {
  418. traffic.ExpiryTime = newExpiryTime
  419. traffic.ResetCount += renewals
  420. }
  421. c["expiryTime"] = traffic.ExpiryTime
  422. if traffic.ExpiryTime <= now {
  423. // Cap ran out mid-catch-up and the client is still expired: enabling it
  424. // for disableInvalidClients to undo adds and removes an xray user for nothing.
  425. clients[client_index] = any(c)
  426. continue
  427. }
  428. if renewals > 0 {
  429. traffic.Down = 0
  430. traffic.Up = 0
  431. renewedEmails = append(renewedEmails, email)
  432. }
  433. if !trafficWasEnabled[email] {
  434. traffic.Enable = true
  435. c["enable"] = true
  436. key := inboundClientKey{inboundID: inbounds[inbound_index].Id, email: email}
  437. if _, planned := clientsToAddSet[key]; !planned {
  438. clientsToAddSet[key] = struct{}{}
  439. clientsToAdd = append(clientsToAdd,
  440. struct {
  441. inbound model.Inbound
  442. client map[string]any
  443. }{
  444. inbound: *inbounds[inbound_index],
  445. client: apiUserFromClient(c, cipher),
  446. })
  447. }
  448. }
  449. clients[client_index] = any(c)
  450. }
  451. settings["clients"] = clients
  452. newSettings, err := json.MarshalIndent(settings, "", " ")
  453. if err != nil {
  454. return false, 0, err
  455. }
  456. inbounds[inbound_index].Settings = string(newSettings)
  457. }
  458. err = tx.Save(inbounds).Error
  459. if err != nil {
  460. return false, 0, err
  461. }
  462. for _, ib := range inbounds {
  463. if ib == nil {
  464. continue
  465. }
  466. cs, gcErr := s.GetClients(ib)
  467. if gcErr != nil {
  468. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  469. continue
  470. }
  471. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  472. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  473. }
  474. }
  475. err = tx.Save(traffics).Error
  476. if err != nil {
  477. return false, 0, err
  478. }
  479. // A renewed client starts a fresh quota window: drop the cross-panel rows
  480. // too, or the stale pushed totals would re-deplete it immediately.
  481. if err = clearGlobalTraffic(tx, renewedEmails...); err != nil {
  482. return false, 0, err
  483. }
  484. for _, clientToAdd := range clientsToAdd {
  485. if clientToAdd.inbound.NodeID != nil {
  486. mutationBatch.addNode(*clientToAdd.inbound.NodeID)
  487. continue
  488. }
  489. mutationBatch.localPlans = append(mutationBatch.localPlans, trafficLocalApplyPlan{
  490. action: trafficAddUser, inbound: clientToAdd.inbound, client: clientToAdd.client,
  491. })
  492. }
  493. return needRestart, int64(len(renewedEmails)), nil
  494. }
  495. // AddClientStat inserts a per-client accounting row, or refreshes the
  496. // config-derived columns on an email conflict. Xray reports traffic per
  497. // email, so the surviving row also acts as the shared accumulator for
  498. // inbounds that re-use the same identity — every call for that identity
  499. // (one per attached inbound) carries the same enable/expiry/reset/total,
  500. // so re-asserting them here is idempotent for that legitimate case.
  501. //
  502. // The conflict path matters on its own for a second reason: an inbound
  503. // delete detaches its clients (InboundService.DelInbound) without deleting
  504. // their client_traffics row, by design — mirroring ClientService.Detach,
  505. // which intentionally leaves a fully-detached client's row in place so a
  506. // later Attach can resume it with its accumulated traffic intact. If that
  507. // same email is instead reused for a freshly (re)created client, the new
  508. // config's enable/expiry/reset/total must win over whatever the orphaned
  509. // row still holds; DoNothing left them stale indefinitely (#5958).
  510. //
  511. // up/down are deliberately excluded from the refresh: they are the
  512. // accumulated traffic totals, and zeroing them here would erase real usage
  513. // every time an existing, actively-used client is attached to one more
  514. // inbound. One tradeoff this does not resolve: a genuinely new client that
  515. // happens to reuse an orphaned email still inherits that row's leftover
  516. // up/down, since nothing at this call site can tell the two cases apart.
  517. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  518. if err := validateClientRenewal(*client); err != nil {
  519. return err
  520. }
  521. clientTraffic := xray.ClientTraffic{
  522. InboundId: inboundId,
  523. Email: client.Email,
  524. Total: client.TotalGB,
  525. ExpiryTime: client.ExpiryTime,
  526. Enable: client.Enable,
  527. Reset: client.Reset,
  528. ResetDay: client.ResetDay,
  529. ResetWeekday: client.ResetWeekday,
  530. ResetMax: client.ResetMax,
  531. }
  532. return tx.Clauses(clause.OnConflict{
  533. Columns: []clause.Column{{Name: "email"}},
  534. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_weekday", "reset_max"}),
  535. }).Create(&clientTraffic).Error
  536. }
  537. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  538. if err := validateClientRenewal(*client); err != nil {
  539. return err
  540. }
  541. result := tx.Model(xray.ClientTraffic{}).
  542. Where("email = ?", email).
  543. Updates(map[string]any{
  544. "enable": client.Enable,
  545. "email": client.Email,
  546. "total": client.TotalGB,
  547. "expiry_time": client.ExpiryTime,
  548. "reset": client.Reset,
  549. "reset_day": client.ResetDay,
  550. "reset_weekday": client.ResetWeekday,
  551. "reset_max": client.ResetMax,
  552. })
  553. err := result.Error
  554. return err
  555. }
  556. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  557. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  558. return err
  559. }
  560. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  561. return err
  562. }
  563. if err := clearGlobalTraffic(tx, email); err != nil {
  564. return err
  565. }
  566. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  567. }
  568. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  569. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  570. return err
  571. }
  572. const chunk = 400
  573. for start := 0; start < len(emails); start += chunk {
  574. end := min(start+chunk, len(emails))
  575. batch := emails[start:end]
  576. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  577. return err
  578. }
  579. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  580. return err
  581. }
  582. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  583. return err
  584. }
  585. }
  586. return nil
  587. }
  588. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  589. err := submitTrafficWrite(func() error {
  590. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  591. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  592. return err
  593. }
  594. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  595. return err
  596. }
  597. if err := tx.Model(xray.ClientTraffic{}).
  598. Where("email = ?", clientEmail).
  599. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  600. return err
  601. }
  602. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  603. })
  604. })
  605. if err == nil {
  606. s.resetMtprotoClientQuota(clientEmail)
  607. }
  608. return err
  609. }
  610. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  611. var resetInbound *model.Inbound
  612. err = submitTrafficWrite(func() error {
  613. var inner error
  614. needRestart, resetInbound, inner = s.resetClientTrafficLocked(id, clientEmail)
  615. return inner
  616. })
  617. if err == nil {
  618. s.resetMtprotoClientQuota(clientEmail)
  619. if resetInbound != nil && resetInbound.NodeID != nil {
  620. // Attempted whatever the node's status: nothing replays a reset, so a
  621. // node still serving after being marked offline must get it now.
  622. if rt, rterr := s.runtimeFor(resetInbound); rterr != nil {
  623. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  624. } else {
  625. ctx, cancel := nodePushContext()
  626. e := rt.ResetClientTraffic(ctx, resetInbound, clientEmail)
  627. cancel()
  628. if e != nil {
  629. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  630. }
  631. }
  632. }
  633. }
  634. return
  635. }
  636. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, *model.Inbound, error) {
  637. needRestart := false
  638. var reenablePlan *trafficLocalApplyPlan
  639. var reenableNodeID *int
  640. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  641. if err != nil {
  642. return false, nil, err
  643. }
  644. if !traffic.Enable {
  645. inbound, err := s.GetInbound(id)
  646. if err != nil {
  647. return false, nil, err
  648. }
  649. clients, err := s.GetClients(inbound)
  650. if err != nil {
  651. return false, nil, err
  652. }
  653. for _, client := range clients {
  654. if client.Email == clientEmail && client.Enable {
  655. cipher := ""
  656. if string(inbound.Protocol) == "shadowsocks" {
  657. var oldSettings map[string]any
  658. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  659. if err != nil {
  660. return false, nil, err
  661. }
  662. cipher, _ = oldSettings["method"].(string)
  663. }
  664. clientMap := map[string]any{
  665. "email": client.Email,
  666. "id": client.ID,
  667. "auth": client.Auth,
  668. "security": client.Security,
  669. "flow": client.Flow,
  670. "password": client.Password,
  671. "cipher": cipher,
  672. "reverse": client.Reverse,
  673. }
  674. if inbound.NodeID != nil {
  675. reenableNodeID = inbound.NodeID
  676. } else {
  677. reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap}
  678. }
  679. break
  680. }
  681. }
  682. }
  683. traffic.Up = 0
  684. traffic.Down = 0
  685. traffic.Enable = true
  686. db := database.GetDB()
  687. now := time.Now().UnixMilli()
  688. inbound, err := s.GetInbound(id)
  689. if err != nil {
  690. return false, nil, err
  691. }
  692. if err := db.Transaction(func(tx *gorm.DB) error {
  693. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  694. return err
  695. }
  696. if err := tx.Save(traffic).Error; err != nil {
  697. return err
  698. }
  699. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  700. return err
  701. }
  702. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  703. return err
  704. }
  705. if err := tx.Model(model.Inbound{}).
  706. Where("id = ?", id).
  707. Update("last_traffic_reset_time", now).Error; err != nil {
  708. return err
  709. }
  710. if reenableNodeID != nil {
  711. return (&NodeService{}).MarkNodeDirtyTx(tx, *reenableNodeID)
  712. }
  713. if inbound != nil && inbound.NodeID != nil {
  714. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  715. }
  716. return nil
  717. }); err != nil {
  718. return false, nil, err
  719. }
  720. if reenablePlan != nil {
  721. rt, err := s.runtimeFor(&reenablePlan.inbound)
  722. if err != nil {
  723. needRestart = true
  724. } else if err := rt.AddUser(context.Background(), &reenablePlan.inbound, reenablePlan.client); err != nil {
  725. logger.Debug("Error in enabling client on", rt.Name(), ":", err)
  726. needRestart = true
  727. } else {
  728. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  729. }
  730. }
  731. return needRestart, inbound, nil
  732. }
  733. func (s *InboundService) ResetAllTraffics() error {
  734. err := submitTrafficWrite(func() error {
  735. return s.resetAllTrafficsLocked()
  736. })
  737. if err == nil {
  738. s.propagateResetAllTrafficsToNodes()
  739. s.resetAllMtprotoQuotas()
  740. }
  741. return err
  742. }
  743. func (s *InboundService) resetAllTrafficsLocked() error {
  744. db := database.GetDB()
  745. now := time.Now().UnixMilli()
  746. return db.Model(model.Inbound{}).
  747. Where("user_id > ?", 0).
  748. Updates(map[string]any{
  749. "up": 0,
  750. "down": 0,
  751. "last_traffic_reset_time": now,
  752. }).Error
  753. }
  754. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  755. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  756. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  757. // stalls traffic accounting and drops the deltas of every concurrent poll.
  758. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  759. nodes, err := (&NodeService{}).GetAll()
  760. if err != nil {
  761. return
  762. }
  763. ids := make([]int, len(nodes))
  764. for i, node := range nodes {
  765. ids[i] = node.Id
  766. }
  767. fanoutInboundResults(ids, nodeFanoutConcurrency, func(i int) struct{} {
  768. if rt, err := runtime.GetManager().RuntimeFor(&ids[i]); err == nil {
  769. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  770. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  771. }
  772. }
  773. return struct{}{}
  774. })
  775. }
  776. func (s *InboundService) ResetInboundTraffic(id int) error {
  777. var inbound *model.Inbound
  778. if err := submitTrafficWrite(func() error {
  779. db := database.GetDB()
  780. if err := db.Model(model.Inbound{}).
  781. Where("id = ?", id).
  782. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  783. return err
  784. }
  785. var err error
  786. inbound, err = s.GetInbound(id)
  787. if err != nil {
  788. return err
  789. }
  790. return nil
  791. }); err != nil {
  792. return err
  793. }
  794. if inbound != nil && inbound.NodeID != nil {
  795. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  796. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  797. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  798. }
  799. } else {
  800. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  801. }
  802. }
  803. return nil
  804. }
  805. func (s *InboundService) DelDepletedClients(id int) (err error) {
  806. db := database.GetDB()
  807. var deletedInbounds []model.Inbound
  808. err = db.Transaction(func(tx *gorm.DB) error {
  809. // Collect depleted emails globally — a shared-email row owned by one
  810. // inbound depletes every sibling that lists the email.
  811. now := time.Now().Unix() * 1000
  812. depletedClause := depletedClientsClause
  813. var depletedRows []xray.ClientTraffic
  814. if err := tx.Model(xray.ClientTraffic{}).
  815. Where(depletedClause, now).
  816. Find(&depletedRows).Error; err != nil {
  817. return err
  818. }
  819. if len(depletedRows) == 0 {
  820. return nil
  821. }
  822. depletedEmails := make(map[string]struct{}, len(depletedRows))
  823. for _, r := range depletedRows {
  824. if r.Email == "" {
  825. continue
  826. }
  827. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  828. }
  829. if len(depletedEmails) == 0 {
  830. return nil
  831. }
  832. var inbounds []*model.Inbound
  833. inboundQuery := tx.Model(model.Inbound{})
  834. if id >= 0 {
  835. inboundQuery = inboundQuery.Where("id = ?", id)
  836. }
  837. if err := inboundQuery.Find(&inbounds).Error; err != nil {
  838. return err
  839. }
  840. for _, inbound := range inbounds {
  841. var settings map[string]any
  842. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  843. return err
  844. }
  845. rawClients, ok := settings["clients"].([]any)
  846. if !ok {
  847. continue
  848. }
  849. newClients := make([]any, 0, len(rawClients))
  850. removed := 0
  851. for _, client := range rawClients {
  852. c, ok := client.(map[string]any)
  853. if !ok {
  854. newClients = append(newClients, client)
  855. continue
  856. }
  857. email, _ := c["email"].(string)
  858. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  859. removed++
  860. continue
  861. }
  862. newClients = append(newClients, client)
  863. }
  864. if removed == 0 {
  865. continue
  866. }
  867. if len(newClients) == 0 {
  868. deletedInbounds = append(deletedInbounds, *inbound)
  869. if err := s.clientService.DetachInbound(tx, inbound.Id); err != nil {
  870. return err
  871. }
  872. if err := tx.Where("inbound_id = ?", inbound.Id).Delete(&model.Host{}).Error; err != nil {
  873. return err
  874. }
  875. if err := tx.Delete(model.Inbound{}, inbound.Id).Error; err != nil {
  876. return err
  877. }
  878. if inbound.NodeID != nil {
  879. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  880. return err
  881. }
  882. }
  883. continue
  884. }
  885. settings["clients"] = newClients
  886. ns, mErr := json.MarshalIndent(settings, "", " ")
  887. if mErr != nil {
  888. return mErr
  889. }
  890. inbound.Settings = string(ns)
  891. if err := tx.Save(inbound).Error; err != nil {
  892. return err
  893. }
  894. survivingClients, gcErr := s.GetClients(inbound)
  895. if gcErr != nil {
  896. return gcErr
  897. }
  898. if err := s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  899. return err
  900. }
  901. if inbound.NodeID != nil {
  902. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil {
  903. return err
  904. }
  905. }
  906. }
  907. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  908. // no out-of-scope inbound still references the email.
  909. if id < 0 {
  910. return tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  911. }
  912. emails := make([]string, 0, len(depletedEmails))
  913. for e := range depletedEmails {
  914. emails = append(emails, e)
  915. }
  916. var stillReferenced []string
  917. emailExpr := database.JSONFieldText("client.value", "email")
  918. stillQuery := fmt.Sprintf(
  919. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  920. emailExpr,
  921. database.JSONClientsFromInbound(),
  922. emailExpr,
  923. )
  924. if err := tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  925. return err
  926. }
  927. stillSet := make(map[string]struct{}, len(stillReferenced))
  928. for _, e := range stillReferenced {
  929. stillSet[e] = struct{}{}
  930. }
  931. toDelete := make([]string, 0, len(emails))
  932. for _, e := range emails {
  933. if _, kept := stillSet[e]; !kept {
  934. toDelete = append(toDelete, e)
  935. }
  936. }
  937. if len(toDelete) > 0 {
  938. if err := tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  939. return err
  940. }
  941. }
  942. return nil
  943. })
  944. if err != nil {
  945. return err
  946. }
  947. for i := range deletedInbounds {
  948. inbound := &deletedInbounds[i]
  949. if rt, rtErr := s.runtimeFor(inbound); rtErr != nil {
  950. logger.Warning("DelDepletedClients: runtime lookup failed after commit:", rtErr)
  951. } else if rtErr = rt.DelInbound(context.Background(), inbound); rtErr != nil && !xray.IsMissingHandlerErr(rtErr) {
  952. logger.Warning("DelDepletedClients: runtime cleanup failed after commit:", rtErr)
  953. }
  954. if inbound.Tag != "" {
  955. if _, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(inbound.Tag); syncErr != nil {
  956. logger.Warning("DelDepletedClients: routing cleanup failed after commit:", syncErr)
  957. }
  958. }
  959. }
  960. return nil
  961. }
  962. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  963. db := database.GetDB()
  964. idQuery := fmt.Sprintf(
  965. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  966. database.JSONClientsFromInbound(),
  967. database.JSONFieldText("client.value", "tgId"),
  968. )
  969. var inboundIds []int
  970. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  971. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  972. return nil, err
  973. }
  974. var inbounds []*model.Inbound
  975. if len(inboundIds) > 0 {
  976. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  977. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  978. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  979. return nil, err
  980. }
  981. }
  982. var emails []string
  983. for _, inbound := range inbounds {
  984. clients, err := s.GetClients(inbound)
  985. if err != nil {
  986. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  987. continue
  988. }
  989. for _, client := range clients {
  990. if client.TgID == tgId {
  991. emails = append(emails, client.Email)
  992. }
  993. }
  994. }
  995. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  996. // account owns thousands of clients across inbounds.
  997. uniqEmails := uniqueNonEmptyStrings(emails)
  998. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  999. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1000. var page []*xray.ClientTraffic
  1001. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  1002. if errors.Is(err, gorm.ErrRecordNotFound) {
  1003. continue
  1004. }
  1005. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  1006. return nil, err
  1007. }
  1008. traffics = append(traffics, page...)
  1009. }
  1010. if len(traffics) == 0 {
  1011. logger.Warning("No ClientTraffic records found for emails:", emails)
  1012. return nil, nil
  1013. }
  1014. // Populate UUID and other client data for each traffic record
  1015. for i := range traffics {
  1016. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1017. traffics[i].Enable = client.Enable
  1018. traffics[i].UUID = client.ID
  1019. traffics[i].SubId = client.SubID
  1020. }
  1021. }
  1022. return traffics, nil
  1023. }
  1024. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  1025. // emails. Used in online-API mode for clients that hold a live connection but
  1026. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  1027. // last_online on a non-zero delta, so idle-but-connected clients would
  1028. // otherwise show a stale "last online" while being reported online.
  1029. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  1030. uniq := uniqueNonEmptyStrings(emails)
  1031. if len(uniq) == 0 {
  1032. return nil
  1033. }
  1034. now := time.Now().UnixMilli()
  1035. return submitTrafficWrite(func() error {
  1036. db := database.GetDB()
  1037. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1038. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  1039. return err
  1040. }
  1041. }
  1042. return nil
  1043. })
  1044. }
  1045. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  1046. uniq := uniqueNonEmptyStrings(emails)
  1047. if len(uniq) == 0 {
  1048. return nil, nil
  1049. }
  1050. db := database.GetDB()
  1051. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  1052. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  1053. var page []*xray.ClientTraffic
  1054. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  1055. return nil, err
  1056. }
  1057. traffics = append(traffics, page...)
  1058. }
  1059. overlayGlobalTraffic(db, traffics)
  1060. return traffics, nil
  1061. }
  1062. // GetAllClientTraffics returns the full set of client_traffics rows so the
  1063. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  1064. // delta path silently dropped the per-client section whenever no client moved
  1065. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  1066. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  1067. // above the traffic job's snapshot threshold (where the marshaled snapshot
  1068. // would exceed the hub's payload cap and be dropped wholesale) does the job
  1069. // fall back to active-row deltas.
  1070. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  1071. db := database.GetDB()
  1072. var traffics []*xray.ClientTraffic
  1073. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  1074. return nil, err
  1075. }
  1076. overlayGlobalTraffic(db, traffics)
  1077. return traffics, nil
  1078. }
  1079. func (s *InboundService) CountClientTraffics() (int64, error) {
  1080. db := database.GetDB()
  1081. var count int64
  1082. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  1083. return count, err
  1084. }
  1085. type InboundTrafficSummary struct {
  1086. Id int `json:"id" example:"1"`
  1087. Up int64 `json:"up" example:"1048576"`
  1088. Down int64 `json:"down" example:"2097152"`
  1089. Total int64 `json:"total" example:"10737418240"`
  1090. Enable bool `json:"enable" example:"true"`
  1091. }
  1092. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  1093. db := database.GetDB()
  1094. var summaries []InboundTrafficSummary
  1095. if err := db.Model(&model.Inbound{}).
  1096. Select("id, up, down, total, enable").
  1097. Find(&summaries).Error; err != nil {
  1098. return nil, err
  1099. }
  1100. return summaries, nil
  1101. }
  1102. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1103. db := database.GetDB()
  1104. var traffics []*xray.ClientTraffic
  1105. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  1106. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1107. return nil, err
  1108. }
  1109. if len(traffics) == 0 {
  1110. return nil, nil
  1111. }
  1112. overlayGlobalTraffic(db, traffics)
  1113. t := traffics[0]
  1114. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  1115. c := rec.ToClient()
  1116. t.UUID = c.ID
  1117. t.SubId = c.SubID
  1118. return t, nil
  1119. }
  1120. t2, client, err := s.GetClientByEmail(email)
  1121. if err != nil {
  1122. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1123. return nil, err
  1124. }
  1125. if t2 != nil && client != nil {
  1126. t2.UUID = client.ID
  1127. t2.SubId = client.SubID
  1128. return t2, nil
  1129. }
  1130. return nil, nil
  1131. }
  1132. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1133. return submitTrafficWrite(func() error {
  1134. db := database.GetDB()
  1135. err := db.Model(xray.ClientTraffic{}).
  1136. Where("email = ?", email).
  1137. Updates(map[string]any{
  1138. "up": upload,
  1139. "down": download,
  1140. }).Error
  1141. if err != nil {
  1142. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1143. }
  1144. return err
  1145. })
  1146. }
  1147. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1148. db := database.GetDB()
  1149. inbound := &model.Inbound{}
  1150. traffic = &xray.ClientTraffic{}
  1151. // Search for inbound settings that contain the query
  1152. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1153. if err != nil {
  1154. if errors.Is(err, gorm.ErrRecordNotFound) {
  1155. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1156. return nil, err
  1157. }
  1158. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1159. return nil, err
  1160. }
  1161. traffic.InboundId = inbound.Id
  1162. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1163. if err != nil {
  1164. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1165. return nil, err
  1166. }
  1167. for _, client := range clients {
  1168. if (client.ID == query || client.Password == query) && client.Email != "" {
  1169. traffic.Email = client.Email
  1170. break
  1171. }
  1172. }
  1173. if traffic.Email == "" {
  1174. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1175. return nil, gorm.ErrRecordNotFound
  1176. }
  1177. // Retrieve ClientTraffic based on the found email
  1178. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1179. if err != nil {
  1180. if errors.Is(err, gorm.ErrRecordNotFound) {
  1181. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1182. return nil, err
  1183. }
  1184. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1185. return nil, err
  1186. }
  1187. return traffic, nil
  1188. }