1
0

inbound_node.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  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.ResetWeekday <= 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. ResetWeekday: cs.ResetWeekday,
  909. ResetMax: cs.ResetMax,
  910. ResetCount: cs.ResetCount,
  911. Up: seedUp,
  912. Down: seedDown,
  913. LastOnline: cs.LastOnline,
  914. }
  915. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  916. Create(row).Error; err != nil {
  917. return false, err
  918. }
  919. centralCS[csKey{c.Id, cs.Email}] = row
  920. centralCSByEmail[cs.Email] = row
  921. existingEmails[cs.Email] = struct{}{}
  922. structuralChange = true
  923. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  924. return false, err
  925. }
  926. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  927. continue
  928. }
  929. existing := centralCSByEmail[cs.Email]
  930. if existing != nil {
  931. expiryChanged := !lifecycleFrozen && existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime)
  932. // Only a real latch to disabled is structural; one-way merge never
  933. // re-enables from the node.
  934. enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
  935. !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
  936. metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset || existing.ResetWeekday != cs.ResetWeekday)
  937. if enableChanged || metaChanged || expiryChanged {
  938. structuralChange = true
  939. }
  940. }
  941. renewed := !lifecycleFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base)
  942. if renewed {
  943. // Reject when the node's own settings still carry the old absolute:
  944. // lagging ClientStats after a master shorten mimic a renew (#6228).
  945. if snapExpiries == nil {
  946. snapExpiries = settingsClientAbsoluteExpiries(snapIb.Settings)
  947. }
  948. if se, ok := snapExpiries[cs.Email]; ok && se <= existing.ExpiryTime {
  949. renewed = false
  950. }
  951. }
  952. if renewed {
  953. // A renewal starts a fresh quota window: adopt the node's counters
  954. // and enable state, drop stale pushes (mirrors autoRenewClients).
  955. if err := tx.Exec(
  956. fmt.Sprintf(
  957. `UPDATE client_traffics
  958. SET up = ?, down = ?, enable = ?, total = ?,
  959. expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s
  960. WHERE email = ?`,
  961. database.GreatestExpr("last_online", "?"),
  962. ),
  963. canon.Up, canon.Down, cs.Enable, cs.Total,
  964. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount,
  965. cs.LastOnline, cs.Email,
  966. ).Error; err != nil {
  967. return false, err
  968. }
  969. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  970. return false, err
  971. }
  972. existing.Up = canon.Up
  973. existing.Down = canon.Down
  974. existing.Enable = cs.Enable
  975. existing.Total = cs.Total
  976. existing.ExpiryTime = cs.ExpiryTime
  977. existing.Reset = cs.Reset
  978. existing.ResetWeekday = cs.ResetWeekday
  979. existing.ResetCount = cs.ResetCount
  980. structuralChange = true
  981. } else if lifecycleFrozen {
  982. // Push pending or just landed: only counters may move, the master
  983. // keeps expiry/enable/total/reset.
  984. if err := tx.Exec(
  985. fmt.Sprintf(
  986. `UPDATE client_traffics
  987. SET up = %s, down = %s, last_online = %s
  988. WHERE email = ?`,
  989. database.ClampedAddExpr("up"),
  990. database.ClampedAddExpr("down"),
  991. database.GreatestExpr("last_online", "?"),
  992. ),
  993. deltaUp, deltaDown, cs.LastOnline, cs.Email,
  994. ).Error; err != nil {
  995. return false, err
  996. }
  997. if existing != nil {
  998. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  999. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1000. }
  1001. } else {
  1002. enableExpr := database.ClientTrafficEnableMergeExpr()
  1003. expiryExpr := database.ClientTrafficExpiryMergeExpr()
  1004. if err := tx.Exec(
  1005. fmt.Sprintf(
  1006. `UPDATE client_traffics
  1007. SET up = %s, down = %s, enable = %s, total = ?,
  1008. expiry_time = %s,
  1009. reset = ?, reset_day = ?, reset_weekday = ?, last_online = %s
  1010. WHERE email = ?`,
  1011. database.ClampedAddExpr("up"),
  1012. database.ClampedAddExpr("down"),
  1013. enableExpr,
  1014. expiryExpr,
  1015. database.GreatestExpr("last_online", "?"),
  1016. ),
  1017. deltaUp, deltaDown,
  1018. cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
  1019. cs.Total,
  1020. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday,
  1021. cs.LastOnline, cs.Email,
  1022. ).Error; err != nil {
  1023. return false, err
  1024. }
  1025. if existing != nil {
  1026. priorExpiry := existing.ExpiryTime
  1027. if !cs.Enable && !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown) {
  1028. existing.Enable = false
  1029. }
  1030. existing.ExpiryTime = mergeActivationExpiry(priorExpiry, cs.ExpiryTime)
  1031. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1032. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1033. existing.Total = cs.Total
  1034. existing.Reset = cs.Reset
  1035. existing.ResetWeekday = cs.ResetWeekday
  1036. }
  1037. }
  1038. // A dip plus a lagging longer expiry mimics nodeClientRenewed and would
  1039. // undo a master shorten once the freeze lifts (#6228).
  1040. if lifecycleFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) {
  1041. continue
  1042. }
  1043. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  1044. return false, err
  1045. }
  1046. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  1047. }
  1048. for k, existing := range centralCS {
  1049. if dirty {
  1050. continue
  1051. }
  1052. if k.inboundID != c.Id {
  1053. continue
  1054. }
  1055. if _, kept := snapEmails[k.email]; kept {
  1056. continue
  1057. }
  1058. // Gone from this inbound's stats but still reported by the node under
  1059. // a sibling inbound: both the shared accumulator row and the (node,
  1060. // email) baseline must survive, or the sibling's next delta would
  1061. // compute against nothing and freeze the counter (#5202).
  1062. if _, still := snapEmailsAll[k.email]; still {
  1063. continue
  1064. }
  1065. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1066. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1067. return false, err
  1068. }
  1069. // Same shared-accumulator rule as the inbound-removal sweep above:
  1070. // keep the row while another inbound still references the email.
  1071. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  1072. if uErr != nil {
  1073. return false, uErr
  1074. }
  1075. // Usage, quota and expiry live on this row, so a client the orphan
  1076. // sweep will mark keeps it until the reaper confirms the removal.
  1077. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  1078. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1079. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1080. return false, err
  1081. }
  1082. }
  1083. structuralChange = true
  1084. }
  1085. }
  1086. type oldSet struct {
  1087. inboundID int
  1088. emails map[string]struct{}
  1089. }
  1090. var perInboundOld []oldSet
  1091. syncFailedInbounds := map[int]struct{}{}
  1092. for _, p := range pendingAdopts {
  1093. lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, centralCSByEmail)
  1094. adoptedSettings := p.wireSettings
  1095. if liftChanged {
  1096. adoptedSettings = lifted
  1097. lifecycleLifted = true
  1098. }
  1099. if p.central.Settings != adoptedSettings {
  1100. if err := tx.Model(model.Inbound{}).
  1101. Where("id = ?", p.central.Id).
  1102. Update("settings", adoptedSettings).Error; err != nil {
  1103. return false, err
  1104. }
  1105. structuralChange = true
  1106. }
  1107. // The fingerprint stamps the un-lifted wire blob on purpose: a lift must
  1108. // leave reconcile a mismatch to re-push against.
  1109. if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
  1110. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
  1111. }
  1112. }
  1113. for _, snapIb := range snap.Inbounds {
  1114. if snapIb == nil {
  1115. continue
  1116. }
  1117. c, ok := tagToCentral[snapIb.Tag]
  1118. if !ok {
  1119. continue
  1120. }
  1121. if dirty {
  1122. continue
  1123. }
  1124. var oldEmailsRows []string
  1125. if err := tx.Table("clients").
  1126. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1127. Where("client_inbounds.inbound_id = ?", c.Id).
  1128. Pluck("email", &oldEmailsRows).Error; err == nil {
  1129. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1130. for _, e := range oldEmailsRows {
  1131. if e != "" {
  1132. oldEmails[e] = struct{}{}
  1133. }
  1134. }
  1135. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1136. }
  1137. clients, gcErr := s.GetClients(snapIb)
  1138. if gcErr != nil {
  1139. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1140. continue
  1141. }
  1142. csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
  1143. for _, cs := range snapIb.ClientStats {
  1144. csByEmail[cs.Email] = cs
  1145. }
  1146. filtered := clients[:0]
  1147. for i := range clients {
  1148. if isClientEmailTombstoned(clients[i].Email) {
  1149. continue
  1150. }
  1151. existing := centralCSByEmail[clients[i].Email]
  1152. var csPtr *xray.ClientTraffic
  1153. if cs, hit := csByEmail[clients[i].Email]; hit {
  1154. csCopy := cs
  1155. csPtr = &csCopy
  1156. }
  1157. applyMasterClientLifecycle(&clients[i], existing, csPtr)
  1158. filtered = append(filtered, clients[i])
  1159. }
  1160. localEmails := make([]string, 0, len(filtered))
  1161. for i := range filtered {
  1162. if filtered[i].Email != "" {
  1163. localEmails = append(localEmails, filtered[i].Email)
  1164. }
  1165. }
  1166. if len(localEmails) > 0 {
  1167. var localMeta []struct {
  1168. Email string
  1169. Comment string `gorm:"column:comment"`
  1170. }
  1171. if err := tx.Table("clients").
  1172. Select("email, comment").
  1173. Where("email IN ?", localEmails).
  1174. Find(&localMeta).Error; err == nil {
  1175. commentByEmail := make(map[string]string, len(localMeta))
  1176. for _, m := range localMeta {
  1177. commentByEmail[m.Email] = m.Comment
  1178. }
  1179. for i := range filtered {
  1180. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1181. filtered[i].Comment = cmt
  1182. }
  1183. }
  1184. }
  1185. }
  1186. if len(localEmails) > 0 {
  1187. foreign, err := clientEmailsOwnedElsewhere(tx, nodeID, localEmails)
  1188. if err != nil {
  1189. return false, err
  1190. }
  1191. if len(foreign) > 0 {
  1192. kept := filtered[:0]
  1193. for i := range filtered {
  1194. if _, claimed := foreign[filtered[i].Email]; !claimed {
  1195. kept = append(kept, filtered[i])
  1196. continue
  1197. }
  1198. key := fmt.Sprintf("%d:%s", nodeID, filtered[i].Email)
  1199. if _, seen := reportedForeignClientClaim.LoadOrStore(key, struct{}{}); !seen {
  1200. logger.Warningf(
  1201. "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)",
  1202. nodeID, filtered[i].Email,
  1203. )
  1204. }
  1205. }
  1206. filtered = kept
  1207. }
  1208. }
  1209. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1210. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1211. syncFailedInbounds[c.Id] = struct{}{}
  1212. }
  1213. }
  1214. for _, old := range perInboundOld {
  1215. // The sweep's premise is that links were just rebuilt from the snapshot,
  1216. // which is exactly what a failed SyncInbound violates.
  1217. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1218. continue
  1219. }
  1220. var stillAttached []string
  1221. if err := tx.Table("clients").
  1222. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1223. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1224. Pluck("email", &stillAttached).Error; err != nil {
  1225. continue
  1226. }
  1227. stillSet := make(map[string]struct{}, len(stillAttached))
  1228. for _, e := range stillAttached {
  1229. stillSet[e] = struct{}{}
  1230. }
  1231. for email := range old.emails {
  1232. if _, kept := stillSet[email]; kept {
  1233. continue
  1234. }
  1235. var attachmentCount int64
  1236. if err := tx.Table("client_inbounds").
  1237. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1238. Where("clients.email = ?", email).
  1239. Count(&attachmentCount).Error; err != nil {
  1240. continue
  1241. }
  1242. if attachmentCount > 0 {
  1243. continue
  1244. }
  1245. // "Ended the merge unattached" is true for a real remote deletion and
  1246. // equally true for a bad merge, so record a strike instead of deleting.
  1247. if err := markSyncOrphan(tx, email, now); err != nil {
  1248. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1249. continue
  1250. }
  1251. structuralChange = true
  1252. }
  1253. }
  1254. if err := clearSyncOrphanMarks(tx); err != nil {
  1255. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1256. }
  1257. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1258. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1259. }
  1260. if err := tx.Commit().Error; err != nil {
  1261. return false, err
  1262. }
  1263. committed = true
  1264. if lifecycleLifted && !dirty {
  1265. var already model.Node
  1266. if err := database.GetDB().Select("config_dirty").Where("id = ?", nodeID).First(&already).Error; err == nil && already.ConfigDirty {
  1267. logger.Debugf("setRemoteTraffic: node %d lifecycle lift; already dirty", nodeID)
  1268. } else {
  1269. logger.Infof("setRemoteTraffic: node %d lifecycle lift; marking dirty for re-push", nodeID)
  1270. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1271. logger.Warningf("setRemoteTraffic: mark node %d dirty after lifecycle lift failed: %v", nodeID, err)
  1272. }
  1273. }
  1274. }
  1275. if len(adoptedInbounds) > 0 {
  1276. if mgr := runtime.GetManager(); mgr != nil {
  1277. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1278. if rem, ok := rt.(*runtime.Remote); ok {
  1279. for _, ib := range adoptedInbounds {
  1280. rem.RecordAdoptedInbound(ib)
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. if process := currentXrayProcess(); process != nil {
  1287. tree := snap.OnlineTree
  1288. switch {
  1289. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1290. // Old-build node (no GUID tree): key its flat online list under its
  1291. // own effective identity so attribution still works for that branch.
  1292. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1293. case guidShared && len(tree) > 0:
  1294. // Newer cloned node: its own clients arrive keyed under the shared
  1295. // panelGuid. Remap just that entry to the node-unique key so the
  1296. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1297. if _, ok := tree[nodeRow.Guid]; ok {
  1298. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1299. }
  1300. }
  1301. process.SetNodeOnlineTree(nodeID, tree)
  1302. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1303. if guidShared && len(activeTree) > 0 {
  1304. if _, ok := activeTree[nodeRow.Guid]; ok {
  1305. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1306. }
  1307. }
  1308. if len(activeTree) > 0 {
  1309. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1310. }
  1311. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1312. }
  1313. return structuralChange, nil
  1314. }
  1315. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1316. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1317. if err != nil {
  1318. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1319. return
  1320. }
  1321. if !restartOnDisable {
  1322. return
  1323. }
  1324. // Best-effort and never replayed: a hanging node must not hold the traffic poll.
  1325. common.GoRecover("restart-nodes-on-client-disable", func() {
  1326. for _, nodeID := range nodeIDs {
  1327. nodeIDCopy := nodeID
  1328. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1329. if rtErr != nil {
  1330. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1331. continue
  1332. }
  1333. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1334. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1335. }
  1336. }
  1337. })
  1338. }
  1339. func (s *InboundService) GetOnlineClients() []string {
  1340. process := currentXrayProcess()
  1341. if process == nil {
  1342. return []string{}
  1343. }
  1344. return process.GetOnlineClients()
  1345. }
  1346. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1347. // node that physically hosts each set: this panel's own clients under its own
  1348. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1349. // node-id keying so a client three hops down is attributed to its real node,
  1350. // not the intermediate one it was synced through.
  1351. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1352. process := currentXrayProcess()
  1353. if process == nil {
  1354. return map[string][]string{}
  1355. }
  1356. out := process.GetMergedNodeTrees()
  1357. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1358. if guid := s.panelGuid(); guid != "" {
  1359. out[guid] = mergeEmails(out[guid], local)
  1360. }
  1361. }
  1362. return out
  1363. }
  1364. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1365. // the grace window, keyed by the panelGuid of the node that physically hosts
  1366. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1367. // inbounds (old-build node or no active-inbound signal).
  1368. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1369. process := currentXrayProcess()
  1370. if process == nil {
  1371. return map[string][]string{}
  1372. }
  1373. out := process.GetMergedActiveInboundTrees()
  1374. active := process.GetLocalActiveInbounds()
  1375. if len(active) == 0 {
  1376. return out
  1377. }
  1378. guid := s.panelGuid()
  1379. if guid == "" {
  1380. return out
  1381. }
  1382. out[guid] = mergeEmails(out[guid], active)
  1383. return out
  1384. }
  1385. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1386. if process := currentXrayProcess(); process != nil {
  1387. process.SetNodeOnlineTree(nodeID, tree)
  1388. }
  1389. }
  1390. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1391. if process := currentXrayProcess(); process != nil {
  1392. process.ClearNodeOnlineClients(nodeID)
  1393. }
  1394. }
  1395. // RetainSyncedNodeOnlineClients keeps online clients only for nodes the traffic
  1396. // sync still fetches; a node missing from nodes was deleted.
  1397. func (s *InboundService) RetainSyncedNodeOnlineClients(nodes []*model.Node) {
  1398. process := currentXrayProcess()
  1399. if process == nil {
  1400. return
  1401. }
  1402. synced := make(map[int]bool, len(nodes))
  1403. for _, n := range nodes {
  1404. synced[n.Id] = n.Enable && n.Status == "online"
  1405. }
  1406. process.RetainNodeOnlineClients(func(nodeID int) bool { return synced[nodeID] })
  1407. }
  1408. // panelGuid returns this panel's stable self-identifier, used to key the local
  1409. // panel's own clients in the per-node online maps (#4983).
  1410. func (s *InboundService) panelGuid() string {
  1411. guid, _ := (&SettingService{}).GetPanelGuid()
  1412. return guid
  1413. }
  1414. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1415. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1416. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1417. // flat-topology case where an old-build node appears.
  1418. func synthNodeGuid(nodeID int) string {
  1419. return fmt.Sprintf("node:%d", nodeID)
  1420. }
  1421. // mergeEmails returns the deduped union of two email slices.
  1422. func mergeEmails(a, b []string) []string {
  1423. if len(a) == 0 {
  1424. return b
  1425. }
  1426. seen := make(map[string]struct{}, len(a)+len(b))
  1427. out := make([]string, 0, len(a)+len(b))
  1428. for _, e := range a {
  1429. if _, ok := seen[e]; !ok {
  1430. seen[e] = struct{}{}
  1431. out = append(out, e)
  1432. }
  1433. }
  1434. for _, e := range b {
  1435. if _, ok := seen[e]; !ok {
  1436. seen[e] = struct{}{}
  1437. out = append(out, e)
  1438. }
  1439. }
  1440. return out
  1441. }
  1442. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1443. if from == "" || to == "" || from == to {
  1444. return tree
  1445. }
  1446. remapped := make(map[string][]string, len(tree))
  1447. for guid, values := range tree {
  1448. if guid == from {
  1449. guid = to
  1450. }
  1451. remapped[guid] = mergeEmails(remapped[guid], values)
  1452. }
  1453. return remapped
  1454. }
  1455. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1456. if len(tree) == 0 {
  1457. return nil
  1458. }
  1459. out := make(map[string][]string, len(tree))
  1460. for guid, tags := range tree {
  1461. if guid == "" || len(tags) == 0 {
  1462. continue
  1463. }
  1464. seen := make(map[string]struct{}, len(tags))
  1465. for _, tag := range tags {
  1466. if tag == "" {
  1467. continue
  1468. }
  1469. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1470. tag = central.Tag
  1471. }
  1472. if _, dup := seen[tag]; dup {
  1473. continue
  1474. }
  1475. seen[tag] = struct{}{}
  1476. out[guid] = append(out[guid], tag)
  1477. }
  1478. }
  1479. if len(out) == 0 {
  1480. return nil
  1481. }
  1482. return out
  1483. }
  1484. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1485. allowed := make(map[string]struct{})
  1486. for _, ib := range inbounds {
  1487. if ib == nil {
  1488. continue
  1489. }
  1490. if _, ok := tagToCentral[ib.Tag]; !ok {
  1491. continue
  1492. }
  1493. if guid := originGuidFor(ib); guid != "" {
  1494. allowed[guid] = struct{}{}
  1495. }
  1496. }
  1497. return allowed
  1498. }
  1499. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1500. if len(tree) == 0 || len(allowed) == 0 {
  1501. return nil
  1502. }
  1503. out := make(map[string][]string, len(tree))
  1504. for guid, values := range tree {
  1505. if _, ok := allowed[guid]; !ok {
  1506. continue
  1507. }
  1508. if len(values) > 0 {
  1509. out[guid] = values
  1510. }
  1511. }
  1512. if len(out) == 0 {
  1513. return nil
  1514. }
  1515. return out
  1516. }
  1517. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1518. db := database.GetDB()
  1519. var rows []xray.ClientTraffic
  1520. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1521. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1522. return nil, err
  1523. }
  1524. result := make(map[string]int64, len(rows))
  1525. for _, r := range rows {
  1526. result[r.Email] = r.LastOnline
  1527. }
  1528. return result, nil
  1529. }
  1530. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1531. // panel's own xray this poll into the local online/active sets, applying the
  1532. // grace window and pruning stale entries. Pass nil to only prune. See
  1533. // xray.Process for why the local sets are kept separate from the shared
  1534. // last_online column.
  1535. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1536. if process := currentXrayProcess(); process != nil {
  1537. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1538. }
  1539. }
  1540. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1541. db := database.GetDB()
  1542. // Step 1: Get ClientTraffic records for emails in the input list.
  1543. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1544. uniqEmails := uniqueNonEmptyStrings(emails)
  1545. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1546. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1547. var page []xray.ClientTraffic
  1548. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1549. return nil, nil, err
  1550. }
  1551. clients = append(clients, page...)
  1552. }
  1553. // Step 2: Sort clients by (Up + Down) descending
  1554. sort.Slice(clients, func(i, j int) bool {
  1555. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1556. })
  1557. // Step 3: Extract sorted valid emails and track found ones
  1558. validEmails := make([]string, 0, len(clients))
  1559. found := make(map[string]bool)
  1560. for _, client := range clients {
  1561. validEmails = append(validEmails, client.Email)
  1562. found[client.Email] = true
  1563. }
  1564. // Step 4: Identify emails that were not found in the database
  1565. extraEmails := make([]string, 0)
  1566. for _, email := range emails {
  1567. if !found[email] {
  1568. extraEmails = append(extraEmails, email)
  1569. }
  1570. }
  1571. return validEmails, extraEmails, nil
  1572. }