inbound_node.go 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  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. // ExcludeFromSub stays master-authored: older nodes omit the field and
  386. // would otherwise reset it to false on every heartbeat mirror.
  387. a.Listen = snapIb.Listen
  388. a.Port = snapIb.Port
  389. a.Protocol = snapIb.Protocol
  390. a.Total = snapIb.Total
  391. a.ExpiryTime = snapIb.ExpiryTime
  392. a.Settings = adoptedSettings
  393. a.StreamSettings = snapIb.StreamSettings
  394. a.Sniffing = snapIb.Sniffing
  395. a.TrafficReset = snapIb.TrafficReset
  396. a.TrafficResetDay = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  397. return &a
  398. }
  399. // clientEmailsOwnedElsewhere returns the emails attached only to inbounds of
  400. // other nodes: email is unique, so adopting one would overwrite a client this
  401. // node does not serve. Attached nowhere means soft-orphaned, hence adoptable.
  402. func clientEmailsOwnedElsewhere(tx *gorm.DB, nodeID int, emails []string) (map[string]struct{}, error) {
  403. attachedEmails := func(nodeScoped bool) ([]string, error) {
  404. q := tx.Table("clients").
  405. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  406. Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id").
  407. Where("clients.email IN ?", emails)
  408. if nodeScoped {
  409. q = q.Where("inbounds.node_id = ?", nodeID)
  410. }
  411. var rows []string
  412. err := q.Pluck("clients.email", &rows).Error
  413. return rows, err
  414. }
  415. attached, err := attachedEmails(false)
  416. if err != nil {
  417. return nil, err
  418. }
  419. if len(attached) == 0 {
  420. return nil, nil
  421. }
  422. owned, err := attachedEmails(true)
  423. if err != nil {
  424. return nil, err
  425. }
  426. ownedSet := make(map[string]struct{}, len(owned))
  427. for _, email := range owned {
  428. ownedSet[email] = struct{}{}
  429. }
  430. foreign := make(map[string]struct{})
  431. for _, email := range attached {
  432. if _, ok := ownedSet[email]; !ok {
  433. foreign[email] = struct{}{}
  434. }
  435. }
  436. return foreign, nil
  437. }
  438. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) {
  439. if snap == nil || nodeID <= 0 {
  440. return false, nil
  441. }
  442. db := database.GetDB()
  443. now := time.Now().UnixMilli()
  444. // originGuidFor attributes a synced inbound to the panel that physically
  445. // hosts it. A node's OWN inbounds report either an empty origin or — on
  446. // builds that set it locally — the node's own panelGuid; both resolve to
  447. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  448. // (shared with another node or the master, i.e. a cloned server), in which
  449. // case it falls back to the node-unique id so #4983 attribution doesn't
  450. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  451. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  452. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  453. var nodeRow model.Node
  454. db.Select("guid", "config_dirty", "inbound_sync_mode", "inbound_tags").Where("id = ?", nodeID).First(&nodeRow)
  455. // Re-read inside the serialized writer: a client added while this snapshot
  456. // was in flight marks the node dirty after the caller sampled the flag.
  457. dirty = dirty || nodeRow.ConfigDirty
  458. // Adoption, record sync and sweeps still run on a just-pushed tick; only the
  459. // client lifecycle merge waits for a snapshot that reflects the push.
  460. lifecycleFrozen := dirty || justPushed
  461. nodeRow.Id = nodeID
  462. unmanagedTag := unmanagedTagPredicate(&nodeRow)
  463. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  464. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  465. originGuidFor := func(snapIb *model.Inbound) string {
  466. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  467. return snapIb.OriginNodeGuid
  468. }
  469. return selfKey
  470. }
  471. var central []model.Inbound
  472. if err := db.Model(model.Inbound{}).
  473. Where("node_id = ?", nodeID).
  474. Find(&central).Error; err != nil {
  475. return false, err
  476. }
  477. // Index under the stored tag and its prefix-flipped form so a snap matches
  478. // whether the n<id>- prefix lives on the node side, the central side, or
  479. // neither — a mismatch must never spawn a duplicate central inbound.
  480. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  481. prefix := nodeTagPrefix(&nodeID)
  482. for i := range central {
  483. tagToCentral[central[i].Tag] = &central[i]
  484. if prefix != "" {
  485. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  486. tagToCentral[stripped] = &central[i]
  487. } else {
  488. tagToCentral[prefix+central[i].Tag] = &central[i]
  489. }
  490. }
  491. }
  492. var centralClientStats []xray.ClientTraffic
  493. if len(central) > 0 {
  494. ids := make([]int, 0, len(central))
  495. for i := range central {
  496. ids = append(ids, central[i].Id)
  497. }
  498. if err := db.Model(xray.ClientTraffic{}).
  499. Where("inbound_id IN ?", ids).
  500. Find(&centralClientStats).Error; err != nil {
  501. return false, err
  502. }
  503. }
  504. type csKey struct {
  505. inboundID int
  506. email string
  507. }
  508. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  509. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  510. for i := range centralClientStats {
  511. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  512. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  513. }
  514. nodeBaselines := make(map[string]nodeTrafficCounter)
  515. var baselineRows []model.NodeClientTraffic
  516. if err := db.Model(&model.NodeClientTraffic{}).
  517. Where("node_id = ?", nodeID).
  518. Find(&baselineRows).Error; err != nil {
  519. return false, err
  520. }
  521. for i := range baselineRows {
  522. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  523. }
  524. var defaultUserId int
  525. if len(central) > 0 {
  526. defaultUserId = central[0].UserId
  527. } else {
  528. var u model.User
  529. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  530. defaultUserId = u.Id
  531. } else {
  532. defaultUserId = 1
  533. }
  534. }
  535. // Union of every email the snapshot still reports, across all inbounds.
  536. // The (node, email) baseline rows are keyed per node, not per inbound, so
  537. // the sweeps below must only drop one when the email left the node
  538. // entirely — an email whose stats moved to (or always lived under) a
  539. // sibling inbound still needs its baseline for the sibling's delta
  540. // computation (#5202).
  541. //
  542. // Xray counts traffic per email, not per inbound, so a multi-attached
  543. // client's shared counter is copied onto every inbound it's on. Fold each
  544. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  545. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  546. snapEmailsAll := make(map[string]struct{})
  547. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  548. for _, snapIb := range snap.Inbounds {
  549. if snapIb == nil {
  550. continue
  551. }
  552. for i := range snapIb.ClientStats {
  553. email := snapIb.ClientStats[i].Email
  554. snapEmailsAll[email] = struct{}{}
  555. cur := nodeEmailTotals[email]
  556. if snapIb.ClientStats[i].Up > cur.Up {
  557. cur.Up = snapIb.ClientStats[i].Up
  558. }
  559. if snapIb.ClientStats[i].Down > cur.Down {
  560. cur.Down = snapIb.ClientStats[i].Down
  561. }
  562. nodeEmailTotals[email] = cur
  563. }
  564. }
  565. // Membership set for the rowExists checks below. Only the snapshot's emails
  566. // are ever probed, so scope the lookup to those instead of plucking the whole
  567. // client_traffics table (50k+ rows) on every node poll.
  568. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  569. if len(snapEmailsAll) > 0 {
  570. snapEmailList := make([]string, 0, len(snapEmailsAll))
  571. for email := range snapEmailsAll {
  572. snapEmailList = append(snapEmailList, email)
  573. }
  574. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  575. var found []string
  576. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  577. return false, err
  578. }
  579. for _, e := range found {
  580. existingEmails[e] = struct{}{}
  581. }
  582. }
  583. }
  584. tx := db.Begin()
  585. committed := false
  586. defer func() {
  587. if !committed {
  588. tx.Rollback()
  589. }
  590. }()
  591. structuralChange := false
  592. lifecycleLifted := false
  593. var adoptedInbounds []*model.Inbound
  594. type pendingAdopt struct {
  595. central *model.Inbound
  596. snapIb *model.Inbound
  597. wireSettings string
  598. }
  599. var pendingAdopts []pendingAdopt
  600. newInboundIDs := make(map[int]struct{})
  601. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  602. for _, snapIb := range snap.Inbounds {
  603. if snapIb == nil {
  604. continue
  605. }
  606. snapTags[snapIb.Tag] = struct{}{}
  607. // Record the prefix-flipped form too so the orphan sweep below keeps a
  608. // central inbound whether its tag carries the n<id>- prefix or not.
  609. if prefix != "" {
  610. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  611. snapTags[stripped] = struct{}{}
  612. } else {
  613. snapTags[prefix+snapIb.Tag] = struct{}{}
  614. }
  615. }
  616. c, ok := tagToCentral[snapIb.Tag]
  617. if !ok {
  618. origin := originGuidFor(snapIb)
  619. var compatible []*model.Inbound
  620. for i := range central {
  621. candidate := &central[i]
  622. if candidate.OriginNodeGuid == origin &&
  623. candidate.Port == snapIb.Port &&
  624. candidate.Protocol == snapIb.Protocol &&
  625. strings.TrimSpace(candidate.Listen) == strings.TrimSpace(snapIb.Listen) {
  626. compatible = append(compatible, candidate)
  627. }
  628. }
  629. switch len(compatible) {
  630. case 1:
  631. c, ok = compatible[0], true
  632. tagToCentral[snapIb.Tag] = c
  633. snapTags[c.Tag] = struct{}{}
  634. case 0:
  635. // A genuinely new inbound follows the normal adoption path.
  636. default:
  637. return false, fmt.Errorf("setRemoteTraffic: inbound %q has ambiguous compatible central aliases", snapIb.Tag)
  638. }
  639. }
  640. if !ok {
  641. if dirty {
  642. continue
  643. }
  644. // Try snap.Tag first; on collision fall back to the n<id>-
  645. // prefixed form so local+node can both own the same port.
  646. pickFreeTag := func() (string, error) {
  647. candidates := []string{snapIb.Tag}
  648. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  649. candidates = append(candidates, prefix+snapIb.Tag)
  650. }
  651. for _, t := range candidates {
  652. var owner model.Inbound
  653. err := tx.Where("tag = ?", t).First(&owner).Error
  654. if errors.Is(err, gorm.ErrRecordNotFound) {
  655. return t, nil
  656. }
  657. if err != nil {
  658. return "", err
  659. }
  660. }
  661. return "", nil
  662. }
  663. chosenTag, err := pickFreeTag()
  664. if err != nil {
  665. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  666. continue
  667. }
  668. if chosenTag == "" {
  669. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  670. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  671. logger.Warningf(
  672. "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)",
  673. snapIb.Tag, nodeID, nodeID,
  674. )
  675. }
  676. continue
  677. }
  678. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  679. newIb := model.Inbound{
  680. UserId: defaultUserId,
  681. NodeID: &nodeID,
  682. OriginNodeGuid: originGuidFor(snapIb),
  683. Tag: chosenTag,
  684. Listen: snapIb.Listen,
  685. Port: snapIb.Port,
  686. Protocol: snapIb.Protocol,
  687. Settings: snapIb.Settings,
  688. StreamSettings: snapIb.StreamSettings,
  689. Sniffing: snapIb.Sniffing,
  690. TrafficReset: snapIb.TrafficReset,
  691. TrafficResetDay: normalizeTrafficResetDay(snapIb.TrafficResetDay),
  692. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  693. Enable: snapIb.Enable,
  694. Remark: snapIb.Remark,
  695. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  696. ExcludeFromSub: snapIb.ExcludeFromSub,
  697. Total: snapIb.Total,
  698. ExpiryTime: snapIb.ExpiryTime,
  699. Up: snapIb.Up,
  700. Down: snapIb.Down,
  701. ShareAddrStrategy: "node",
  702. DisableFlow: snapIb.DisableFlow,
  703. }
  704. if err := tx.Create(&newIb).Error; err != nil {
  705. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  706. continue
  707. }
  708. tagToCentral[snapIb.Tag] = &newIb
  709. if newIb.Tag != snapIb.Tag {
  710. tagToCentral[newIb.Tag] = &newIb
  711. }
  712. if rows := adoptedHostRows(snap.HostGroups, snapIb.Id, newIb.Id); len(rows) > 0 {
  713. if err := tx.Create(&rows).Error; err != nil {
  714. logger.Warningf("setRemoteTraffic: adopt host rows for tag %q failed: %v", newIb.Tag, err)
  715. }
  716. }
  717. newInboundIDs[newIb.Id] = struct{}{}
  718. structuralChange = true
  719. continue
  720. }
  721. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  722. // Adopting the node's settings verbatim would re-add a client the master
  723. // deleted moments ago if this snapshot was fetched before the deletion
  724. // push landed — filter just-deleted emails out while their tombstone lives.
  725. adoptedSettings := snapIb.Settings
  726. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  727. adoptedSettings = stripped
  728. }
  729. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  730. adoptedSettings = deduped
  731. }
  732. updates := map[string]any{}
  733. if !dirty {
  734. // Defer lifecycle lift until after client_traffics absorbs this tick's
  735. // deltas so quota stale-disable matches SQL (#6228).
  736. pendingAdopts = append(pendingAdopts, pendingAdopt{
  737. central: c, snapIb: snapIb, wireSettings: adoptedSettings,
  738. })
  739. updates["enable"] = snapIb.Enable
  740. updates["remark"] = snapIb.Remark
  741. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  742. updates["listen"] = snapIb.Listen
  743. updates["port"] = snapIb.Port
  744. updates["protocol"] = snapIb.Protocol
  745. updates["total"] = snapIb.Total
  746. updates["expiry_time"] = snapIb.ExpiryTime
  747. updates["stream_settings"] = snapIb.StreamSettings
  748. updates["sniffing"] = snapIb.Sniffing
  749. updates["traffic_reset"] = snapIb.TrafficReset
  750. updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
  751. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  752. }
  753. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  754. updates["up"] = snapIb.Up
  755. updates["down"] = snapIb.Down
  756. }
  757. // Physical-home attribution is independent of config-dirty state, so
  758. // keep it current even while the node has pending offline edits. Writes
  759. // once to backfill an existing row, then stays equal (#4983).
  760. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  761. updates["origin_node_guid"] = og
  762. }
  763. if !dirty && (c.Remark != snapIb.Remark ||
  764. c.Listen != snapIb.Listen ||
  765. c.Port != snapIb.Port ||
  766. c.Total != snapIb.Total ||
  767. c.ExpiryTime != snapIb.ExpiryTime ||
  768. c.Enable != snapIb.Enable) {
  769. structuralChange = true
  770. }
  771. if len(updates) > 0 {
  772. if err := tx.Model(model.Inbound{}).
  773. Where("id = ?", c.Id).
  774. Updates(updates).Error; err != nil {
  775. return false, err
  776. }
  777. }
  778. }
  779. for _, c := range central {
  780. if dirty {
  781. continue
  782. }
  783. // A node inbound created disabled is never delivered, so its absence from
  784. // the snapshot is ambiguous rather than evidence of a node-side delete.
  785. if !c.Enable {
  786. continue
  787. }
  788. if len(snapTags) == 0 {
  789. // A node mid-restart or with a transient DB error can return an empty
  790. // inbound list with success=true. Treat "zero inbounds reported" as
  791. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  792. // wipes the node's central inbounds and every client on them (and
  793. // resets traffic history on re-create). A real per-inbound deletion
  794. // still sweeps, because the node keeps reporting its other inbounds.
  795. continue
  796. }
  797. if _, kept := snapTags[c.Tag]; kept {
  798. continue
  799. }
  800. if unmanagedTag(c.Tag) {
  801. continue
  802. }
  803. // This drops the central inbound and its clients' traffic history, so say
  804. // so: silent removal is indistinguishable from an inbound never arriving.
  805. logger.Warningf("setRemoteTraffic: node %d no longer reports inbound %q (id %d, port %d) — removing it centrally", nodeID, c.Tag, c.Id, c.Port)
  806. var goneEmails []string
  807. if err := tx.Model(xray.ClientTraffic{}).
  808. Where("inbound_id = ?", c.Id).
  809. Pluck("email", &goneEmails).Error; err != nil {
  810. return false, err
  811. }
  812. if len(goneEmails) > 0 {
  813. // Baselines are per (node, email), not per inbound: keep them for
  814. // emails the snapshot still reports under a sibling inbound (#5202).
  815. baselineGone := make([]string, 0, len(goneEmails))
  816. for _, e := range goneEmails {
  817. if _, still := snapEmailsAll[e]; !still {
  818. baselineGone = append(baselineGone, e)
  819. }
  820. }
  821. // Chunk to avoid SQLite bind var limit when a node has many clients
  822. // removed (e.g. after API bulk delete or structural change on node inbound).
  823. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  824. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  825. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  826. return false, err
  827. }
  828. }
  829. // The per-email row is the shared accumulator across every inbound
  830. // (and node) the email is attached to. Only drop it when this was the
  831. // email's last inbound — wiping it while a sibling still feeds it
  832. // loses the summed history, and the next node sync would re-seed the
  833. // row with that node's counter alone.
  834. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  835. if sErr != nil {
  836. return false, sErr
  837. }
  838. delEmails := make([]string, 0, len(goneEmails))
  839. for _, e := range goneEmails {
  840. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  841. delEmails = append(delEmails, e)
  842. }
  843. }
  844. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  845. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  846. Delete(&xray.ClientTraffic{}).Error; err != nil {
  847. return false, err
  848. }
  849. }
  850. }
  851. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  852. return false, err
  853. }
  854. if err := tx.Where("id = ?", c.Id).
  855. Delete(&model.Inbound{}).Error; err != nil {
  856. return false, err
  857. }
  858. delete(tagToCentral, c.Tag)
  859. structuralChange = true
  860. }
  861. for _, snapIb := range snap.Inbounds {
  862. if snapIb == nil {
  863. continue
  864. }
  865. c, ok := tagToCentral[snapIb.Tag]
  866. if !ok {
  867. continue
  868. }
  869. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  870. // Parsed once per inbound on the first renewal candidate, not per client.
  871. var snapExpiries map[string]int64
  872. for _, cs := range snapIb.ClientStats {
  873. snapEmails[cs.Email] = struct{}{}
  874. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  875. canon := nodeEmailTotals[cs.Email]
  876. base, seen := nodeBaselines[cs.Email]
  877. var deltaUp, deltaDown int64
  878. if seen {
  879. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  880. deltaUp = 0
  881. }
  882. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  883. deltaDown = 0
  884. }
  885. }
  886. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  887. if dirty {
  888. continue
  889. }
  890. _, isNewInbound := newInboundIDs[c.Id]
  891. // On a known inbound a missing row plus a live tombstone means the
  892. // master just deleted this client and the snapshot predates the
  893. // deletion push — recreating the row (at zero) would resurrect the
  894. // client. A freshly adopted inbound still gets its row (seeded at
  895. // zero) so adoption semantics stay intact.
  896. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  897. continue
  898. }
  899. var seedUp, seedDown int64
  900. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  901. seedUp, seedDown = canon.Up, canon.Down
  902. }
  903. row := &xray.ClientTraffic{
  904. InboundId: c.Id,
  905. Email: cs.Email,
  906. Enable: cs.Enable,
  907. Total: cs.Total,
  908. ExpiryTime: cs.ExpiryTime,
  909. Reset: cs.Reset,
  910. ResetDay: cs.ResetDay,
  911. ResetWeekday: cs.ResetWeekday,
  912. ResetMax: cs.ResetMax,
  913. ResetCount: cs.ResetCount,
  914. Up: seedUp,
  915. Down: seedDown,
  916. LastOnline: cs.LastOnline,
  917. }
  918. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  919. Create(row).Error; err != nil {
  920. return false, err
  921. }
  922. centralCS[csKey{c.Id, cs.Email}] = row
  923. centralCSByEmail[cs.Email] = row
  924. existingEmails[cs.Email] = struct{}{}
  925. structuralChange = true
  926. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  927. return false, err
  928. }
  929. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  930. continue
  931. }
  932. existing := centralCSByEmail[cs.Email]
  933. if existing != nil {
  934. expiryChanged := !lifecycleFrozen && existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime)
  935. // Only a real latch to disabled is structural; one-way merge never
  936. // re-enables from the node.
  937. enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
  938. !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
  939. metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset || existing.ResetWeekday != cs.ResetWeekday)
  940. if enableChanged || metaChanged || expiryChanged {
  941. structuralChange = true
  942. }
  943. }
  944. renewed := !lifecycleFrozen && seen && existing != nil && nodeClientRenewed(existing, cs, canon, base)
  945. if renewed {
  946. // Reject when the node's own settings still carry the old absolute:
  947. // lagging ClientStats after a master shorten mimic a renew (#6228).
  948. if snapExpiries == nil {
  949. snapExpiries = settingsClientAbsoluteExpiries(snapIb.Settings)
  950. }
  951. if se, ok := snapExpiries[cs.Email]; ok && se <= existing.ExpiryTime {
  952. renewed = false
  953. }
  954. }
  955. if renewed {
  956. // A renewal starts a fresh quota window: adopt the node's counters
  957. // and enable state, drop stale pushes (mirrors autoRenewClients).
  958. if err := tx.Exec(
  959. fmt.Sprintf(
  960. `UPDATE client_traffics
  961. SET up = ?, down = ?, enable = ?, total = ?,
  962. expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s
  963. WHERE email = ?`,
  964. database.GreatestExpr("last_online", "?"),
  965. ),
  966. canon.Up, canon.Down, cs.Enable, cs.Total,
  967. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount,
  968. cs.LastOnline, cs.Email,
  969. ).Error; err != nil {
  970. return false, err
  971. }
  972. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  973. return false, err
  974. }
  975. existing.Up = canon.Up
  976. existing.Down = canon.Down
  977. existing.Enable = cs.Enable
  978. existing.Total = cs.Total
  979. existing.ExpiryTime = cs.ExpiryTime
  980. existing.Reset = cs.Reset
  981. existing.ResetWeekday = cs.ResetWeekday
  982. existing.ResetCount = cs.ResetCount
  983. structuralChange = true
  984. } else if lifecycleFrozen {
  985. // Push pending or just landed: only counters may move, the master
  986. // keeps expiry/enable/total/reset.
  987. if err := tx.Exec(
  988. fmt.Sprintf(
  989. `UPDATE client_traffics
  990. SET up = %s, down = %s, last_online = %s
  991. WHERE email = ?`,
  992. database.ClampedAddExpr("up"),
  993. database.ClampedAddExpr("down"),
  994. database.GreatestExpr("last_online", "?"),
  995. ),
  996. deltaUp, deltaDown, cs.LastOnline, cs.Email,
  997. ).Error; err != nil {
  998. return false, err
  999. }
  1000. if existing != nil {
  1001. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1002. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1003. }
  1004. } else {
  1005. enableExpr := database.ClientTrafficEnableMergeExpr()
  1006. expiryExpr := database.ClientTrafficExpiryMergeExpr()
  1007. if err := tx.Exec(
  1008. fmt.Sprintf(
  1009. `UPDATE client_traffics
  1010. SET up = %s, down = %s, enable = %s, total = ?,
  1011. expiry_time = %s,
  1012. reset = ?, reset_day = ?, reset_weekday = ?, last_online = %s
  1013. WHERE email = ?`,
  1014. database.ClampedAddExpr("up"),
  1015. database.ClampedAddExpr("down"),
  1016. enableExpr,
  1017. expiryExpr,
  1018. database.GreatestExpr("last_online", "?"),
  1019. ),
  1020. deltaUp, deltaDown,
  1021. cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
  1022. cs.Total,
  1023. cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday,
  1024. cs.LastOnline, cs.Email,
  1025. ).Error; err != nil {
  1026. return false, err
  1027. }
  1028. if existing != nil {
  1029. priorExpiry := existing.ExpiryTime
  1030. if !cs.Enable && !nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown) {
  1031. existing.Enable = false
  1032. }
  1033. existing.ExpiryTime = mergeActivationExpiry(priorExpiry, cs.ExpiryTime)
  1034. existing.Up = clampTrafficCounter(existing.Up + deltaUp)
  1035. existing.Down = clampTrafficCounter(existing.Down + deltaDown)
  1036. existing.Total = cs.Total
  1037. existing.Reset = cs.Reset
  1038. existing.ResetWeekday = cs.ResetWeekday
  1039. }
  1040. }
  1041. // A dip plus a lagging longer expiry mimics nodeClientRenewed and would
  1042. // undo a master shorten once the freeze lifts (#6228).
  1043. if lifecycleFrozen && seen && (canon.Up < base.Up || canon.Down < base.Down) {
  1044. continue
  1045. }
  1046. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  1047. return false, err
  1048. }
  1049. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  1050. }
  1051. for k, existing := range centralCS {
  1052. if dirty {
  1053. continue
  1054. }
  1055. if k.inboundID != c.Id {
  1056. continue
  1057. }
  1058. if _, kept := snapEmails[k.email]; kept {
  1059. continue
  1060. }
  1061. // Gone from this inbound's stats but still reported by the node under
  1062. // a sibling inbound: both the shared accumulator row and the (node,
  1063. // email) baseline must survive, or the sibling's next delta would
  1064. // compute against nothing and freeze the counter (#5202).
  1065. if _, still := snapEmailsAll[k.email]; still {
  1066. continue
  1067. }
  1068. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1069. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1070. return false, err
  1071. }
  1072. // Same shared-accumulator rule as the inbound-removal sweep above:
  1073. // keep the row while another inbound still references the email.
  1074. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  1075. if uErr != nil {
  1076. return false, uErr
  1077. }
  1078. // Usage, quota and expiry live on this row, so a client the orphan
  1079. // sweep will mark keeps it until the reaper confirms the removal.
  1080. if !stillUsed && !clientRecordExists(tx, existing.Email) {
  1081. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1082. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1083. return false, err
  1084. }
  1085. }
  1086. structuralChange = true
  1087. }
  1088. }
  1089. type oldSet struct {
  1090. inboundID int
  1091. emails map[string]struct{}
  1092. }
  1093. var perInboundOld []oldSet
  1094. syncFailedInbounds := map[int]struct{}{}
  1095. for _, p := range pendingAdopts {
  1096. lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, centralCSByEmail)
  1097. adoptedSettings := p.wireSettings
  1098. if liftChanged {
  1099. adoptedSettings = lifted
  1100. lifecycleLifted = true
  1101. }
  1102. if p.central.Settings != adoptedSettings {
  1103. if err := tx.Model(model.Inbound{}).
  1104. Where("id = ?", p.central.Id).
  1105. Update("settings", adoptedSettings).Error; err != nil {
  1106. return false, err
  1107. }
  1108. structuralChange = true
  1109. }
  1110. // The fingerprint stamps the un-lifted wire blob on purpose: a lift must
  1111. // leave reconcile a mismatch to re-push against.
  1112. if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
  1113. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
  1114. }
  1115. }
  1116. for _, snapIb := range snap.Inbounds {
  1117. if snapIb == nil {
  1118. continue
  1119. }
  1120. c, ok := tagToCentral[snapIb.Tag]
  1121. if !ok {
  1122. continue
  1123. }
  1124. if dirty {
  1125. continue
  1126. }
  1127. var oldEmailsRows []string
  1128. if err := tx.Table("clients").
  1129. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1130. Where("client_inbounds.inbound_id = ?", c.Id).
  1131. Pluck("email", &oldEmailsRows).Error; err == nil {
  1132. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1133. for _, e := range oldEmailsRows {
  1134. if e != "" {
  1135. oldEmails[e] = struct{}{}
  1136. }
  1137. }
  1138. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1139. }
  1140. clients, gcErr := s.GetClients(snapIb)
  1141. if gcErr != nil {
  1142. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1143. continue
  1144. }
  1145. csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
  1146. for _, cs := range snapIb.ClientStats {
  1147. csByEmail[cs.Email] = cs
  1148. }
  1149. filtered := clients[:0]
  1150. for i := range clients {
  1151. if isClientEmailTombstoned(clients[i].Email) {
  1152. continue
  1153. }
  1154. existing := centralCSByEmail[clients[i].Email]
  1155. var csPtr *xray.ClientTraffic
  1156. if cs, hit := csByEmail[clients[i].Email]; hit {
  1157. csCopy := cs
  1158. csPtr = &csCopy
  1159. }
  1160. applyMasterClientLifecycle(&clients[i], existing, csPtr)
  1161. filtered = append(filtered, clients[i])
  1162. }
  1163. localEmails := make([]string, 0, len(filtered))
  1164. for i := range filtered {
  1165. if filtered[i].Email != "" {
  1166. localEmails = append(localEmails, filtered[i].Email)
  1167. }
  1168. }
  1169. if len(localEmails) > 0 {
  1170. var localMeta []struct {
  1171. Email string
  1172. Comment string `gorm:"column:comment"`
  1173. }
  1174. if err := tx.Table("clients").
  1175. Select("email, comment").
  1176. Where("email IN ?", localEmails).
  1177. Find(&localMeta).Error; err == nil {
  1178. commentByEmail := make(map[string]string, len(localMeta))
  1179. for _, m := range localMeta {
  1180. commentByEmail[m.Email] = m.Comment
  1181. }
  1182. for i := range filtered {
  1183. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1184. filtered[i].Comment = cmt
  1185. }
  1186. }
  1187. }
  1188. }
  1189. if len(localEmails) > 0 {
  1190. foreign, err := clientEmailsOwnedElsewhere(tx, nodeID, localEmails)
  1191. if err != nil {
  1192. return false, err
  1193. }
  1194. if len(foreign) > 0 {
  1195. kept := filtered[:0]
  1196. for i := range filtered {
  1197. if _, claimed := foreign[filtered[i].Email]; !claimed {
  1198. kept = append(kept, filtered[i])
  1199. continue
  1200. }
  1201. key := fmt.Sprintf("%d:%s", nodeID, filtered[i].Email)
  1202. if _, seen := reportedForeignClientClaim.LoadOrStore(key, struct{}{}); !seen {
  1203. logger.Warningf(
  1204. "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)",
  1205. nodeID, filtered[i].Email,
  1206. )
  1207. }
  1208. }
  1209. filtered = kept
  1210. }
  1211. }
  1212. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1213. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1214. syncFailedInbounds[c.Id] = struct{}{}
  1215. }
  1216. }
  1217. for _, old := range perInboundOld {
  1218. // The sweep's premise is that links were just rebuilt from the snapshot,
  1219. // which is exactly what a failed SyncInbound violates.
  1220. if _, failed := syncFailedInbounds[old.inboundID]; failed {
  1221. continue
  1222. }
  1223. var stillAttached []string
  1224. if err := tx.Table("clients").
  1225. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1226. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1227. Pluck("email", &stillAttached).Error; err != nil {
  1228. continue
  1229. }
  1230. stillSet := make(map[string]struct{}, len(stillAttached))
  1231. for _, e := range stillAttached {
  1232. stillSet[e] = struct{}{}
  1233. }
  1234. for email := range old.emails {
  1235. if _, kept := stillSet[email]; kept {
  1236. continue
  1237. }
  1238. var attachmentCount int64
  1239. if err := tx.Table("client_inbounds").
  1240. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1241. Where("clients.email = ?", email).
  1242. Count(&attachmentCount).Error; err != nil {
  1243. continue
  1244. }
  1245. if attachmentCount > 0 {
  1246. continue
  1247. }
  1248. // "Ended the merge unattached" is true for a real remote deletion and
  1249. // equally true for a bad merge, so record a strike instead of deleting.
  1250. if err := markSyncOrphan(tx, email, now); err != nil {
  1251. logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err)
  1252. continue
  1253. }
  1254. structuralChange = true
  1255. }
  1256. }
  1257. if err := clearSyncOrphanMarks(tx); err != nil {
  1258. logger.Warning("setRemoteTraffic: clear orphan marks failed:", err)
  1259. }
  1260. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  1261. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  1262. }
  1263. if err := tx.Commit().Error; err != nil {
  1264. return false, err
  1265. }
  1266. committed = true
  1267. if lifecycleLifted && !dirty {
  1268. var already model.Node
  1269. if err := database.GetDB().Select("config_dirty").Where("id = ?", nodeID).First(&already).Error; err == nil && already.ConfigDirty {
  1270. logger.Debugf("setRemoteTraffic: node %d lifecycle lift; already dirty", nodeID)
  1271. } else {
  1272. logger.Infof("setRemoteTraffic: node %d lifecycle lift; marking dirty for re-push", nodeID)
  1273. if err := (&NodeService{}).MarkNodeDirty(nodeID); err != nil {
  1274. logger.Warningf("setRemoteTraffic: mark node %d dirty after lifecycle lift failed: %v", nodeID, err)
  1275. }
  1276. }
  1277. }
  1278. if len(adoptedInbounds) > 0 {
  1279. if mgr := runtime.GetManager(); mgr != nil {
  1280. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  1281. if rem, ok := rt.(*runtime.Remote); ok {
  1282. for _, ib := range adoptedInbounds {
  1283. rem.RecordAdoptedInbound(ib)
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. if process := currentXrayProcess(); process != nil {
  1290. tree := snap.OnlineTree
  1291. switch {
  1292. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  1293. // Old-build node (no GUID tree): key its flat online list under its
  1294. // own effective identity so attribution still works for that branch.
  1295. tree = map[string][]string{selfKey: snap.OnlineEmails}
  1296. case guidShared && len(tree) > 0:
  1297. // Newer cloned node: its own clients arrive keyed under the shared
  1298. // panelGuid. Remap just that entry to the node-unique key so the
  1299. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  1300. if _, ok := tree[nodeRow.Guid]; ok {
  1301. tree = remapGuidTreeKey(tree, nodeRow.Guid, selfKey)
  1302. }
  1303. }
  1304. process.SetNodeOnlineTree(nodeID, tree)
  1305. activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral)
  1306. if guidShared && len(activeTree) > 0 {
  1307. if _, ok := activeTree[nodeRow.Guid]; ok {
  1308. activeTree = remapGuidTreeKey(activeTree, nodeRow.Guid, selfKey)
  1309. }
  1310. }
  1311. if len(activeTree) > 0 {
  1312. activeTree = filterGuidTreeKeys(activeTree, activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor))
  1313. }
  1314. process.SetNodeActiveInboundTree(nodeID, activeTree)
  1315. }
  1316. return structuralChange, nil
  1317. }
  1318. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  1319. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  1320. if err != nil {
  1321. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  1322. return
  1323. }
  1324. if !restartOnDisable {
  1325. return
  1326. }
  1327. // Best-effort and never replayed: a hanging node must not hold the traffic poll.
  1328. common.GoRecover("restart-nodes-on-client-disable", func() {
  1329. for _, nodeID := range nodeIDs {
  1330. nodeIDCopy := nodeID
  1331. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  1332. if rtErr != nil {
  1333. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  1334. continue
  1335. }
  1336. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  1337. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  1338. }
  1339. }
  1340. })
  1341. }
  1342. func (s *InboundService) GetOnlineClients() []string {
  1343. process := currentXrayProcess()
  1344. if process == nil {
  1345. return []string{}
  1346. }
  1347. return process.GetOnlineClients()
  1348. }
  1349. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  1350. // node that physically hosts each set: this panel's own clients under its own
  1351. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  1352. // node-id keying so a client three hops down is attributed to its real node,
  1353. // not the intermediate one it was synced through.
  1354. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  1355. process := currentXrayProcess()
  1356. if process == nil {
  1357. return map[string][]string{}
  1358. }
  1359. out := process.GetMergedNodeTrees()
  1360. if local := process.GetLocalOnlineClients(); len(local) > 0 {
  1361. if guid := s.panelGuid(); guid != "" {
  1362. out[guid] = mergeEmails(out[guid], local)
  1363. }
  1364. }
  1365. return out
  1366. }
  1367. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  1368. // the grace window, keyed by the panelGuid of the node that physically hosts
  1369. // each inbound. A GUID missing from the map means "don't gate" for that node's
  1370. // inbounds (old-build node or no active-inbound signal).
  1371. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  1372. process := currentXrayProcess()
  1373. if process == nil {
  1374. return map[string][]string{}
  1375. }
  1376. out := process.GetMergedActiveInboundTrees()
  1377. active := process.GetLocalActiveInbounds()
  1378. if len(active) == 0 {
  1379. return out
  1380. }
  1381. guid := s.panelGuid()
  1382. if guid == "" {
  1383. return out
  1384. }
  1385. out[guid] = mergeEmails(out[guid], active)
  1386. return out
  1387. }
  1388. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1389. if process := currentXrayProcess(); process != nil {
  1390. process.SetNodeOnlineTree(nodeID, tree)
  1391. }
  1392. }
  1393. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1394. if process := currentXrayProcess(); process != nil {
  1395. process.ClearNodeOnlineClients(nodeID)
  1396. }
  1397. }
  1398. // RetainSyncedNodeOnlineClients keeps online clients only for nodes the traffic
  1399. // sync still fetches; a node missing from nodes was deleted.
  1400. func (s *InboundService) RetainSyncedNodeOnlineClients(nodes []*model.Node) {
  1401. process := currentXrayProcess()
  1402. if process == nil {
  1403. return
  1404. }
  1405. synced := make(map[int]bool, len(nodes))
  1406. for _, n := range nodes {
  1407. synced[n.Id] = n.Enable && n.Status == "online"
  1408. }
  1409. process.RetainNodeOnlineClients(func(nodeID int) bool { return synced[nodeID] })
  1410. }
  1411. // panelGuid returns this panel's stable self-identifier, used to key the local
  1412. // panel's own clients in the per-node online maps (#4983).
  1413. func (s *InboundService) panelGuid() string {
  1414. guid, _ := (&SettingService{}).GetPanelGuid()
  1415. return guid
  1416. }
  1417. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1418. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1419. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1420. // flat-topology case where an old-build node appears.
  1421. func synthNodeGuid(nodeID int) string {
  1422. return fmt.Sprintf("node:%d", nodeID)
  1423. }
  1424. // mergeEmails returns the deduped union of two email slices.
  1425. func mergeEmails(a, b []string) []string {
  1426. if len(a) == 0 {
  1427. return b
  1428. }
  1429. seen := make(map[string]struct{}, len(a)+len(b))
  1430. out := make([]string, 0, len(a)+len(b))
  1431. for _, e := range a {
  1432. if _, ok := seen[e]; !ok {
  1433. seen[e] = struct{}{}
  1434. out = append(out, e)
  1435. }
  1436. }
  1437. for _, e := range b {
  1438. if _, ok := seen[e]; !ok {
  1439. seen[e] = struct{}{}
  1440. out = append(out, e)
  1441. }
  1442. }
  1443. return out
  1444. }
  1445. func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]string {
  1446. if from == "" || to == "" || from == to {
  1447. return tree
  1448. }
  1449. remapped := make(map[string][]string, len(tree))
  1450. for guid, values := range tree {
  1451. if guid == from {
  1452. guid = to
  1453. }
  1454. remapped[guid] = mergeEmails(remapped[guid], values)
  1455. }
  1456. return remapped
  1457. }
  1458. func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[string]*model.Inbound) map[string][]string {
  1459. if len(tree) == 0 {
  1460. return nil
  1461. }
  1462. out := make(map[string][]string, len(tree))
  1463. for guid, tags := range tree {
  1464. if guid == "" || len(tags) == 0 {
  1465. continue
  1466. }
  1467. seen := make(map[string]struct{}, len(tags))
  1468. for _, tag := range tags {
  1469. if tag == "" {
  1470. continue
  1471. }
  1472. if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
  1473. tag = central.Tag
  1474. }
  1475. if _, dup := seen[tag]; dup {
  1476. continue
  1477. }
  1478. seen[tag] = struct{}{}
  1479. out[guid] = append(out[guid], tag)
  1480. }
  1481. }
  1482. if len(out) == 0 {
  1483. return nil
  1484. }
  1485. return out
  1486. }
  1487. func activeInboundGuidKeys(inbounds []*model.Inbound, tagToCentral map[string]*model.Inbound, originGuidFor func(*model.Inbound) string) map[string]struct{} {
  1488. allowed := make(map[string]struct{})
  1489. for _, ib := range inbounds {
  1490. if ib == nil {
  1491. continue
  1492. }
  1493. if _, ok := tagToCentral[ib.Tag]; !ok {
  1494. continue
  1495. }
  1496. if guid := originGuidFor(ib); guid != "" {
  1497. allowed[guid] = struct{}{}
  1498. }
  1499. }
  1500. return allowed
  1501. }
  1502. func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) map[string][]string {
  1503. if len(tree) == 0 || len(allowed) == 0 {
  1504. return nil
  1505. }
  1506. out := make(map[string][]string, len(tree))
  1507. for guid, values := range tree {
  1508. if _, ok := allowed[guid]; !ok {
  1509. continue
  1510. }
  1511. if len(values) > 0 {
  1512. out[guid] = values
  1513. }
  1514. }
  1515. if len(out) == 0 {
  1516. return nil
  1517. }
  1518. return out
  1519. }
  1520. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1521. db := database.GetDB()
  1522. var rows []xray.ClientTraffic
  1523. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1524. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1525. return nil, err
  1526. }
  1527. result := make(map[string]int64, len(rows))
  1528. for _, r := range rows {
  1529. result[r.Email] = r.LastOnline
  1530. }
  1531. return result, nil
  1532. }
  1533. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1534. // panel's own xray this poll into the local online/active sets, applying the
  1535. // grace window and pruning stale entries. Pass nil to only prune. See
  1536. // xray.Process for why the local sets are kept separate from the shared
  1537. // last_online column.
  1538. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1539. if process := currentXrayProcess(); process != nil {
  1540. process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1541. }
  1542. }
  1543. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1544. db := database.GetDB()
  1545. // Step 1: Get ClientTraffic records for emails in the input list.
  1546. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1547. uniqEmails := uniqueNonEmptyStrings(emails)
  1548. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1549. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1550. var page []xray.ClientTraffic
  1551. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1552. return nil, nil, err
  1553. }
  1554. clients = append(clients, page...)
  1555. }
  1556. // Step 2: Sort clients by (Up + Down) descending
  1557. sort.Slice(clients, func(i, j int) bool {
  1558. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1559. })
  1560. // Step 3: Extract sorted valid emails and track found ones
  1561. validEmails := make([]string, 0, len(clients))
  1562. found := make(map[string]bool)
  1563. for _, client := range clients {
  1564. validEmails = append(validEmails, client.Email)
  1565. found[client.Email] = true
  1566. }
  1567. // Step 4: Identify emails that were not found in the database
  1568. extraEmails := make([]string, 0)
  1569. for _, email := range emails {
  1570. if !found[email] {
  1571. extraEmails = append(extraEmails, email)
  1572. }
  1573. }
  1574. return validEmails, extraEmails, nil
  1575. }