inbound_node.go 38 KB

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