inbound_traffic.go 41 KB

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