inbound_traffic.go 41 KB

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