inbound_node.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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/web/runtime"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "gorm.io/gorm"
  16. "gorm.io/gorm/clause"
  17. )
  18. var reportedRemoteTagConflict sync.Map
  19. // nodeBulkPushThreshold caps how many per-client RPCs a single operation will
  20. // stream to a remote node. Above it, the panel marks the node dirty instead and
  21. // lets one ReconcileNode push converge the whole inbound — far cheaper than M
  22. // sequential round-trips. Small ops stay on the live per-client path.
  23. const nodeBulkPushThreshold = 32
  24. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  25. mgr := runtime.GetManager()
  26. if mgr == nil {
  27. return nil, fmt.Errorf("runtime manager not initialised")
  28. }
  29. return mgr.RuntimeFor(ib.NodeID)
  30. }
  31. func (s *InboundService) nodePushPlan(ib *model.Inbound) (runtime.Runtime, bool, bool, error) {
  32. if ib.NodeID == nil {
  33. rt, err := s.runtimeFor(ib)
  34. if err != nil {
  35. return nil, false, false, nil
  36. }
  37. return rt, true, false, nil
  38. }
  39. nodeSvc := NodeService{}
  40. enabled, status, _, _, err := nodeSvc.NodeSyncState(*ib.NodeID)
  41. if err != nil {
  42. return nil, false, false, err
  43. }
  44. if !enabled || status == "offline" {
  45. return nil, false, true, nil
  46. }
  47. rt, err := s.runtimeFor(ib)
  48. if err != nil {
  49. return nil, false, true, nil
  50. }
  51. return rt, true, false, nil
  52. }
  53. func (s *InboundService) NodeIsPending(nodeID *int) bool {
  54. if nodeID == nil {
  55. return false
  56. }
  57. return (&NodeService{}).IsNodePending(*nodeID)
  58. }
  59. func (s *InboundService) AnyNodePending(inboundIds []int) bool {
  60. if len(inboundIds) == 0 {
  61. return false
  62. }
  63. nodeSvc := NodeService{}
  64. for _, id := range inboundIds {
  65. ib, err := s.GetInbound(id)
  66. if err != nil || ib.NodeID == nil {
  67. continue
  68. }
  69. if nodeSvc.IsNodePending(*ib.NodeID) {
  70. return true
  71. }
  72. }
  73. return false
  74. }
  75. // ReconcileNode pushes every inbound and sweeps undesired remote tags even when
  76. // individual operations fail, returning the failures joined: one inbound the
  77. // node rejects (e.g. a legacy protocol failing validation, #5685) must not
  78. // stall the rest of the node's config — or, via syncOne, its traffic sync.
  79. func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, n *model.Node) error {
  80. if rt == nil || n == nil || n.Id <= 0 {
  81. return nil
  82. }
  83. nodeID := n.Id
  84. db := database.GetDB()
  85. var inbounds []*model.Inbound
  86. if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil {
  87. return err
  88. }
  89. remoteTags, err := rt.ListRemoteTags(ctx)
  90. if err != nil {
  91. return err
  92. }
  93. remoteTagSet := make(map[string]struct{}, len(remoteTags))
  94. for _, tag := range remoteTags {
  95. remoteTagSet[tag] = struct{}{}
  96. }
  97. prefix := nodeTagPrefix(&nodeID)
  98. desiredTags := make(map[string]struct{}, len(inbounds)*2)
  99. var errs []error
  100. for _, ib := range inbounds {
  101. desiredTags[ib.Tag] = struct{}{}
  102. // existsOnNode: does the node already report this inbound under any of the
  103. // tag forms it may be stored as? If so, an unchanged push can be skipped.
  104. _, existsOnNode := remoteTagSet[ib.Tag]
  105. if prefix != "" {
  106. if stripped, found := strings.CutPrefix(ib.Tag, prefix); found {
  107. desiredTags[stripped] = struct{}{}
  108. if _, ok := remoteTagSet[stripped]; ok {
  109. existsOnNode = true
  110. }
  111. } else {
  112. desiredTags[prefix+ib.Tag] = struct{}{}
  113. if _, ok := remoteTagSet[prefix+ib.Tag]; ok {
  114. existsOnNode = true
  115. }
  116. }
  117. }
  118. if _, err := rt.ReconcileInbound(ctx, ib, existsOnNode); err != nil {
  119. errs = append(errs, fmt.Errorf("reconcile inbound %q: %w", ib.Tag, err))
  120. }
  121. }
  122. // Before the first clean sync adopts the node's inbounds, "absent locally"
  123. // means "not imported yet" — sweeping now would wipe the node at onboarding.
  124. if n.InboundsAdoptedAt == 0 {
  125. return errors.Join(errs...)
  126. }
  127. // In "selected" sync mode the panel only manages the selected tags: the
  128. // rest were never imported, so their absence from the local DB must not
  129. // delete them from the node. Only a selected tag missing locally (the
  130. // panel deleted it while the node was unreachable) may be swept.
  131. var selected map[string]struct{}
  132. if n.InboundSyncMode == "selected" {
  133. selected = make(map[string]struct{}, len(n.InboundTags))
  134. for _, tag := range n.InboundTags {
  135. selected[tag] = struct{}{}
  136. }
  137. }
  138. for _, tag := range remoteTags {
  139. if _, want := desiredTags[tag]; want {
  140. continue
  141. }
  142. if selected != nil {
  143. if _, managed := selected[tag]; !managed {
  144. continue
  145. }
  146. }
  147. if err := rt.DelInbound(ctx, &model.Inbound{Tag: tag}); err != nil {
  148. errs = append(errs, fmt.Errorf("reconcile delete %q: %w", tag, err))
  149. }
  150. }
  151. return errors.Join(errs...)
  152. }
  153. const resetGracePeriodMs int64 = 30000
  154. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  155. // Xray's stats counters often report a zero delta for an active session across
  156. // a single poll, so a 5s grace would still drop the client on the next tick.
  157. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  158. // long after a real disconnect.
  159. const onlineGracePeriodMs int64 = 20000
  160. type nodeTrafficCounter struct {
  161. Up int64
  162. Down int64
  163. }
  164. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  165. return tx.Clauses(clause.OnConflict{
  166. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  167. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  168. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  169. }
  170. // mergeActivationExpiry reconciles a node-reported client expiry with the value
  171. // already stored on the master. "Start after first connect" persists a negative
  172. // duration that each node converts to an absolute deadline (now+duration) the
  173. // first time the client connects there. The per-email client_traffics row is
  174. // shared across every node, so a node that has not yet seen a first connection
  175. // keeps reporting the negative duration — which must never reset a deadline
  176. // another node already activated.
  177. //
  178. // A node may legitimately move an already-activated deadline forward (traffic
  179. // reset / auto-renew extends it), so any positive node value is still adopted —
  180. // only an un-activated (<= 0) value is rejected once an absolute deadline
  181. // exists. Kept in lockstep with the SQL CASE in setRemoteTrafficLocked.
  182. func mergeActivationExpiry(existing, node int64) int64 {
  183. if existing > 0 && node <= 0 {
  184. return existing
  185. }
  186. return node
  187. }
  188. // nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
  189. // forward while the node's cumulative counter fell below the stored baseline.
  190. func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
  191. if cs.Reset <= 0 || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
  192. return false
  193. }
  194. if cs.ExpiryTime <= existing.ExpiryTime {
  195. return false
  196. }
  197. return canon.Up < base.Up || canon.Down < base.Down
  198. }
  199. // liftActivatedClientRecordExpiries copies a node-activated deadline from
  200. // client_traffics onto client records still holding the negative duration (#5714).
  201. func liftActivatedClientRecordExpiries(tx *gorm.DB) error {
  202. return tx.Exec(
  203. `UPDATE clients
  204. SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1)
  205. WHERE clients.expiry_time < 0
  206. AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`,
  207. ).Error
  208. }
  209. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  210. var structuralChange bool
  211. err := submitTrafficWrite(func() error {
  212. var inner error
  213. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  214. return inner
  215. })
  216. return structuralChange, err
  217. }
  218. // GetNodeInboundTrafficTotals returns the current cumulative up/down for every
  219. // node-hosted inbound, keyed by tag. The node sync diffs successive snapshots of
  220. // this to derive per-inbound speed for the dashboard — node inbounds have no
  221. // local Xray poll to produce live deltas the way local inbounds do.
  222. func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, error) {
  223. var rows []struct {
  224. Tag string
  225. Up int64
  226. Down int64
  227. }
  228. if err := database.GetDB().Table("inbounds").
  229. Select("tag, up, down").
  230. Where("node_id IS NOT NULL").
  231. Scan(&rows).Error; err != nil {
  232. return nil, err
  233. }
  234. out := make(map[string][2]int64, len(rows))
  235. for _, r := range rows {
  236. out[r.Tag] = [2]int64{r.Up, r.Down}
  237. }
  238. return out, nil
  239. }
  240. func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
  241. return c.Settings != adoptedSettings ||
  242. c.Enable != snapIb.Enable ||
  243. c.Remark != snapIb.Remark ||
  244. c.SubSortIndex != normalizeSubSortIndex(snapIb.SubSortIndex) ||
  245. c.Listen != snapIb.Listen ||
  246. c.Port != snapIb.Port ||
  247. c.Protocol != snapIb.Protocol ||
  248. c.Total != snapIb.Total ||
  249. c.ExpiryTime != snapIb.ExpiryTime ||
  250. c.StreamSettings != snapIb.StreamSettings ||
  251. c.Sniffing != snapIb.Sniffing ||
  252. c.TrafficReset != snapIb.TrafficReset
  253. }
  254. // adoptedWireInbound is the central inbound as it reads after adopting the
  255. // node-reported wire fields — the payload the reconcile fingerprint must track.
  256. func adoptedWireInbound(c, snapIb *model.Inbound, adoptedSettings string) *model.Inbound {
  257. a := *c
  258. a.Enable = snapIb.Enable
  259. a.Remark = snapIb.Remark
  260. a.SubSortIndex = normalizeSubSortIndex(snapIb.SubSortIndex)
  261. a.Listen = snapIb.Listen
  262. a.Port = snapIb.Port
  263. a.Protocol = snapIb.Protocol
  264. a.Total = snapIb.Total
  265. a.ExpiryTime = snapIb.ExpiryTime
  266. a.Settings = adoptedSettings
  267. a.StreamSettings = snapIb.StreamSettings
  268. a.Sniffing = snapIb.Sniffing
  269. a.TrafficReset = snapIb.TrafficReset
  270. return &a
  271. }
  272. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  273. if snap == nil || nodeID <= 0 {
  274. return false, nil
  275. }
  276. db := database.GetDB()
  277. now := time.Now().UnixMilli()
  278. // originGuidFor attributes a synced inbound to the panel that physically
  279. // hosts it. A node's OWN inbounds report either an empty origin or — on
  280. // builds that set it locally — the node's own panelGuid; both resolve to
  281. // selfKey, which is the node's panelGuid unless that GUID is ambiguous
  282. // (shared with another node or the master, i.e. a cloned server), in which
  283. // case it falls back to the node-unique id so #4983 attribution doesn't
  284. // collapse two physical nodes into one bucket. Only a DIFFERENT, non-empty
  285. // origin (an inbound the node forwards from its own sub-node) is kept as-is,
  286. // so a chained Node1->Node2->Node3 still attributes Node3's inbounds to Node3.
  287. var nodeRow model.Node
  288. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  289. selfKey := effectiveNodeKey(&model.Node{Id: nodeID, Guid: nodeRow.Guid})
  290. guidShared := nodeRow.Guid != "" && selfKey != nodeRow.Guid
  291. originGuidFor := func(snapIb *model.Inbound) string {
  292. if snapIb.OriginNodeGuid != "" && snapIb.OriginNodeGuid != nodeRow.Guid {
  293. return snapIb.OriginNodeGuid
  294. }
  295. return selfKey
  296. }
  297. var central []model.Inbound
  298. if err := db.Model(model.Inbound{}).
  299. Where("node_id = ?", nodeID).
  300. Find(&central).Error; err != nil {
  301. return false, err
  302. }
  303. // Index under the stored tag and its prefix-flipped form so a snap matches
  304. // whether the n<id>- prefix lives on the node side, the central side, or
  305. // neither — a mismatch must never spawn a duplicate central inbound.
  306. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  307. prefix := nodeTagPrefix(&nodeID)
  308. for i := range central {
  309. tagToCentral[central[i].Tag] = &central[i]
  310. if prefix != "" {
  311. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  312. tagToCentral[stripped] = &central[i]
  313. } else {
  314. tagToCentral[prefix+central[i].Tag] = &central[i]
  315. }
  316. }
  317. }
  318. var centralClientStats []xray.ClientTraffic
  319. if len(central) > 0 {
  320. ids := make([]int, 0, len(central))
  321. for i := range central {
  322. ids = append(ids, central[i].Id)
  323. }
  324. if err := db.Model(xray.ClientTraffic{}).
  325. Where("inbound_id IN ?", ids).
  326. Find(&centralClientStats).Error; err != nil {
  327. return false, err
  328. }
  329. }
  330. type csKey struct {
  331. inboundID int
  332. email string
  333. }
  334. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  335. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  336. for i := range centralClientStats {
  337. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  338. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  339. }
  340. nodeBaselines := make(map[string]nodeTrafficCounter)
  341. var baselineRows []model.NodeClientTraffic
  342. if err := db.Model(&model.NodeClientTraffic{}).
  343. Where("node_id = ?", nodeID).
  344. Find(&baselineRows).Error; err != nil {
  345. return false, err
  346. }
  347. for i := range baselineRows {
  348. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  349. }
  350. var defaultUserId int
  351. if len(central) > 0 {
  352. defaultUserId = central[0].UserId
  353. } else {
  354. var u model.User
  355. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  356. defaultUserId = u.Id
  357. } else {
  358. defaultUserId = 1
  359. }
  360. }
  361. // Union of every email the snapshot still reports, across all inbounds.
  362. // The (node, email) baseline rows are keyed per node, not per inbound, so
  363. // the sweeps below must only drop one when the email left the node
  364. // entirely — an email whose stats moved to (or always lived under) a
  365. // sibling inbound still needs its baseline for the sibling's delta
  366. // computation (#5202).
  367. //
  368. // Xray counts traffic per email, not per inbound, so a multi-attached
  369. // client's shared counter is copied onto every inbound it's on. Fold each
  370. // email to its per-field max (nodeEmailTotals) so divergent copies can't make
  371. // the reset clamp re-add a lower sibling as fresh traffic (#5274).
  372. snapEmailsAll := make(map[string]struct{})
  373. nodeEmailTotals := make(map[string]nodeTrafficCounter)
  374. for _, snapIb := range snap.Inbounds {
  375. if snapIb == nil {
  376. continue
  377. }
  378. for i := range snapIb.ClientStats {
  379. email := snapIb.ClientStats[i].Email
  380. snapEmailsAll[email] = struct{}{}
  381. cur := nodeEmailTotals[email]
  382. if snapIb.ClientStats[i].Up > cur.Up {
  383. cur.Up = snapIb.ClientStats[i].Up
  384. }
  385. if snapIb.ClientStats[i].Down > cur.Down {
  386. cur.Down = snapIb.ClientStats[i].Down
  387. }
  388. nodeEmailTotals[email] = cur
  389. }
  390. }
  391. // Membership set for the rowExists checks below. Only the snapshot's emails
  392. // are ever probed, so scope the lookup to those instead of plucking the whole
  393. // client_traffics table (50k+ rows) on every node poll.
  394. existingEmails := make(map[string]struct{}, len(snapEmailsAll))
  395. if len(snapEmailsAll) > 0 {
  396. snapEmailList := make([]string, 0, len(snapEmailsAll))
  397. for email := range snapEmailsAll {
  398. snapEmailList = append(snapEmailList, email)
  399. }
  400. for _, batch := range chunkStrings(snapEmailList, sqliteMaxVars) {
  401. var found []string
  402. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Pluck("email", &found).Error; err != nil {
  403. return false, err
  404. }
  405. for _, e := range found {
  406. existingEmails[e] = struct{}{}
  407. }
  408. }
  409. }
  410. tx := db.Begin()
  411. committed := false
  412. defer func() {
  413. if !committed {
  414. tx.Rollback()
  415. }
  416. }()
  417. structuralChange := false
  418. var adoptedInbounds []*model.Inbound
  419. newInboundIDs := make(map[int]struct{})
  420. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  421. for _, snapIb := range snap.Inbounds {
  422. if snapIb == nil {
  423. continue
  424. }
  425. snapTags[snapIb.Tag] = struct{}{}
  426. // Record the prefix-flipped form too so the orphan sweep below keeps a
  427. // central inbound whether its tag carries the n<id>- prefix or not.
  428. if prefix != "" {
  429. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  430. snapTags[stripped] = struct{}{}
  431. } else {
  432. snapTags[prefix+snapIb.Tag] = struct{}{}
  433. }
  434. }
  435. c, ok := tagToCentral[snapIb.Tag]
  436. if !ok {
  437. if dirty {
  438. continue
  439. }
  440. // Try snap.Tag first; on collision fall back to the n<id>-
  441. // prefixed form so local+node can both own the same port.
  442. pickFreeTag := func() (string, error) {
  443. candidates := []string{snapIb.Tag}
  444. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  445. candidates = append(candidates, prefix+snapIb.Tag)
  446. }
  447. for _, t := range candidates {
  448. var owner model.Inbound
  449. err := tx.Where("tag = ?", t).First(&owner).Error
  450. if errors.Is(err, gorm.ErrRecordNotFound) {
  451. return t, nil
  452. }
  453. if err != nil {
  454. return "", err
  455. }
  456. }
  457. return "", nil
  458. }
  459. chosenTag, err := pickFreeTag()
  460. if err != nil {
  461. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  462. continue
  463. }
  464. if chosenTag == "" {
  465. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  466. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  467. logger.Warningf(
  468. "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)",
  469. snapIb.Tag, nodeID, nodeID,
  470. )
  471. }
  472. continue
  473. }
  474. reportedRemoteTagConflict.Delete(fmt.Sprintf("%d:%s", nodeID, snapIb.Tag))
  475. newIb := model.Inbound{
  476. UserId: defaultUserId,
  477. NodeID: &nodeID,
  478. OriginNodeGuid: originGuidFor(snapIb),
  479. Tag: chosenTag,
  480. Listen: snapIb.Listen,
  481. Port: snapIb.Port,
  482. Protocol: snapIb.Protocol,
  483. Settings: snapIb.Settings,
  484. StreamSettings: snapIb.StreamSettings,
  485. Sniffing: snapIb.Sniffing,
  486. TrafficReset: snapIb.TrafficReset,
  487. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  488. Enable: snapIb.Enable,
  489. Remark: snapIb.Remark,
  490. SubSortIndex: normalizeSubSortIndex(snapIb.SubSortIndex),
  491. Total: snapIb.Total,
  492. ExpiryTime: snapIb.ExpiryTime,
  493. Up: snapIb.Up,
  494. Down: snapIb.Down,
  495. ShareAddrStrategy: "node",
  496. }
  497. if err := tx.Create(&newIb).Error; err != nil {
  498. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  499. continue
  500. }
  501. tagToCentral[snapIb.Tag] = &newIb
  502. if newIb.Tag != snapIb.Tag {
  503. tagToCentral[newIb.Tag] = &newIb
  504. }
  505. newInboundIDs[newIb.Id] = struct{}{}
  506. structuralChange = true
  507. continue
  508. }
  509. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  510. // Adopting the node's settings verbatim would re-add a client the master
  511. // deleted moments ago if this snapshot was fetched before the deletion
  512. // push landed — filter just-deleted emails out while their tombstone lives.
  513. adoptedSettings := snapIb.Settings
  514. if stripped, changed := stripTombstonedClients(adoptedSettings); changed {
  515. adoptedSettings = stripped
  516. }
  517. if deduped, changed := dedupeSettingsClients(adoptedSettings); changed {
  518. adoptedSettings = deduped
  519. }
  520. updates := map[string]any{}
  521. if !dirty {
  522. updates["enable"] = snapIb.Enable
  523. updates["remark"] = snapIb.Remark
  524. updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
  525. updates["listen"] = snapIb.Listen
  526. updates["port"] = snapIb.Port
  527. updates["protocol"] = snapIb.Protocol
  528. updates["total"] = snapIb.Total
  529. updates["expiry_time"] = snapIb.ExpiryTime
  530. updates["settings"] = adoptedSettings
  531. updates["stream_settings"] = snapIb.StreamSettings
  532. updates["sniffing"] = snapIb.Sniffing
  533. updates["traffic_reset"] = snapIb.TrafficReset
  534. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  535. if adoptedWireChanged(c, snapIb, adoptedSettings) {
  536. adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, adoptedSettings))
  537. }
  538. }
  539. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  540. updates["up"] = snapIb.Up
  541. updates["down"] = snapIb.Down
  542. }
  543. // Physical-home attribution is independent of config-dirty state, so
  544. // keep it current even while the node has pending offline edits. Writes
  545. // once to backfill an existing row, then stays equal (#4983).
  546. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  547. updates["origin_node_guid"] = og
  548. }
  549. if !dirty && (c.Settings != adoptedSettings ||
  550. c.Remark != snapIb.Remark ||
  551. c.Listen != snapIb.Listen ||
  552. c.Port != snapIb.Port ||
  553. c.Total != snapIb.Total ||
  554. c.ExpiryTime != snapIb.ExpiryTime ||
  555. c.Enable != snapIb.Enable) {
  556. structuralChange = true
  557. }
  558. if len(updates) > 0 {
  559. if err := tx.Model(model.Inbound{}).
  560. Where("id = ?", c.Id).
  561. Updates(updates).Error; err != nil {
  562. return false, err
  563. }
  564. }
  565. }
  566. for _, c := range central {
  567. if dirty {
  568. continue
  569. }
  570. if len(snapTags) == 0 {
  571. // A node mid-restart or with a transient DB error can return an empty
  572. // inbound list with success=true. Treat "zero inbounds reported" as
  573. // "nothing to say", not "delete all my inbounds" — otherwise a blip
  574. // wipes the node's central inbounds and every client on them (and
  575. // resets traffic history on re-create). A real per-inbound deletion
  576. // still sweeps, because the node keeps reporting its other inbounds.
  577. continue
  578. }
  579. if _, kept := snapTags[c.Tag]; kept {
  580. continue
  581. }
  582. var goneEmails []string
  583. if err := tx.Model(xray.ClientTraffic{}).
  584. Where("inbound_id = ?", c.Id).
  585. Pluck("email", &goneEmails).Error; err != nil {
  586. return false, err
  587. }
  588. if len(goneEmails) > 0 {
  589. // Baselines are per (node, email), not per inbound: keep them for
  590. // emails the snapshot still reports under a sibling inbound (#5202).
  591. baselineGone := make([]string, 0, len(goneEmails))
  592. for _, e := range goneEmails {
  593. if _, still := snapEmailsAll[e]; !still {
  594. baselineGone = append(baselineGone, e)
  595. }
  596. }
  597. // Chunk to avoid SQLite bind var limit when a node has many clients
  598. // removed (e.g. after API bulk delete or structural change on node inbound).
  599. for _, batch := range chunkStrings(baselineGone, sqliteMaxVars) {
  600. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  601. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  602. return false, err
  603. }
  604. }
  605. // The per-email row is the shared accumulator across every inbound
  606. // (and node) the email is attached to. Only drop it when this was the
  607. // email's last inbound — wiping it while a sibling still feeds it
  608. // loses the summed history, and the next node sync would re-seed the
  609. // row with that node's counter alone.
  610. sharedEmails, sErr := s.emailsUsedByOtherInbounds(goneEmails, c.Id)
  611. if sErr != nil {
  612. return false, sErr
  613. }
  614. delEmails := make([]string, 0, len(goneEmails))
  615. for _, e := range goneEmails {
  616. if !sharedEmails[strings.ToLower(strings.TrimSpace(e))] {
  617. delEmails = append(delEmails, e)
  618. }
  619. }
  620. for _, batch := range chunkStrings(delEmails, sqliteMaxVars) {
  621. if err := tx.Where("inbound_id = ? AND email IN ?", c.Id, batch).
  622. Delete(&xray.ClientTraffic{}).Error; err != nil {
  623. return false, err
  624. }
  625. }
  626. }
  627. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  628. return false, err
  629. }
  630. if err := tx.Where("id = ?", c.Id).
  631. Delete(&model.Inbound{}).Error; err != nil {
  632. return false, err
  633. }
  634. delete(tagToCentral, c.Tag)
  635. structuralChange = true
  636. }
  637. for _, snapIb := range snap.Inbounds {
  638. if snapIb == nil {
  639. continue
  640. }
  641. c, ok := tagToCentral[snapIb.Tag]
  642. if !ok {
  643. continue
  644. }
  645. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  646. for _, cs := range snapIb.ClientStats {
  647. snapEmails[cs.Email] = struct{}{}
  648. // Node-wide total, not this inbound's possibly-stale copy (#5274).
  649. canon := nodeEmailTotals[cs.Email]
  650. base, seen := nodeBaselines[cs.Email]
  651. var deltaUp, deltaDown int64
  652. if seen {
  653. if deltaUp = canon.Up - base.Up; deltaUp < 0 {
  654. deltaUp = 0
  655. }
  656. if deltaDown = canon.Down - base.Down; deltaDown < 0 {
  657. deltaDown = 0
  658. }
  659. }
  660. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  661. if dirty {
  662. continue
  663. }
  664. _, isNewInbound := newInboundIDs[c.Id]
  665. // On a known inbound a missing row plus a live tombstone means the
  666. // master just deleted this client and the snapshot predates the
  667. // deletion push — recreating the row (at zero) would resurrect the
  668. // client. A freshly adopted inbound still gets its row (seeded at
  669. // zero) so adoption semantics stay intact.
  670. if !isNewInbound && isClientEmailTombstoned(cs.Email) {
  671. continue
  672. }
  673. var seedUp, seedDown int64
  674. if isNewInbound && !isClientEmailTombstoned(cs.Email) {
  675. seedUp, seedDown = canon.Up, canon.Down
  676. }
  677. row := &xray.ClientTraffic{
  678. InboundId: c.Id,
  679. Email: cs.Email,
  680. Enable: cs.Enable,
  681. Total: cs.Total,
  682. ExpiryTime: cs.ExpiryTime,
  683. Reset: cs.Reset,
  684. Up: seedUp,
  685. Down: seedDown,
  686. LastOnline: cs.LastOnline,
  687. }
  688. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  689. Create(row).Error; err != nil {
  690. return false, err
  691. }
  692. centralCS[csKey{c.Id, cs.Email}] = row
  693. centralCSByEmail[cs.Email] = row
  694. existingEmails[cs.Email] = struct{}{}
  695. structuralChange = true
  696. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  697. return false, err
  698. }
  699. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  700. continue
  701. }
  702. existing := centralCSByEmail[cs.Email]
  703. if existing != nil &&
  704. (existing.Enable != cs.Enable ||
  705. existing.Total != cs.Total ||
  706. existing.ExpiryTime != mergeActivationExpiry(existing.ExpiryTime, cs.ExpiryTime) ||
  707. existing.Reset != cs.Reset) {
  708. structuralChange = true
  709. }
  710. if seen && existing != nil && nodeClientRenewed(existing, cs, canon, base) {
  711. // A renewal starts a fresh quota window: adopt the node's counters
  712. // and enable state, drop stale pushes (mirrors autoRenewClients).
  713. if err := tx.Exec(
  714. fmt.Sprintf(
  715. `UPDATE client_traffics
  716. SET up = ?, down = ?, enable = ?, total = ?,
  717. expiry_time = ?, reset = ?, last_online = %s
  718. WHERE email = ?`,
  719. database.GreatestExpr("last_online", "?"),
  720. ),
  721. canon.Up, canon.Down, cs.Enable, cs.Total,
  722. cs.ExpiryTime, cs.Reset,
  723. cs.LastOnline, cs.Email,
  724. ).Error; err != nil {
  725. return false, err
  726. }
  727. if err := clearGlobalTraffic(tx, cs.Email); err != nil {
  728. return false, err
  729. }
  730. } else {
  731. enableExpr := database.ClientTrafficEnableMergeExpr()
  732. // expiry_time merge mirrors mergeActivationExpiry: a node that has not
  733. // yet seen the client's first connection keeps reporting the negative
  734. // "start after first connect" duration, which must never reset the
  735. // absolute deadline another node already activated. A positive node
  736. // value is still adopted (e.g. auto-renew moves the deadline forward).
  737. // CAST(? AS BIGINT): in the `<= 0` comparison Postgres would otherwise
  738. // infer int4 from the literal and overflow on real expiry values.
  739. if err := tx.Exec(
  740. fmt.Sprintf(
  741. `UPDATE client_traffics
  742. SET up = %s, down = %s, enable = %s, total = ?,
  743. expiry_time = CASE WHEN expiry_time > 0 AND CAST(? AS BIGINT) <= 0 THEN expiry_time ELSE CAST(? AS BIGINT) END,
  744. reset = ?, last_online = %s
  745. WHERE email = ?`,
  746. database.ClampedAddExpr("up"),
  747. database.ClampedAddExpr("down"),
  748. enableExpr,
  749. database.GreatestExpr("last_online", "?"),
  750. ),
  751. deltaUp, deltaDown, cs.Enable, cs.Total,
  752. cs.ExpiryTime, cs.ExpiryTime, cs.Reset,
  753. cs.LastOnline, cs.Email,
  754. ).Error; err != nil {
  755. return false, err
  756. }
  757. }
  758. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon.Up, canon.Down); err != nil {
  759. return false, err
  760. }
  761. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: canon.Up, Down: canon.Down}
  762. }
  763. for k, existing := range centralCS {
  764. if dirty {
  765. continue
  766. }
  767. if k.inboundID != c.Id {
  768. continue
  769. }
  770. if _, kept := snapEmails[k.email]; kept {
  771. continue
  772. }
  773. // Gone from this inbound's stats but still reported by the node under
  774. // a sibling inbound: both the shared accumulator row and the (node,
  775. // email) baseline must survive, or the sibling's next delta would
  776. // compute against nothing and freeze the counter (#5202).
  777. if _, still := snapEmailsAll[k.email]; still {
  778. continue
  779. }
  780. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  781. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  782. return false, err
  783. }
  784. // Same shared-accumulator rule as the inbound-removal sweep above:
  785. // keep the row while another inbound still references the email.
  786. stillUsed, uErr := s.emailUsedByOtherInbounds(existing.Email, c.Id)
  787. if uErr != nil {
  788. return false, uErr
  789. }
  790. if !stillUsed {
  791. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  792. Delete(&xray.ClientTraffic{}).Error; err != nil {
  793. return false, err
  794. }
  795. }
  796. structuralChange = true
  797. }
  798. }
  799. type oldSet struct {
  800. inboundID int
  801. emails map[string]struct{}
  802. }
  803. var perInboundOld []oldSet
  804. for _, snapIb := range snap.Inbounds {
  805. if snapIb == nil {
  806. continue
  807. }
  808. c, ok := tagToCentral[snapIb.Tag]
  809. if !ok {
  810. continue
  811. }
  812. if dirty {
  813. continue
  814. }
  815. var oldEmailsRows []string
  816. if err := tx.Table("clients").
  817. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  818. Where("client_inbounds.inbound_id = ?", c.Id).
  819. Pluck("email", &oldEmailsRows).Error; err == nil {
  820. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  821. for _, e := range oldEmailsRows {
  822. if e != "" {
  823. oldEmails[e] = struct{}{}
  824. }
  825. }
  826. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  827. }
  828. clients, gcErr := s.GetClients(snapIb)
  829. if gcErr != nil {
  830. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  831. continue
  832. }
  833. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  834. for _, cs := range snapIb.ClientStats {
  835. csEnableByEmail[cs.Email] = cs.Enable
  836. }
  837. filtered := clients[:0]
  838. for i := range clients {
  839. if isClientEmailTombstoned(clients[i].Email) {
  840. continue
  841. }
  842. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  843. clients[i].Enable = false
  844. }
  845. filtered = append(filtered, clients[i])
  846. }
  847. localEmails := make([]string, 0, len(filtered))
  848. for i := range filtered {
  849. if filtered[i].Email != "" {
  850. localEmails = append(localEmails, filtered[i].Email)
  851. }
  852. }
  853. if len(localEmails) > 0 {
  854. var localMeta []struct {
  855. Email string
  856. Comment string `gorm:"column:comment"`
  857. }
  858. if err := tx.Table("clients").
  859. Select("email, comment").
  860. Where("email IN ?", localEmails).
  861. Find(&localMeta).Error; err == nil {
  862. commentByEmail := make(map[string]string, len(localMeta))
  863. for _, m := range localMeta {
  864. commentByEmail[m.Email] = m.Comment
  865. }
  866. for i := range filtered {
  867. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  868. filtered[i].Comment = cmt
  869. }
  870. }
  871. }
  872. }
  873. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  874. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  875. }
  876. }
  877. for _, old := range perInboundOld {
  878. var stillAttached []string
  879. if err := tx.Table("clients").
  880. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  881. Where("client_inbounds.inbound_id = ?", old.inboundID).
  882. Pluck("email", &stillAttached).Error; err != nil {
  883. continue
  884. }
  885. stillSet := make(map[string]struct{}, len(stillAttached))
  886. for _, e := range stillAttached {
  887. stillSet[e] = struct{}{}
  888. }
  889. for email := range old.emails {
  890. if _, kept := stillSet[email]; kept {
  891. continue
  892. }
  893. var attachmentCount int64
  894. if err := tx.Table("client_inbounds").
  895. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  896. Where("clients.email = ?", email).
  897. Count(&attachmentCount).Error; err != nil {
  898. continue
  899. }
  900. if attachmentCount > 0 {
  901. continue
  902. }
  903. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  904. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  905. }
  906. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  907. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  908. }
  909. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  910. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  911. }
  912. structuralChange = true
  913. }
  914. }
  915. if err := liftActivatedClientRecordExpiries(tx); err != nil {
  916. logger.Warning("setRemoteTraffic: lift activated expiries failed:", err)
  917. }
  918. if err := tx.Commit().Error; err != nil {
  919. return false, err
  920. }
  921. committed = true
  922. if len(adoptedInbounds) > 0 {
  923. if mgr := runtime.GetManager(); mgr != nil {
  924. if rt, rtErr := mgr.RuntimeFor(&nodeID); rtErr == nil {
  925. if rem, ok := rt.(*runtime.Remote); ok {
  926. for _, ib := range adoptedInbounds {
  927. rem.RecordAdoptedInbound(ib)
  928. }
  929. }
  930. }
  931. }
  932. }
  933. if p != nil {
  934. tree := snap.OnlineTree
  935. switch {
  936. case len(tree) == 0 && len(snap.OnlineEmails) > 0:
  937. // Old-build node (no GUID tree): key its flat online list under its
  938. // own effective identity so attribution still works for that branch.
  939. tree = map[string][]string{selfKey: snap.OnlineEmails}
  940. case guidShared && len(tree) > 0:
  941. // Newer cloned node: its own clients arrive keyed under the shared
  942. // panelGuid. Remap just that entry to the node-unique key so the
  943. // clones don't merge; descendant subtrees keep their distinct GUIDs.
  944. if _, ok := tree[nodeRow.Guid]; ok {
  945. remapped := make(map[string][]string, len(tree))
  946. for g, emails := range tree {
  947. if g == nodeRow.Guid {
  948. g = selfKey
  949. }
  950. remapped[g] = emails
  951. }
  952. tree = remapped
  953. }
  954. }
  955. p.SetNodeOnlineTree(nodeID, tree)
  956. }
  957. return structuralChange, nil
  958. }
  959. func (s *InboundService) GetOnlineClients() []string {
  960. if p == nil {
  961. return []string{}
  962. }
  963. return p.GetOnlineClients()
  964. }
  965. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  966. // node that physically hosts each set: this panel's own clients under its own
  967. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  968. // node-id keying so a client three hops down is attributed to its real node,
  969. // not the intermediate one it was synced through.
  970. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  971. if p == nil {
  972. return map[string][]string{}
  973. }
  974. out := p.GetMergedNodeTrees()
  975. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  976. if guid := s.panelGuid(); guid != "" {
  977. out[guid] = mergeEmails(out[guid], local)
  978. }
  979. }
  980. return out
  981. }
  982. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  983. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  984. // report per-inbound activity, so a GUID missing from the map means "don't
  985. // gate" for that node's inbounds.
  986. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  987. if p == nil {
  988. return map[string][]string{}
  989. }
  990. active := p.GetLocalActiveInbounds()
  991. if len(active) == 0 {
  992. return map[string][]string{}
  993. }
  994. guid := s.panelGuid()
  995. if guid == "" {
  996. return map[string][]string{}
  997. }
  998. return map[string][]string{guid: active}
  999. }
  1000. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  1001. if p != nil {
  1002. p.SetNodeOnlineTree(nodeID, tree)
  1003. }
  1004. }
  1005. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  1006. if p != nil {
  1007. p.ClearNodeOnlineClients(nodeID)
  1008. }
  1009. }
  1010. // panelGuid returns this panel's stable self-identifier, used to key the local
  1011. // panel's own clients in the per-node online maps (#4983).
  1012. func (s *InboundService) panelGuid() string {
  1013. guid, _ := (&SettingService{}).GetPanelGuid()
  1014. return guid
  1015. }
  1016. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  1017. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  1018. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  1019. // flat-topology case where an old-build node appears.
  1020. func synthNodeGuid(nodeID int) string {
  1021. return fmt.Sprintf("node:%d", nodeID)
  1022. }
  1023. // mergeEmails returns the deduped union of two email slices.
  1024. func mergeEmails(a, b []string) []string {
  1025. if len(a) == 0 {
  1026. return b
  1027. }
  1028. seen := make(map[string]struct{}, len(a)+len(b))
  1029. out := make([]string, 0, len(a)+len(b))
  1030. for _, e := range a {
  1031. if _, ok := seen[e]; !ok {
  1032. seen[e] = struct{}{}
  1033. out = append(out, e)
  1034. }
  1035. }
  1036. for _, e := range b {
  1037. if _, ok := seen[e]; !ok {
  1038. seen[e] = struct{}{}
  1039. out = append(out, e)
  1040. }
  1041. }
  1042. return out
  1043. }
  1044. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  1045. db := database.GetDB()
  1046. var rows []xray.ClientTraffic
  1047. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  1048. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1049. return nil, err
  1050. }
  1051. result := make(map[string]int64, len(rows))
  1052. for _, r := range rows {
  1053. result[r.Email] = r.LastOnline
  1054. }
  1055. return result, nil
  1056. }
  1057. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  1058. // panel's own xray this poll into the local online/active sets, applying the
  1059. // grace window and pruning stale entries. Pass nil to only prune. See
  1060. // xray.Process for why the local sets are kept separate from the shared
  1061. // last_online column.
  1062. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  1063. if p != nil {
  1064. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  1065. }
  1066. }
  1067. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  1068. db := database.GetDB()
  1069. // Step 1: Get ClientTraffic records for emails in the input list.
  1070. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  1071. uniqEmails := uniqueNonEmptyStrings(emails)
  1072. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  1073. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  1074. var page []xray.ClientTraffic
  1075. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1076. return nil, nil, err
  1077. }
  1078. clients = append(clients, page...)
  1079. }
  1080. // Step 2: Sort clients by (Up + Down) descending
  1081. sort.Slice(clients, func(i, j int) bool {
  1082. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  1083. })
  1084. // Step 3: Extract sorted valid emails and track found ones
  1085. validEmails := make([]string, 0, len(clients))
  1086. found := make(map[string]bool)
  1087. for _, client := range clients {
  1088. validEmails = append(validEmails, client.Email)
  1089. found[client.Email] = true
  1090. }
  1091. // Step 4: Identify emails that were not found in the database
  1092. extraEmails := make([]string, 0)
  1093. for _, email := range emails {
  1094. if !found[email] {
  1095. extraEmails = append(extraEmails, email)
  1096. }
  1097. }
  1098. return validEmails, extraEmails, nil
  1099. }