inbound_node.go 40 KB

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