inbound_traffic.go 42 KB

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