inbound_traffic.go 42 KB

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