1
0

inbound_node.go 34 KB

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