inbound_node.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  14. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. "gorm.io/gorm/clause"
  18. )
  19. var reportedRemoteTagConflict sync.Map
  20. var reportedForeignClientClaim sync.Map
  21. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  22. // stream to a remote node. Above it, the panel marks the node dirty instead and
  23. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  24. // sequential round-trips. Small ops stay on the live per-client path.
  25. const nodeBulkPushThreshold = 32
  26. // nodeClientPushTimeout bounds the synchronous per-client push: the change is
  27. // committed and the node flagged dirty, so a slow node defers to the reconcile.
  28. const nodeClientPushTimeout = 4 * time.Second
  29. // nodeFanoutConcurrency bounds an operation that calls every node, as the heartbeat
  30. // does: one at a time, a few hanging nodes outlast the request's write timeout.
  31. const nodeFanoutConcurrency = 32
  32. func nodePushContext() (context.Context, context.CancelFunc) {
  33. return context.WithTimeout(context.Background(), nodeClientPushTimeout)
  34. }
  35. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  36. mgr := runtime.GetManager()
  37. if mgr == nil {
  38. return nil, fmt.Errorf("runtime manager not initialised")
  39. }
  40. return mgr.RuntimeFor(ib.NodeID)
  41. }
  42. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  43. if ib.NodeID == nil {
  44. rt, err := s.runtimeFor(ib)
  45. if err != nil {
  46. return nil, false, false, nil
  47. }
  48. return rt, true, false, nil
  49. }
  50. nodeSvc := NodeService{}
  51. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  52. if err != nil {
  53. return nil, false, false, err
  54. }
  55. if !enabled || status == "offline" {
  56. return nil, false, true, nil
  57. }
  58. rt, err := s.runtimeFor(ib)
  59. if err != nil {
  60. return nil, false, true, nil
  61. }
  62. return rt, true, false, nil
  63. }
  64. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  65. if nodeID == nil {
  66. return false
  67. }
  68. return (&NodeService{}).IsNodePending(*nodeID)
  69. }
  70. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  71. if len(inboundIds) == 0 {
  72. return false
  73. }
  74. nodeSvc := NodeService{}
  75. for _, id := range inboundIds {
  76. ib, err := s.GetInbound(id)
  77. if err != nil || ib.NodeID == nil {
  78. continue
  79. }
  80. if nodeSvc.IsNodePending(*ib.NodeID) {
  81. return true
  82. }
  83. }
  84. return false
  85. }
  86. // ReconcileNode pushes every inbound and sweeps undesired remote tags even when
  87. // individual operations fail, returning the failures joined: one inbound the
  88. // node rejects (e.g. a legacy protocol failing validation, #5685) must not
  89. // stall the rest of the node's config — or, via syncOne, its traffic sync.
  90. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  91. if rt == nil || n == nil || n.Id <= 0 {
  92. return nil
  93. }
  94. nodeID := n.Id
  95. db := database.GetDB()
  96. var inbounds []*model.Inbound
  97. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  98. return err
  99. }
  100. remoteInbounds, err := rt.ListInboundOptions(ctx)
  101. if err != nil {
  102. return err
  103. }
  104. remoteTags := make([]string, 0, len(remoteInbounds))
  105. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  106. for _, remoteIb := range remoteInbounds {
  107. remoteTags = append(remoteTags, remoteIb.Tag)
  108. remoteTagSet[remoteIb.Tag] = struct{}{}
  109. }
  110. prefix := nodeTagPrefix(&nodeID)
  111. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  112. var errs []error
  113. for _, ib := range inbounds {
  114. desiredTags[ib.Tag] = struct{}{}
  115. // existsOnNode: does the node already report this inbound under any of the
  116. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  117. _, existsOnNode := remoteTagSet[ib.Tag]
  118. if prefix != "" {
  119. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  120. desiredTags[stripped] = struct{}{}
  121. if _, ok := remoteTagSet[stripped]; ok {
  122. existsOnNode = true
  123. }
  124. } else {
  125. desiredTags[prefix+ib.Tag] = struct{}{}
  126. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  127. existsOnNode = true
  128. }
  129. }
  130. }
  131. runtimeIb := ib
  132. if built, bErr := s.buildInboundForNodePush(db, ib); bErr == nil {
  133. runtimeIb = built
  134. }
  135. if !existsOnNode && n.Guid != "" && ib.OriginNodeGuid == n.Guid {
  136. var compatible []runtime.RemoteInboundOption
  137. for _, remoteIb := range remoteInbounds {
  138. if remoteIb.Port == runtimeIb.Port &&
  139. remoteIb.Protocol == runtimeIb.Protocol &&
  140. strings.TrimSpace(remoteIb.Listen) == strings.TrimSpace(runtimeIb.Listen) {
  141. compatible = append(compatible, remoteIb)
  142. }
  143. }
  144. switch len(compatible) {
  145. case 1:
  146. alias := compatible[0]
  147. desiredTags[alias.Tag] = struct{}{}
  148. rt.AdoptInboundAlias(runtimeIb, alias)
  149. existsOnNode = true
  150. logger.Infof("adopted compatible inbound %q on node %s as %q", alias.Tag, n.Name, ib.Tag)
  151. case 0:
  152. // No compatible occupant: keep the normal create path, which
  153. // leaves a real port/protocol drift loud.
  154. default:
  155. for _, candidate := range compatible {
  156. desiredTags[candidate.Tag] = struct{}{}
  157. }
  158. errs = append(errs, fmt.Errorf("reconcile inbound %q: ambiguous compatible remote inbounds", ib.Tag))
  159. continue
  160. }
  161. }
  162. if _, err := rt.ReconcileInbound(ctx, runtimeIb, existsOnNode); err != nil {
  163. errs = append(errs, fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err))
  164. }
  165. }
  166. // Before the next clean sync adopts the node's inbounds, "absent locally"
  167. // means "not imported yet" — sweeping now would wipe the node at onboarding.
  168. if n.InboundsAdoptedAt == 0 {
  169. return errors.Join(errs...)
  170. }
  171. // In "selected" sync mode the panel only manages the selected tags: the
  172. // rest were never imported, so their absence from the local DB must not
  173. // delete them from the node. Only a selected tag missing locally (the
  174. // panel deleted it while the node was unreachable) may be swept.
  175. selected := nodeSelectedTagSet(n)
  176. for _, tag := range remoteTags {
  177. if _, want := desiredTags[tag]; want {
  178. continue
  179. }
  180. if selected != nil {
  181. if _, managed := selected[tag]; !managed {
  182. continue
  183. }
  184. }
  185. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  186. errs = append(errs, fmt.Errorf("reconcile delete %q: %w", tag, err))
  187. }
  188. }
  189. return errors.Join(errs...)
  190. }
  191. const resetGracePeriodMs int64 = 30000
  192. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  193. // Xray's stats counters often report a zero delta for an active session across
  194. // a single poll, so a 5s grace would still drop the client on the next tick.
  195. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  196. // long after a real disconnect.
  197. const onlineGracePeriodMs int64 = 20000
  198. type nodeTrafficCounter struct {
  199. Up int64
  200. Down int64
  201. }
  202. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  203. return tx.Clauses(clause.OnConflict{
  204. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  205. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  206. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  207. }
  208. // mergeActivationExpiry: master absolute wins; node may only activate when
  209. // master is unset/duration. Node auto-renew goes through nodeClientRenewed.
  210. func mergeActivationExpiry(existing, node int64) int64 {
  211. if existing > 0 {
  212. return existing
  213. }
  214. return node
  215. }
  216. // masterLimitsAllowClient reports whether the master's own deadline and quota
  217. // (including this tick's deltas) still permit the client.
  218. func masterLimitsAllowClient(master *xray.ClientTraffic, now, deltaUp, deltaDown int64) bool {
  219. if master == nil {
  220. return false
  221. }
  222. if master.ExpiryTime > 0 && master.ExpiryTime <= now {
  223. return false
  224. }
  225. if master.Total > 0 && master.Up+deltaUp+master.Down+deltaDown >= master.Total {
  226. return false
  227. }
  228. return true
  229. }
  230. // nodeDisableIsStale reports an enable=false the node decided against limits the
  231. // master has since changed, so it must not latch back (#6228 / #4917).
  232. func nodeDisableIsStale(master *xray.ClientTraffic, node xray.ClientTraffic, now, deltaUp, deltaDown int64) bool {
  233. if master == nil {
  234. return false
  235. }
  236. // Matching limits mean the node judged the client on the master's own terms:
  237. // that verdict is genuine and still latches, as #4917 requires.
  238. if node.ExpiryTime == master.ExpiryTime && node.Total == master.Total {
  239. return false
  240. }
  241. return masterLimitsAllowClient(master, now, deltaUp, deltaDown)
  242. }
  243. func clampTrafficCounter(v int64) int64 {
  244. if v > database.TrafficMax {
  245. return database.TrafficMax
  246. }
  247. if v < 0 {
  248. return 0
  249. }
  250. return v
  251. }
  252. // applyMasterClientLifecycle overlays the already-merged master row onto a
  253. // node-reported client for SyncInbound (#6228).
  254. func applyMasterClientLifecycle(c *model.Client, master *xray.ClientTraffic, cs *xray.ClientTraffic) {
  255. if master == nil {
  256. // No central row to speak for the client: the node's own latch is all
  257. // there is, and it may only disable.
  258. if cs != nil && !cs.Enable {
  259. c.Enable = false
  260. }
  261. return
  262. }
  263. c.ExpiryTime = mergeActivationExpiry(master.ExpiryTime, c.ExpiryTime)
  264. c.Enable = master.Enable
  265. }
  266. // nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
  267. // forward, evidenced by a renewal-count bump or a drop below the stored baseline.
  268. func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
  269. if (cs.Reset <= 0 && cs.ResetDay <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
  270. return false
  271. }
  272. if cs.ExpiryTime <= existing.ExpiryTime {
  273. return false
  274. }
  275. // A client that used no traffic in the period never dips, so the renewal
  276. // counter is the only evidence autoRenewClients leaves behind (#6228).
  277. if cs.ResetCount > existing.ResetCount {
  278. return true
  279. }
  280. return canon.Up < base.Up || canon.Down < base.Down
  281. }
  282. // liftActivatedClientRecordExpiries copies a node-activated deadline from
  283. // client_traffics onto client records still holding the negative duration (#5714).
  284. func liftActivatedClientRecordExpiries(tx *gorm.DB) error {
  285. return tx.Exec(
  286. `UPDATE clients
  287. SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1)
  288. WHERE clients.expiry_time < 0
  289. AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`,
  290. ).Error
  291. }
  292. // SnapshotHasUnadoptedInbounds reports whether the snapshot carries a tag with
  293. // no central row yet, i.e. the next merge would adopt a new inbound.
  294. func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  295. if snap == nil || len(snap.Inbounds) == 0 {
  296. return false, nil
  297. }
  298. var tags []string
  299. if err := database.GetDB().Model(model.Inbound{}).
  300. Where("node_id = ?", nodeID).
  301. Pluck("tag", &tags).Error; err != nil {
  302. return false, err
  303. }
  304. prefix := nodeTagPrefix(&nodeID)
  305. known := make(map[string]struct{}, len(tags)*2)
  306. for _, tag := range tags {
  307. known[tag] = struct{}{}
  308. if prefix != "" {
  309. if stripped, found := strings.CutPrefix(tag, prefix); found {
  310. known[stripped] = struct{}{}
  311. } else {
  312. known[prefix+tag] = struct{}{}
  313. }
  314. }
  315. }
  316. for _, ib := range snap.Inbounds {
  317. if ib == nil {
  318. continue
  319. }
  320. if _, ok := known[ib.Tag]; !ok {
  321. return true, nil
  322. }
  323. }
  324. return false, nil
  325. }
  326. // SetRemoteTraffic merges a node snapshot. justPushed marks the tick whose
  327. // config push just landed, whose snapshot may still predate it (#6228).
  328. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) {
  329. var structuralChange bool
  330. err := submitTrafficWrite(func() error {
  331. var inner error
  332. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed)
  333. return inner
  334. })
  335. if err != nil {
  336. // As on a failed fetch: a node whose snapshot did not merge keeps no online set.
  337. s.ClearNodeOnlineClients(nodeID)
  338. }
  339. return structuralChange, err
  340. }
  341. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  342. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  343. // this to derive per-inbound speed for the dashboard — node inbounds have no
  344. // local Xray poll to produce live deltas the way local inbounds do.
  345. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  346. var rows []struct {
  347. Tag string
  348. Up int64
  349. Down int64
  350. }
  351. if err := database.GetDB().Table("inbounds").
  352. Select("tag, up, down").
  353. Where("node_id IS NOT NULL").
  354. Scan(&rows).Error; err != nil {
  355. return nil, err
  356. }
  357. out := make(map[string][2]int64, len(rows))
  358. for _, r := range rows {
  359. out[r.Tag] = [2]int64{r.Up, r.Down}
  360. }
  361. return out, nil
  362. }
  363. func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
  364. return c.Settings != adoptedSettings ||
  365. c.Enable != snapIb.Enable ||
  366. c.Remark != snapIb.Remark ||
  367. c.SubSortIndex != normalizeSubSortIndex(snapIb.SubSortIndex) ||
  368. c.Listen != snapIb.Listen ||
  369. c.Port != snapIb.Port ||
  370. c.Protocol != snapIb.Protocol ||
  371. c.Total != snapIb.Total ||
  372. c.ExpiryTime != snapIb.ExpiryTime ||
  373. c.StreamSettings != snapIb.StreamSettings ||
  374. c.Sniffing != snapIb.Sniffing ||
  375. c.TrafficReset != snapIb.TrafficReset ||
  376. c.TrafficResetDay != normalizeTrafficResetDay(snapIb.TrafficResetDay)
  377. }
  378. // adoptedWireInbound is the central inbound as it reads after adopting the
  379. // node-reported wire fields — the payload the reconcile fingerprint must track.
  380. func adoptedWireInbound(c, snapIb *model.Inbound, adoptedSettings string) *model.Inbound {
  381. a := *c
  382. a.Enable = snapIb.Enable
  383. a.Remark = snapIb.Remark
  384. a.SubSortIndex = normalizeSubSortIndex(snapIb.SubSortIndex)
  385. a.Listen = snapIb.Listen
  386. a.Port = snapIb.Port
  387. a.Protocol = snapIb.Protocol
  388. a.Total = snapIb.Total
  389. a.ExpiryTime = snapIb.ExpiryTime
  390. a.Settings = adoptedSettings
  391. a.StreamSettings = snapIb.StreamSettings
  392. a.Sniffing = snapIb.Sniffing
  393. a.TrafficReset = snapIb.TrafficReset
  394. a.TrafficResetDay = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  395. return &a
  396. }
  397. // clientEmailsOwnedElsewhere returns the emails attached only to inbounds of
  398. // other nodes: email is unique, so adopting one would overwrite a client this
  399. // node does not serve. Attached nowhere means soft-orphaned, hence adoptable.
  400. func clientEmailsOwnedElsewhere(tx *gorm.DB, nodeID int, emails []string) (map[string]struct{}, error) {
  401. attachedEmails := func(nodeScoped bool) ([]string, error) {
  402. q := tx.Table("clients").
  403. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  404. Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id").
  405. Where("clients.email IN ?", emails)
  406. if nodeScoped {
  407. q = q.Where("inbounds.node_id = ?", nodeID)
  408. }
  409. var rows []string
  410. err := q.Pluck("clients.email", &rows).Error
  411. return rows, err
  412. }
  413. attached, err := attachedEmails(false)
  414. if err != nil {
  415. return nil, err
  416. }
  417. if len(attached) == 0 {
  418. return nil, nil
  419. }
  420. owned, err := attachedEmails(true)
  421. if err != nil {
  422. return nil, err
  423. }
  424. ownedSet := make(map[string]struct{}, len(owned))
  425. for _, email := range owned {
  426. ownedSet[email] = struct{}{}
  427. }
  428. foreign := make(map[string]struct{})
  429. for _, email := range attached {
  430. if _, ok := ownedSet[email]; !ok {
  431. foreign[email] = struct{}{}
  432. }
  433. }
  434. return foreign, nil
  435. }
  436. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) {
  437. if snap == nil || nodeID <= 0 {
  438. return false, nil
  439. }
  440. db := database.GetDB()
  441. now := time.Now().UnixMilli()
  442. // originGuidFor attributes a synced inbound to the panel that physically
  443. // hosts it. A node's OWN inbounds report either an empty origin or — on
  444. // builds that set it locally — the node's own panelGuid; both resolve to
  445. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  446. // (shared with another node or the master, i.e. a cloned server), in which
  447. // case it falls back to the node-unique id so #4983 attribution doesn't
  448. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  449. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  450. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  451. var nodeRow model.Node
  452. db.Select("guid", "config_dirty", "inbound_sync_mode", "inbound_tags").Where("id = ?", nodeID).First(&nodeRow)
  453. // Re-read inside the serialized writer: a client added while this snapshot
  454. // was in flight marks the node dirty after the caller sampled the flag.
  455. dirty = dirty || nodeRow.ConfigDirty
  456. // Adoption, record sync and sweeps still run on a just-pushed tick; only the
  457. // client lifecycle merge waits for a snapshot that reflects the push.
  458. lifecycleFrozen := dirty || justPushed
  459. nodeRow.Id = nodeID
  460. unmanagedTag := unmanagedTagPredicate(&nodeRow)
  461. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  462. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  463. originGuidFor := func(snapIb *model.Inbound) string {
  464. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  465. return snapIb.OriginNodeGuid
  466. }
  467. return selfKey
  468. }
  469. var central []model.Inbound
  470. if err := db.Model(model.Inbound{}).
  471. Where("node_id = ?", nodeID).
  472. Find(&central).Error; err != nil {
  473. return false, err
  474. }
  475. // Index under the stored tag and its prefix-flipped form so a snap matches
  476. // whether the n<id>- prefix lives on the node side, the central side, or
  477. // neither — a mismatch must never spawn a duplicate central inbound.
  478. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  479. prefix := nodeTagPrefix(&nodeID)
  480. for i := range central {
  481. tagToCentral[central[i].Tag] = &central[i]
  482. if prefix != "" {
  483. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  484. tagToCentral[stripped] = &central[i]
  485. } else {
  486. tagToCentral[prefix+central[i].Tag] = &central[i]
  487. }
  488. }
  489. }
  490. var centralClientStats []xray.ClientTraffic
  491. if len(central) > 0 {
  492. ids := make([]int, 0, len(central))
  493. for i := range central {
  494. ids = append(ids, central[i].Id)
  495. }
  496. if err := db.Model(xray.ClientTraffic{}).
  497. Where("inbound_id IN ?", ids).
  498. Find(&centralClientStats).Error; err != nil {
  499. return false, err
  500. }
  501. }
  502. type csKey struct {
  503. inboundID int
  504. email string
  505. }
  506. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  507. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  508. for i := range centralClientStats {
  509. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  510. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  511. }
  512. nodeBaselines := make(map[string]nodeTrafficCounter)
  513. var baselineRows []model.NodeClientTraffic
  514. if err := db.Model(&model.NodeClientTraffic{}).
  515. Where("node_id = ?", nodeID).
  516. Find(&baselineRows).Error; err != nil {
  517. return false, err
  518. }
  519. for i := range baselineRows {
  520. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  521. }
  522. var defaultUserId int
  523. if len(central) > 0 {
  524. defaultUserId = central[0].UserId
  525. } else {
  526. var u model.User
  527. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  528. defaultUserId = u.Id
  529. } else {
  530. defaultUserId = 1
  531. }
  532. }
  533. // Union of every email the snapshot still reports, across all inbounds.
  534. // The (node, email) baseline rows are keyed per node, not per inbound, so
  535. // the sweeps below must only drop one when the email left the node
  536. // entirely — an email whose stats moved to (or always lived under) a
  537. // sibling inbound still needs its baseline for the sibling's delta
  538. // computation (#5202).
  539. //
  540. // Xray counts traffic per email, not per inbound, so a multi-attached
  541. // client's shared counter is copied onto every inbound it's on. Fold each
  542. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  543. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  544. snapEmailsAll := make(map[string]struct{})
  545. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  546. for _, snapIb := range snap.Inbounds {
  547. if snapIb == nil {
  548. continue
  549. }
  550. for i := range snapIb.ClientStats {
  551. email := snapIb.ClientStats[i].Email
  552. snapEmailsAll[email] = struct{}{}
  553. cur := nodeEmailTotals[email]
  554. if snapIb.ClientStats[i].Up > cur.Up {
  555. cur.Up = snapIb.ClientStats[i].Up
  556. }
  557. if snapIb.ClientStats[i].Down > cur.Down {
  558. cur.Down = snapIb.ClientStats[i].Down
  559. }
  560. nodeEmailTotals[email] = cur
  561. }
  562. }
  563. // Membership set for the rowExists checks below. Only the snapshot's emails
  564. // are ever probed, so scope the lookup to those instead of plucking the whole
  565. // client_traffics table (50k+ rows) on every node poll.
  566. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  567. if len(snapEmailsAll) > 0 {
  568. snapEmailList := make([]string, 0, len(snapEmailsAll))
  569. for email := range snapEmailsAll {
  570. snapEmailList = append(snapEmailList, email)
  571. }
  572. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  573. var found []string
  574. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  575. return false, err
  576. }
  577. for _, e := range found {
  578. existingEmails[e] = struct{}{}
  579. }
  580. }
  581. }
  582. tx := db.Begin()
  583. committed := false
  584. defer func() {
  585. if !committed {
  586. tx.Rollback()
  587. }
  588. }()
  589. structuralChange := false
  590. lifecycleLifted := false
  591. var adoptedInbounds []*model.Inbound
  592. type pendingAdopt struct {
  593. central *model.Inbound
  594. snapIb *model.Inbound
  595. wireSettings string
  596. }
  597. var pendingAdopts []pendingAdopt
  598. newInboundIDs := make(map[int]struct{})
  599. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  600. for _, snapIb := range snap.Inbounds {
  601. if snapIb == nil {
  602. continue
  603. }
  604. snapTags[snapIb.Tag] = struct{}{}
  605. // Record the prefix-flipped form too so the orphan sweep below keeps a
  606. // central inbound whether its tag carries the n<id>- prefix or not.
  607. if prefix != "" {
  608. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  609. snapTags[stripped] = struct{}{}
  610. } else {
  611. snapTags[prefix+snapIb.Tag] = struct{}{}
  612. }
  613. }
  614. c, ok := tagToCentral[snapIb.Tag]
  615. if !ok {
  616. origin := originGuidFor(snapIb)
  617. var compatible []*model.Inbound
  618. for i := range central {
  619. candidate := &central[i]
  620. if candidate.OriginNodeGuid == origin &&
  621. candidate.Port == snapIb.Port &&
  622. candidate.Protocol == snapIb.Protocol &&
  623. strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) {
  624. compatible = append(compatible, candidate)
  625. }
  626. }
  627. switch len(compatible) {
  628. case 1:
  629. c, ok = compatible[0], true
  630. tagToCentral[snapIb.Tag] = c
  631. snapTags[c.Tag] = struct{}{}
  632. case 0:
  633. // A genuinely new inbound follows the normal adoption path.
  634. default:
  635. return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag)
  636. }
  637. }
  638. if !ok {
  639. if dirty {
  640. continue
  641. }
  642. // Try snap.Tag first; on collision fall back to the n<id>-
  643. // prefixed form so local+node can both own the same port.
  644. pickFreeTag := func() (string, error) {
  645. candidates := []string{snapIb.Tag}
  646. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  647. candidates = append(candidates, prefix+snapIb.Tag)
  648. }
  649. for _, t := range candidates {
  650. var owner model.Inbound
  651. err := tx.Where("tag = ?", t).First(&owner).Error
  652. if errors.Is(err, gorm.ErrRecordNotFound) {
  653. return t, nil
  654. }
  655. if err != nil {
  656. return "", err
  657. }
  658. }
  659. return "", nil
  660. }
  661. chosenTag, err := pickFreeTag()
  662. if err != nil {
  663. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  664. continue
  665. }
  666. if chosenTag == "" {
  667. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  668. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  669. logger.Warningf(
  670. "setRemoteTraffic: tag %q from node %d collides with an existing inbound even after the n%d- prefix — skipping (rename one side to remove the duplicate)",
  671. snapIb.Tag, nodeID, nodeID,
  672. )
  673. }
  674. continue
  675. }
  676. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  677. newIb := model.Inbound{
  678. UserId: defaultUserId,
  679. NodeID: &nodeID,
  680. OriginNodeGuid: originGuidFor(snapIb),
  681. Tag: chosenTag,
  682. Listen: snapIb.Listen,
  683. Port: snapIb.Port,
  684. Protocol: snapIb.Protocol,
  685. Settings: snapIb.Settings,
  686. StreamSettings: snapIb.StreamSettings,
  687. Sniffing: snapIb.Sniffing,
  688. TrafficReset: snapIb.TrafficReset,
  689. TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay),
  690. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  691. Enable: snapIb.Enable,
  692. Remark: snapIb.Remark,
  693. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  694. Total: snapIb.Total,
  695. ExpiryTime: snapIb.ExpiryTime,
  696. Up: snapIb.Up,
  697. Down: snapIb.Down,
  698. ShareAddrStrategy: "node",
  699. DisableFlow: snapIb.DisableFlow,
  700. }
  701. if err := tx.Create(&newIb).Error; err != nil {
  702. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  703. continue
  704. }
  705. tagToCentral[snapIb.Tag] = &newIb
  706. if newIb.Tag != snapIb.Tag {
  707. tagToCentral[newIb.Tag] = &newIb
  708. }
  709. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  710. if err := tx.Create(&rows).Error; err != nil {
  711. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  712. }
  713. }
  714. newInboundIDs[newIb.Id] = struct{}{}
  715. structuralChange = true
  716. continue
  717. }
  718. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  719. // Adopting the node's settings verbatim would re-add a client the master
  720. // deleted moments ago if this snapshot was fetched before the deletion
  721. // push landed — filter just-deleted emails out while their tombstone lives.
  722. adoptedSettings := snapIb.Settings
  723. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  724. adoptedSettings = stripped
  725. }
  726. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  727. adoptedSettings = deduped
  728. }
  729. updates := map[string]any{}
  730. if !dirty {
  731. // Defer lifecycle lift until after client_traffics absorbs this tick's
  732. // deltas so quota stale-disable matches SQL (#6228).
  733. pendingAdopts = append(pendingAdopts, pendingAdopt{
  734. central: c, snapIb: snapIb, wireSettings: adoptedSettings,
  735. })
  736. updates["enable"] = snapIb.Enable
  737. updates["remark"] = snapIb.Remark
  738. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  739. updates["listen"] = snapIb.Listen
  740. updates["port"] = snapIb.Port
  741. updates["protocol"] = snapIb.Protocol
  742. updates["total"] = snapIb.Total
  743. updates["expiry_time"] = snapIb.ExpiryTime
  744. updates["stream_settings"] = snapIb.StreamSettings
  745. updates["sniffing"] = snapIb.Sniffing
  746. updates["traffic_reset"] = snapIb.TrafficReset
  747. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  748. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  749. }
  750. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  751. updates["up"] = snapIb.Up
  752. updates["down"] = snapIb.Down
  753. }
  754. // Physical-home attribution is independent of config-dirty state, so
  755. // keep it current even while the node has pending offline edits. Writes
  756. // once to backfill an existing row, then stays equal (#4983).
  757. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  758. updates["origin_node_guid"] = og
  759. }
  760. if !dirty && (c.Remark != snapIb.Remark ||
  761. c.Listen != snapIb.Listen ||
  762. c.Port != snapIb.Port ||
  763. c.Total != snapIb.Total ||
  764. c.ExpiryTime != snapIb.ExpiryTime ||
  765. c.Enable != snapIb.Enable) {
  766. structuralChange = true
  767. }
  768. if len(updates) > 0 {
  769. if err := tx.Model(model.Inbound{}).
  770. Where("id = ?", c.Id).
  771. Updates(updates).Error; err != nil {
  772. return false, err
  773. }
  774. }
  775. }
  776. for _, c := range central {
  777. if dirty {
  778. continue
  779. }
  780. // A node inbound created disabled is never delivered, so its absence from
  781. // the snapshot is ambiguous rather than evidence of a node-side delete.
  782. if !c.Enable {
  783. continue
  784. }
  785. if len(snapTags) == 0 {
  786. // A node mid-restart or with a transient DB error can return an empty
  787. // inbound list with success=true. Treat "zero inbounds reported" as
  788. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  789. // wipes the node's central inbounds and every client on them (and
  790. // resets traffic history on re-create). A real per-inbound deletion
  791. // still sweeps, because the node keeps reporting its other inbounds.
  792. continue
  793. }
  794. if _, kept := snapTags[c.Tag]; kept {
  795. continue
  796. }
  797. if unmanagedTag(c.Tag) {
  798. continue
  799. }
  800. // This drops the central inbound and its clients' traffic history, so say
  801. // so: silent removal is indistinguishable from an inbound never arriving.
  802. logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port)
  803. var goneEmails []string
  804. if err := tx.Model(xray.ClientTraffic{}).
  805. Where("inbound_id = ?", c.Id).
  806. Pluck("email", &goneEmails).Error; err != nil {
  807. return false, err
  808. }
  809. if len(goneEmails) > 0 {
  810. // Baselines are per (node, email), not per inbound: keep them for
  811. // emails the snapshot still reports under a sibling inbound (#5202).
  812. baselineGone := make([]string, 0, len(goneEmails))
  813. for _, e := range goneEmails {
  814. if _, still := snapEmailsAll[e]; !still {
  815. baselineGone = append(baselineGone, e)
  816. }
  817. }
  818. // Chunk to avoid SQLite bind var limit when a node has many clients
  819. // removed (e.g. after API bulk delete or structural change on node inbound).
  820. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  821. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  822. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  823. return false, err
  824. }
  825. }
  826. // The per-email row is the shared accumulator across every inbound
  827. // (and node) the email is attached to. Only drop it when this was the
  828. // email's last inbound — wiping it while a sibling still feeds it
  829. // loses the summed history, and the next node sync would re-seed the
  830. // row with that node's counter alone.
  831. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  832. if sErr != nil {
  833. return false, sErr
  834. }
  835. delEmails := make([]string, 0, len(goneEmails))
  836. for _, e := range goneEmails {
  837. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  838. delEmails = append(delEmails, e)
  839. }
  840. }
  841. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  842. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  843. Delete(&xray.ClientTraffic{}).Error; err != nil {
  844. return false, err
  845. }
  846. }
  847. }
  848. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  849. return false, err
  850. }
  851. if err := tx.Where("id = ?", c.Id).
  852. Delete(&model.Inbound{}).Error; err != nil {
  853. return false, err
  854. }
  855. delete(tagToCentral, c.Tag)
  856. structuralChange = true
  857. }
  858. for _, snapIb := range snap.Inbounds {
  859. if snapIb == nil {
  860. continue
  861. }
  862. c, ok := tagToCentral[snapIb.Tag]
  863. if !ok {
  864. continue
  865. }
  866. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  867. // Parsed once per inbound on the first renewal candidate, not per client.
  868. var snapExpiries map[string]int64
  869. for _, cs := range snapIb.ClientStats {
  870. snapEmails[cs.Email] = struct{}{}
  871. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  872. canon := nodeEmailTotals[cs.Email]
  873. base, seen := nodeBaselines[cs.Email]
  874. var deltaUp, deltaDown int64
  875. if seen {
  876. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  877. deltaUp = 0
  878. }
  879. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  880. deltaDown = 0
  881. }
  882. }
  883. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  884. if dirty {
  885. continue
  886. }
  887. _, isNewInbound := newInboundIDs[c.Id]
  888. // On a known inbound a missing row plus a live tombstone means the
  889. // master just deleted this client and the snapshot predates the
  890. // deletion push — recreating the row (at zero) would resurrect the
  891. // client. A freshly adopted inbound still gets its row (seeded at
  892. // zero) so adoption semantics stay intact.
  893. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  894. continue
  895. }
  896. var seedUp, seedDown int64
  897. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  898. seedUp, seedDown = canon.Up, canon.Down
  899. }
  900. row := &xray.ClientTraffic{
  901. InboundId: c.Id,
  902. Email: cs.Email,
  903. Enable: cs.Enable,
  904. Total: cs.Total,
  905. ExpiryTime: cs.ExpiryTime,
  906. Reset: cs.Reset,
  907. ResetDay: cs.ResetDay,
  908. Up: seedUp,
  909. Down: seedDown,
  910. LastOnline: cs.LastOnline,
  911. }
  912. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  913. Create(row).Error; err != nil {
  914. return false, err
  915. }
  916. centralCS[csKey{c.Id, cs.Email}] = row
  917. centralCSByEmail[cs.Email] = row
  918. existingEmails[cs.Email] = struct{}{}
  919. structuralChange = true
  920. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  921. return false, err
  922. }
  923. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  924. continue
  925. }
  926. existing := centralCSByEmail[cs.Email]
  927. if existing != nil {
  928. expiryChanged := !lifecycleFrozen && existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime)
  929. // Only a real latch to disabled is structural; one-way merge never
  930. // re-enables from the node.
  931. enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
  932. !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
  933. metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset)
  934. if enableChanged || metaChanged || expiryChanged {
  935. structuralChange = true
  936. }
  937. }
  938. renewed := !lifecycleFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base)
  939. if renewed {
  940. // Reject when the node's own settings still carry the old absolute:
  941. // lagging ClientStats after a master shorten mimic a renew (#6228).
  942. if snapExpiries == nil {
  943. snapExpiries = settingsClientAbsoluteExpiries(snapIb.Settings)
  944. }
  945. if se, ok := snapExpiries[cs.Email]; ok && se <= existing.ExpiryTime {
  946. renewed = false
  947. }
  948. }
  949. if renewed {
  950. // A renewal starts a fresh quota window: adopt the node's counters
  951. // and enable state, drop stale pushes (mirrors autoRenewClients).
  952. if err := tx.Exec(
  953. fmt.Sprintf(
  954. `UPDATE client_traffics
  955. SET up = ?, down = ?, enable = ?, total = ?,
  956. expiry_time = ?, reset = ?, reset_day = ?, reset_count = ?, last_online = %s
  957. WHERE email = ?`,
  958. database.GreatestExpr("last_online", "?"),
  959. ),
  960. canon.Up, canon.Down, cs.Enable, cs.Total,
  961. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetCount,
  962. cs.LastOnline, cs.Email,
  963. ).Error; err != nil {
  964. return false, err
  965. }
  966. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  967. return false, err
  968. }
  969. existing.Up = canon.Up
  970. existing.Down = canon.Down
  971. existing.Enable = cs.Enable
  972. existing.Total = cs.Total
  973. existing.ExpiryTime = cs.ExpiryTime
  974. existing.Reset = cs.Reset
  975. existing.ResetCount = cs.ResetCount
  976. structuralChange = true
  977. } else if lifecycleFrozen {
  978. // Push pending or just landed: only counters may move, the master
  979. // keeps expiry/enable/total/reset.
  980. if err := tx.Exec(
  981. fmt.Sprintf(
  982. `UPDATE client_traffics
  983. SET up = %s, down = %s, last_online = %s
  984. WHERE email = ?`,
  985. database.ClampedAddExpr("up"),
  986. database.ClampedAddExpr("down"),
  987. database.GreatestExpr("last_online", "?"),
  988. ),
  989. deltaUp, deltaDown, cs.LastOnline, cs.Email,
  990. ).Error; err != nil {
  991. return false, err
  992. }
  993. if existing != nil {
  994. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  995. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  996. }
  997. } else {
  998. enableExpr := database.ClientTrafficEnableMergeExpr()
  999. expiryExpr := database.ClientTrafficExpiryMergeExpr()
  1000. if err := tx.Exec(
  1001. fmt.Sprintf(
  1002. `UPDATE client_traffics
  1003. SET up = %s, down = %s, enable = %s, total = ?,
  1004. expiry_time = %s,
  1005. reset = ?, reset_day = ?, last_online = %s
  1006. WHERE email = ?`,
  1007. database.ClampedAddExpr("up"),
  1008. database.ClampedAddExpr("down"),
  1009. enableExpr,
  1010. expiryExpr,
  1011. database.GreatestExpr("last_online", "?"),
  1012. ),
  1013. deltaUp, deltaDown,
  1014. cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
  1015. cs.Total,
  1016. cs.ExpiryTime, cs.Reset, cs.ResetDay,
  1017. cs.LastOnline, cs.Email,
  1018. ).Error; err != nil {
  1019. return false, err
  1020. }
  1021. if existing != nil {
  1022. priorExpiry := existing.ExpiryTime
  1023. if !cs.Enable && !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown) {
  1024. existing.Enable = false
  1025. }
  1026. existing.ExpiryTime = mergeActivationExpiry(priorExpiry, cs.ExpiryTime)
  1027. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1028. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1029. existing.Total = cs.Total
  1030. existing.Reset = cs.Reset
  1031. }
  1032. }
  1033. // A dip plus a lagging longer expiry mimics nodeClientRenewed and would
  1034. // undo a master shorten once the freeze lifts (#6228).
  1035. if lifecycleFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) {
  1036. continue
  1037. }
  1038. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  1039. return false, err
  1040. }
  1041. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  1042. }
  1043. for k, existing := range centralCS {
  1044. if dirty {
  1045. continue
  1046. }
  1047. if k.inboundID != c.Id {
  1048. continue
  1049. }
  1050. if _, kept := snapEmails[k.email]; kept {
  1051. continue
  1052. }
  1053. // Gone from this inbound's stats but still reported by the node under
  1054. // a sibling inbound: both the shared accumulator row and the (node,
  1055. // email) baseline must survive, or the sibling's next delta would
  1056. // compute against nothing and freeze the counter (#5202).
  1057. if _, still := snapEmailsAll[k.email]; still {
  1058. continue
  1059. }
  1060. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1061. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1062. return false, err
  1063. }
  1064. // Same shared-accumulator rule as the inbound-removal sweep above:
  1065. // keep the row while another inbound still references the email.
  1066. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  1067. if uErr != nil {
  1068. return false, uErr
  1069. }
  1070. // Usage, quota and expiry live on this row, so a client the orphan
  1071. // sweep will mark keeps it until the reaper confirms the removal.
  1072. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  1073. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1074. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1075. return false, err
  1076. }
  1077. }
  1078. structuralChange = true
  1079. }
  1080. }
  1081. type oldSet struct {
  1082. inboundID int
  1083. emails map[string]struct{}
  1084. }
  1085. var perInboundOld []oldSet
  1086. syncFailedInbounds := map[int]struct{}{}
  1087. for _, p := range pendingAdopts {
  1088. lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, centralCSByEmail)
  1089. adoptedSettings := p.wireSettings
  1090. if liftChanged {
  1091. adoptedSettings = lifted
  1092. lifecycleLifted = true
  1093. }
  1094. if p.central.Settings != adoptedSettings {
  1095. if err := tx.Model(model.Inbound{}).
  1096. Where("id = ?", p.central.Id).
  1097. Update("settings", adoptedSettings).Error; err != nil {
  1098. return false, err
  1099. }
  1100. structuralChange = true
  1101. }
  1102. // The fingerprint stamps the un-lifted wire blob on purpose: a lift must
  1103. // leave reconcile a mismatch to re-push against.
  1104. if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
  1105. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
  1106. }
  1107. }
  1108. for _, snapIb := range snap.Inbounds {
  1109. if snapIb == nil {
  1110. continue
  1111. }
  1112. c, ok := tagToCentral[snapIb.Tag]
  1113. if !ok {
  1114. continue
  1115. }
  1116. if dirty {
  1117. continue
  1118. }
  1119. var oldEmailsRows []string
  1120. if err := tx.Table("clients").
  1121. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1122. Where("client_inbounds.inbound_id = ?", c.Id).
  1123. Pluck("email", &oldEmailsRows).Error; err == nil {
  1124. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1125. for _, e := range oldEmailsRows {
  1126. if e != "" {
  1127. oldEmails[e] = struct{}{}
  1128. }
  1129. }
  1130. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1131. }
  1132. clients, gcErr := s.GetClients(snapIb)
  1133. if gcErr != nil {
  1134. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1135. continue
  1136. }
  1137. csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
  1138. for _, cs := range snapIb.ClientStats {
  1139. csByEmail[cs.Email] = cs
  1140. }
  1141. filtered := clients[:0]
  1142. for i := range clients {
  1143. if isClientEmailTombstoned(clients[i].Email) {
  1144. continue
  1145. }
  1146. existing := centralCSByEmail[clients[i].Email]
  1147. var csPtr *xray.ClientTraffic
  1148. if cs, hit := csByEmail[clients[i].Email]; hit {
  1149. csCopy := cs
  1150. csPtr = &csCopy
  1151. }
  1152. applyMasterClientLifecycle(&clients[i], existing, csPtr)
  1153. filtered = append(filtered, clients[i])
  1154. }
  1155. localEmails := make([]string, 0, len(filtered))
  1156. for i := range filtered {
  1157. if filtered[i].Email != "" {
  1158. localEmails = append(localEmails, filtered[i].Email)
  1159. }
  1160. }
  1161. if len(localEmails) > 0 {
  1162. var localMeta []struct {
  1163. Email string
  1164. Comment string `gorm:"column:comment"`
  1165. }
  1166. if err := tx.Table("clients").
  1167. Select("email, comment").
  1168. Where("email IN ?", localEmails).
  1169. Find(&localMeta).Error; err == nil {
  1170. commentByEmail := make(map[string]string, len(localMeta))
  1171. for _, m := range localMeta {
  1172. commentByEmail[m.Email] = m.Comment
  1173. }
  1174. for i := range filtered {
  1175. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1176. filtered[i].Comment = cmt
  1177. }
  1178. }
  1179. }
  1180. }
  1181. if len(localEmails) > 0 {
  1182. foreign, err := clientEmailsOwnedElsewhere(tx, nodeID, localEmails)
  1183. if err != nil {
  1184. return false, err
  1185. }
  1186. if len(foreign) > 0 {
  1187. kept := filtered[:0]
  1188. for i := range filtered {
  1189. if _, claimed := foreign[filtered[i].Email]; !claimed {
  1190. kept = append(kept, filtered[i])
  1191. continue
  1192. }
  1193. key := fmt.Sprintf("%d:%s", nodeID, filtered[i].Email)
  1194. if _, seen := reportedForeignClientClaim.LoadOrStore(key, struct{}{}); !seen {
  1195. logger.Warningf(
  1196. "setRemoteTraffic: node %d reported client %q, which is attached only to inbounds of another node — not adopting (rename one side to remove the duplicate email)",
  1197. nodeID, filtered[i].Email,
  1198. )
  1199. }
  1200. }
  1201. filtered = kept
  1202. }
  1203. }
  1204. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1205. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1206. syncFailedInbounds[c.Id] = struct{}{}
  1207. }
  1208. }
  1209. for _, old := range perInboundOld {
  1210. // The sweep's premise is that links were just rebuilt from the snapshot,
  1211. // which is exactly what a failed SyncInbound violates.
  1212. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1213. continue
  1214. }
  1215. var stillAttached []string
  1216. if err := tx.Table("clients").
  1217. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1218. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1219. Pluck("email", &stillAttached).Error; err != nil {
  1220. continue
  1221. }
  1222. stillSet := make(map[string]struct{}, len(stillAttached))
  1223. for _, e := range stillAttached {
  1224. stillSet[e] = struct{}{}
  1225. }
  1226. for email := range old.emails {
  1227. if _, kept := stillSet[email]; kept {
  1228. continue
  1229. }
  1230. var attachmentCount int64
  1231. if err := tx.Table("client_inbounds").
  1232. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1233. Where("clients.email = ?", email).
  1234. Count(&attachmentCount).Error; err != nil {
  1235. continue
  1236. }
  1237. if attachmentCount > 0 {
  1238. continue
  1239. }
  1240. // "Ended the merge unattached" is true for a real remote deletion and
  1241. // equally true for a bad merge, so record a strike instead of deleting.
  1242. if err := markSyncOrphan(tx, email, now); err != nil {
  1243. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1244. continue
  1245. }
  1246. structuralChange = true
  1247. }
  1248. }
  1249. if err := clearSyncOrphanMarks(tx); err != nil {
  1250. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1251. }
  1252. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1253. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1254. }
  1255. if err := tx.Commit().Error; err != nil {
  1256. return false, err
  1257. }
  1258. committed = true
  1259. if lifecycleLifted && !dirty {
  1260. var already model.Node
  1261. if err := database.GetDB().Select("config_dirty").Where("id = ?", nodeID).First(&already).Error; err == nil && already.ConfigDirty {
  1262. logger.Debugf("setRemoteTraffic: node %d lifecycle lift; already dirty", nodeID)
  1263. } else {
  1264. logger.Infof("setRemoteTraffic: node %d lifecycle lift; marking dirty for re-push", nodeID)
  1265. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1266. logger.Warningf("setRemoteTraffic: mark node %d dirty after lifecycle lift failed: %v", nodeID, err)
  1267. }
  1268. }
  1269. }
  1270. if len(adoptedInbounds) > 0 {
  1271. if mgr := runtime.GetManager(); mgr != nil {
  1272. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1273. if rem, ok := rt.(*runtime.Remote); ok {
  1274. for _, ib := range adoptedInbounds {
  1275. rem.RecordAdoptedInbound(ib)
  1276. }
  1277. }
  1278. }
  1279. }
  1280. }
  1281. if process := currentXrayProcess(); process != nil {
  1282. tree := snap.OnlineTree
  1283. switch {
  1284. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1285. // Old-build node (no GUID tree): key its flat online list under its
  1286. // own effective identity so attribution still works for that branch.
  1287. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1288. case guidShared && len(tree) > 0:
  1289. // Newer cloned node: its own clients arrive keyed under the shared
  1290. // panelGuid. Remap just that entry to the node-unique key so the
  1291. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1292. if _, ok := tree[nodeRow.Guid]; ok {
  1293. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1294. }
  1295. }
  1296. process.SetNodeOnlineTree(nodeID, tree)
  1297. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1298. if guidShared && len(activeTree) > 0 {
  1299. if _, ok := activeTree[nodeRow.Guid]; ok {
  1300. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1301. }
  1302. }
  1303. if len(activeTree) > 0 {
  1304. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1305. }
  1306. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1307. }
  1308. return structuralChange, nil
  1309. }
  1310. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1311. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1312. if err != nil {
  1313. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1314. return
  1315. }
  1316. if !restartOnDisable {
  1317. return
  1318. }
  1319. // Best-effort and never replayed: a hanging node must not hold the traffic poll.
  1320. common.GoRecover("restart-nodes-on-client-disable", func() {
  1321. for _, nodeID := range nodeIDs {
  1322. nodeIDCopy := nodeID
  1323. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1324. if rtErr != nil {
  1325. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1326. continue
  1327. }
  1328. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1329. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1330. }
  1331. }
  1332. })
  1333. }
  1334. func (s *InboundService) GetOnlineClients() []string {
  1335. process := currentXrayProcess()
  1336. if process == nil {
  1337. return []string{}
  1338. }
  1339. return process.GetOnlineClients()
  1340. }
  1341. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1342. // node that physically hosts each set: this panel's own clients under its own
  1343. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1344. // node-id keying so a client three hops down is attributed to its real node,
  1345. // not the intermediate one it was synced through.
  1346. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1347. process := currentXrayProcess()
  1348. if process == nil {
  1349. return map[string][]string{}
  1350. }
  1351. out := process.GetMergedNodeTrees()
  1352. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1353. if guid := s.panelGuid(); guid != "" {
  1354. out[guid] = mergeEmails(out[guid], local)
  1355. }
  1356. }
  1357. return out
  1358. }
  1359. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1360. // the grace window, keyed by the panelGuid of the node that physically hosts
  1361. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1362. // inbounds (old-build node or no active-inbound signal).
  1363. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1364. process := currentXrayProcess()
  1365. if process == nil {
  1366. return map[string][]string{}
  1367. }
  1368. out := process.GetMergedActiveInboundTrees()
  1369. active := process.GetLocalActiveInbounds()
  1370. if len(active) == 0 {
  1371. return out
  1372. }
  1373. guid := s.panelGuid()
  1374. if guid == "" {
  1375. return out
  1376. }
  1377. out[guid] = mergeEmails(out[guid], active)
  1378. return out
  1379. }
  1380. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1381. if process := currentXrayProcess(); process != nil {
  1382. process.SetNodeOnlineTree(nodeID, tree)
  1383. }
  1384. }
  1385. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1386. if process := currentXrayProcess(); process != nil {
  1387. process.ClearNodeOnlineClients(nodeID)
  1388. }
  1389. }
  1390. // RetainSyncedNodeOnlineClients keeps online clients only for nodes the traffic
  1391. // sync still fetches; a node missing from nodes was deleted.
  1392. func (s *InboundService) RetainSyncedNodeOnlineClients(nodes []*model.Node) {
  1393. process := currentXrayProcess()
  1394. if process == nil {
  1395. return
  1396. }
  1397. synced := make(map[int]bool, len(nodes))
  1398. for _, n := range nodes {
  1399. synced[n.Id] = n.Enable && n.Status == "online"
  1400. }
  1401. process.RetainNodeOnlineClients(func(nodeID int) bool { return synced[nodeID] })
  1402. }
  1403. // panelGuid returns this panel's stable self-identifier, used to key the local
  1404. // panel's own clients in the per-node online maps (#4983).
  1405. func (s *InboundService) panelGuid() string {
  1406. guid, _ := (&SettingService{}).GetPanelGuid()
  1407. return guid
  1408. }
  1409. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1410. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1411. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1412. // flat-topology case where an old-build node appears.
  1413. func synthNodeGuid(nodeID int) string {
  1414. return fmt.Sprintf("node:%d", nodeID)
  1415. }
  1416. // mergeEmails returns the deduped union of two email slices.
  1417. func mergeEmails(a, b []string) []string {
  1418. if len(a) == 0 {
  1419. return b
  1420. }
  1421. seen := make(map[string]struct{}, len(a)+len(b))
  1422. out := make([]string, 0, len(a)+len(b))
  1423. for _, e := range a {
  1424. if _, ok := seen[e]; !ok {
  1425. seen[e] = struct{}{}
  1426. out = append(out, e)
  1427. }
  1428. }
  1429. for _, e := range b {
  1430. if _, ok := seen[e]; !ok {
  1431. seen[e] = struct{}{}
  1432. out = append(out, e)
  1433. }
  1434. }
  1435. return out
  1436. }
  1437. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1438. if from == "" || to == "" || from == to {
  1439. return tree
  1440. }
  1441. remapped := make(map[string][]string, len(tree))
  1442. for guid, values := range tree {
  1443. if guid == from {
  1444. guid = to
  1445. }
  1446. remapped[guid] = mergeEmails(remapped[guid], values)
  1447. }
  1448. return remapped
  1449. }
  1450. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1451. if len(tree) == 0 {
  1452. return nil
  1453. }
  1454. out := make(map[string][]string, len(tree))
  1455. for guid, tags := range tree {
  1456. if guid == "" || len(tags) == 0 {
  1457. continue
  1458. }
  1459. seen := make(map[string]struct{}, len(tags))
  1460. for _, tag := range tags {
  1461. if tag == "" {
  1462. continue
  1463. }
  1464. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1465. tag = central.Tag
  1466. }
  1467. if _, dup := seen[tag]; dup {
  1468. continue
  1469. }
  1470. seen[tag] = struct{}{}
  1471. out[guid] = append(out[guid], tag)
  1472. }
  1473. }
  1474. if len(out) == 0 {
  1475. return nil
  1476. }
  1477. return out
  1478. }
  1479. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1480. allowed := make(map[string]struct{})
  1481. for _, ib := range inbounds {
  1482. if ib == nil {
  1483. continue
  1484. }
  1485. if _, ok := tagToCentral[ib.Tag]; !ok {
  1486. continue
  1487. }
  1488. if guid := originGuidFor(ib); guid != "" {
  1489. allowed[guid] = struct{}{}
  1490. }
  1491. }
  1492. return allowed
  1493. }
  1494. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1495. if len(tree) == 0 || len(allowed) == 0 {
  1496. return nil
  1497. }
  1498. out := make(map[string][]string, len(tree))
  1499. for guid, values := range tree {
  1500. if _, ok := allowed[guid]; !ok {
  1501. continue
  1502. }
  1503. if len(values) > 0 {
  1504. out[guid] = values
  1505. }
  1506. }
  1507. if len(out) == 0 {
  1508. return nil
  1509. }
  1510. return out
  1511. }
  1512. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1513. db := database.GetDB()
  1514. var rows []xray.ClientTraffic
  1515. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1516. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1517. return nil, err
  1518. }
  1519. result := make(map[string]int64, len(rows))
  1520. for _, r := range rows {
  1521. result[r.Email] = r.LastOnline
  1522. }
  1523. return result, nil
  1524. }
  1525. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1526. // panel's own xray this poll into the local online/active sets, applying the
  1527. // grace window and pruning stale entries. Pass nil to only prune. See
  1528. // xray.Process for why the local sets are kept separate from the shared
  1529. // last_online column.
  1530. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1531. if process := currentXrayProcess(); process != nil {
  1532. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1533. }
  1534. }
  1535. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1536. db := database.GetDB()
  1537. // Step 1: Get ClientTraffic records for emails in the input list.
  1538. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1539. uniqEmails := uniqueNonEmptyStrings(emails)
  1540. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1541. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1542. var page []xray.ClientTraffic
  1543. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1544. return nil, nil, err
  1545. }
  1546. clients = append(clients, page...)
  1547. }
  1548. // Step 2: Sort clients by (Up + Down) descending
  1549. sort.Slice(clients, func(i, j int) bool {
  1550. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1551. })
  1552. // Step 3: Extract sorted valid emails and track found ones
  1553. validEmails := make([]string, 0, len(clients))
  1554. found := make(map[string]bool)
  1555. for _, client := range clients {
  1556. validEmails = append(validEmails, client.Email)
  1557. found[client.Email] = true
  1558. }
  1559. // Step 4: Identify emails that were not found in the database
  1560. extraEmails := make([]string, 0)
  1561. for _, email := range emails {
  1562. if !found[email] {
  1563. extraEmails = append(extraEmails, email)
  1564. }
  1565. }
  1566. return validEmails, extraEmails, nil
  1567. }