1
0

inbound_node.go 37 KB

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