1
0

node_client_traffic_sum_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. package service
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "gorm.io/gorm"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  12. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  13. )
  14. func initTrafficTestDB(t *testing.T) *gorm.DB {
  15. t.Helper()
  16. dbDir := t.TempDir()
  17. t.Setenv("XUI_DB_FOLDER", dbDir)
  18. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  19. return database.GetDB()
  20. }
  21. func createNodeInbound(t *testing.T, db *gorm.DB, nodeID int, tag string, port int) {
  22. t.Helper()
  23. nid := nodeID
  24. ib := &model.Inbound{UserId: 1, Tag: tag, Enable: true, Port: port, Protocol: model.VLESS, NodeID: &nid}
  25. if err := db.Create(ib).Error; err != nil {
  26. t.Fatalf("create node inbound %q: %v", tag, err)
  27. }
  28. }
  29. // createNodeInboundWithClient mirrors createNodeInbound but stores the client
  30. // in the settings JSON, which the node sync turns into a client_inbounds link.
  31. func createNodeInboundWithClient(t *testing.T, db *gorm.DB, nodeID int, tag string, port int, email string) {
  32. t.Helper()
  33. nid := nodeID
  34. settings := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  35. ib := &model.Inbound{UserId: 1, Tag: tag, Enable: true, Port: port, Protocol: model.VLESS, NodeID: &nid, Settings: settings}
  36. if err := db.Create(ib).Error; err != nil {
  37. t.Fatalf("create node inbound %q: %v", tag, err)
  38. }
  39. }
  40. func syncNode(t *testing.T, svc *InboundService, nodeID int, tag string, stats ...xray.ClientTraffic) {
  41. t.Helper()
  42. snap := &runtime.TrafficSnapshot{
  43. Inbounds: []*model.Inbound{{Tag: tag, ClientStats: stats}},
  44. }
  45. if _, err := svc.setRemoteTrafficLocked(nodeID, snap, false, false); err != nil {
  46. t.Fatalf("setRemoteTrafficLocked node %d: %v", nodeID, err)
  47. }
  48. }
  49. // syncNodeWithSettings mirrors syncNode but carries a real settings JSON on
  50. // the snapshot inbound, like production nodes do — the sync mirrors snapshot
  51. // settings onto the central row, and the shared-accumulator guard reads the
  52. // clients out of those settings.
  53. func syncNodeWithSettings(t *testing.T, svc *InboundService, nodeID int, tag, settings string, stats ...xray.ClientTraffic) {
  54. t.Helper()
  55. snap := &runtime.TrafficSnapshot{
  56. Inbounds: []*model.Inbound{{Tag: tag, Settings: settings, ClientStats: stats}},
  57. }
  58. if _, err := svc.setRemoteTrafficLocked(nodeID, snap, false, false); err != nil {
  59. t.Fatalf("setRemoteTrafficLocked node %d: %v", nodeID, err)
  60. }
  61. }
  62. func readTraffic(t *testing.T, db *gorm.DB, email string) xray.ClientTraffic {
  63. t.Helper()
  64. var ct xray.ClientTraffic
  65. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).First(&ct).Error; err != nil {
  66. t.Fatalf("read client_traffics %q: %v", email, err)
  67. }
  68. return ct
  69. }
  70. func assertUpDown(t *testing.T, ct xray.ClientTraffic, wantUp, wantDown int64, when string) {
  71. t.Helper()
  72. if ct.Up != wantUp || ct.Down != wantDown {
  73. t.Errorf("%s: up=%d down=%d, want %d/%d", when, ct.Up, ct.Down, wantUp, wantDown)
  74. }
  75. }
  76. func TestTwoNodesShareEmail_SumsCorrectly(t *testing.T) {
  77. db := initTrafficTestDB(t)
  78. createNodeInbound(t, db, 1, "n1-in", 41001)
  79. createNodeInbound(t, db, 2, "n2-in", 41002)
  80. svc := &InboundService{}
  81. const email = "shared"
  82. // First-ever sync from each node: the row is created at 0 and the current
  83. // node counters become the baseline. Only deltas beyond those baselines count.
  84. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  85. syncNode(t, svc, 2, "n2-in", xray.ClientTraffic{Email: email, Up: 200, Down: 200, Enable: true})
  86. assertUpDown(t, readTraffic(t, db, email), 0, 0, "after baselines — historical node traffic not imported")
  87. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 150, Down: 150, Enable: true})
  88. syncNode(t, svc, 2, "n2-in", xray.ClientTraffic{Email: email, Up: 260, Down: 260, Enable: true})
  89. assertUpDown(t, readTraffic(t, db, email), 110, 110, "after both nodes grow — deltas (50+60) accrue")
  90. }
  91. func TestSingleNode_MirrorsCorrectly(t *testing.T) {
  92. db := initTrafficTestDB(t)
  93. createNodeInbound(t, db, 1, "n1-in", 41001)
  94. svc := &InboundService{}
  95. const email = "solo"
  96. // First sync: row seeded at 0, current counter becomes the baseline.
  97. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 500, Down: 600, Enable: true})
  98. assertUpDown(t, readTraffic(t, db, email), 0, 0, "first sync — historical traffic not imported")
  99. // Second sync: delta (700-500=200 / 800-600=200) accrues normally.
  100. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 700, Down: 800, Enable: true})
  101. assertUpDown(t, readTraffic(t, db, email), 200, 200, "second sync — delta accrues")
  102. }
  103. func TestNodeAdd_ImportsClientHistoryWithNewInbound(t *testing.T) {
  104. db := initTrafficTestDB(t)
  105. svc := &InboundService{}
  106. const email = "newnode-client"
  107. const histUp, histDown int64 = 6_000_000_000, 200_000_000_000
  108. syncNode(t, svc, 1, "fresh-in", xray.ClientTraffic{Email: email, Up: histUp, Down: histDown, Enable: true})
  109. assertUpDown(t, readTraffic(t, db, email), histUp, histDown, "node-add: client history imported with its brand-new inbound")
  110. syncNode(t, svc, 1, "fresh-in", xray.ClientTraffic{Email: email, Up: histUp + 1024, Down: histDown + 2048, Enable: true})
  111. assertUpDown(t, readTraffic(t, db, email), histUp+1024, histDown+2048, "post-import delta accrues, no double count")
  112. }
  113. // TestStaleSnapshot_DeletedClientNotResurrected reproduces #5739: a snapshot
  114. // fetched just before a client's deletion still names the email. Applying it
  115. // must neither recreate the client_traffics row (at zero) nor re-add the
  116. // client to the central inbound's settings while the delete tombstone lives.
  117. func TestStaleSnapshot_DeletedClientNotResurrected(t *testing.T) {
  118. db := initTrafficTestDB(t)
  119. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "victim-5739")
  120. svc := &InboundService{}
  121. const email = "victim-5739"
  122. withClient := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  123. syncNodeWithSettings(t, svc, 1, "n1-in", withClient, xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  124. if err := db.Model(&model.Inbound{}).Where("tag = ?", "n1-in").
  125. Update("settings", `{"clients": []}`).Error; err != nil {
  126. t.Fatalf("clear central settings: %v", err)
  127. }
  128. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  129. t.Fatalf("delete stats row: %v", err)
  130. }
  131. tombstoneClientEmail(email)
  132. syncNodeWithSettings(t, svc, 1, "n1-in", withClient, xray.ClientTraffic{Email: email, Up: 120, Down: 120, Enable: true})
  133. var rows int64
  134. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Count(&rows).Error; err != nil {
  135. t.Fatalf("count stats rows: %v", err)
  136. }
  137. if rows != 0 {
  138. t.Errorf("deleted client's stats row resurrected by stale snapshot (%d rows)", rows)
  139. }
  140. var ib model.Inbound
  141. if err := db.Where("tag = ?", "n1-in").First(&ib).Error; err != nil {
  142. t.Fatalf("load inbound: %v", err)
  143. }
  144. if strings.Contains(ib.Settings, email) {
  145. t.Errorf("deleted client re-added to central settings: %s", ib.Settings)
  146. }
  147. }
  148. func TestNodeAdd_TombstonedClientNotResurrected(t *testing.T) {
  149. db := initTrafficTestDB(t)
  150. svc := &InboundService{}
  151. const email = "deleted-ghost"
  152. const stale int64 = 50_000_000_000
  153. tombstoneClientEmail(email)
  154. syncNode(t, svc, 1, "fresh-in", xray.ClientTraffic{Email: email, Up: stale, Down: stale, Enable: true})
  155. assertUpDown(t, readTraffic(t, db, email), 0, 0, "tombstoned client must not resurrect via node-add seed")
  156. }
  157. func TestUpgrade_PreExistingRow_NoDoubleCount(t *testing.T) {
  158. db := initTrafficTestDB(t)
  159. createNodeInbound(t, db, 1, "n1-in", 41001)
  160. svc := &InboundService{}
  161. const email = "legacy"
  162. var ib model.Inbound
  163. if err := db.Where("tag = ?", "n1-in").First(&ib).Error; err != nil {
  164. t.Fatalf("load inbound: %v", err)
  165. }
  166. if err := db.Create(&xray.ClientTraffic{InboundId: ib.Id, Email: email, Up: 1000, Down: 2000, Enable: true}).Error; err != nil {
  167. t.Fatalf("seed pre-existing row: %v", err)
  168. }
  169. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 1000, Down: 2000, Enable: true})
  170. assertUpDown(t, readTraffic(t, db, email), 1000, 2000, "first snapshot must not double-count")
  171. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 1100, Down: 2100, Enable: true})
  172. assertUpDown(t, readTraffic(t, db, email), 1100, 2100, "growth after upgrade accrues")
  173. }
  174. // TestGhostData_NoPhantomTraffic reproduces the 50 GB phantom traffic bug:
  175. // a node retains stale data for a deleted client (e.g. de-1 was offline during
  176. // deletion). When the master first syncs this email again it must NOT import the
  177. // stale counter — it sets Up=0 and records the current node value as the
  178. // baseline so only future deltas count.
  179. func TestGhostData_NoPhantomTraffic(t *testing.T) {
  180. db := initTrafficTestDB(t)
  181. createNodeInbound(t, db, 1, "de1-in", 41001)
  182. svc := &InboundService{}
  183. const email = "pouya"
  184. const staleBytes int64 = 50 * 1024 * 1024 * 1024 // 50 GB stale on de-1
  185. // Node reports a client with a large pre-existing counter (ghost data from a
  186. // deleted account that survived on the node). Master has no row for this email.
  187. syncNode(t, svc, 1, "de1-in", xray.ClientTraffic{Email: email, Up: staleBytes, Down: staleBytes, Enable: true})
  188. ct := readTraffic(t, db, email)
  189. if ct.Up >= staleBytes || ct.Down >= staleBytes {
  190. t.Errorf("ghost data imported: up=%d down=%d; stale node counter must not count as new traffic", ct.Up, ct.Down)
  191. }
  192. assertUpDown(t, ct, 0, 0, "first sync of ghost email — imported as 0, not 50 GB")
  193. // Subsequent syncs only add incremental usage beyond the baseline.
  194. syncNode(t, svc, 1, "de1-in", xray.ClientTraffic{Email: email, Up: staleBytes + 1024, Down: staleBytes + 2048, Enable: true})
  195. assertUpDown(t, readTraffic(t, db, email), 1024, 2048, "only incremental traffic beyond baseline counts")
  196. }
  197. func TestNodeCounterReset_NoReAdd(t *testing.T) {
  198. db := initTrafficTestDB(t)
  199. createNodeInbound(t, db, 1, "n1-in", 41001)
  200. svc := &InboundService{}
  201. const email = "restart"
  202. // First sync seeds at 0 (baseline=900). Second sync adds delta 950-900=50.
  203. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 900, Down: 900, Enable: true})
  204. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 950, Down: 950, Enable: true})
  205. assertUpDown(t, readTraffic(t, db, email), 50, 50, "before node reset")
  206. // Node reboot drops the counter to 50. delta=50-950=-900 is a counter reset,
  207. // not new traffic: add 0 and rebaseline to 50, never re-add the node's full
  208. // cumulative counter onto the master total (#5456).
  209. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 50, Down: 50, Enable: true})
  210. ct := readTraffic(t, db, email)
  211. if ct.Up < 0 || ct.Down < 0 {
  212. t.Fatalf("row went negative after node reset: up=%d down=%d", ct.Up, ct.Down)
  213. }
  214. assertUpDown(t, ct, 50, 50, "after node counter reset: rebaselined, not re-added")
  215. // Post-reset accrual resumes from the new baseline: 80-50=30.
  216. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 80, Down: 80, Enable: true})
  217. assertUpDown(t, readTraffic(t, db, email), 80, 80, "post-reset delta accrues from rebaselined counter")
  218. }
  219. func TestCentralReset_NoReAdd(t *testing.T) {
  220. db := initTrafficTestDB(t)
  221. createNodeInbound(t, db, 1, "n1-in", 41001)
  222. createNodeInbound(t, db, 2, "n2-in", 41002)
  223. svc := &InboundService{}
  224. const email = "reset"
  225. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  226. syncNode(t, svc, 2, "n2-in", xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  227. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 200, Down: 200, Enable: true})
  228. syncNode(t, svc, 2, "n2-in", xray.ClientTraffic{Email: email, Up: 200, Down: 200, Enable: true})
  229. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).
  230. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  231. t.Fatalf("simulate central reset: %v", err)
  232. }
  233. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 210, Down: 210, Enable: true})
  234. syncNode(t, svc, 2, "n2-in", xray.ClientTraffic{Email: email, Up: 205, Down: 205, Enable: true})
  235. assertUpDown(t, readTraffic(t, db, email), 15, 15, "after central reset only increments accrue")
  236. }
  237. // A real reset (ResetClientTrafficByEmail) must clear the per-node baseline so
  238. // the node's pre-reset cumulative — including traffic it counted but had not yet
  239. // synced — cannot leak back onto the master after the reset (#5476, #5390).
  240. func TestCentralResetClearsNodeBaseline_NoLeak(t *testing.T) {
  241. db := initTrafficTestDB(t)
  242. createNodeInbound(t, db, 1, "n1-in", 41001)
  243. StartTrafficWriter()
  244. svc := &InboundService{}
  245. const email = "reset-revert"
  246. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  247. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 300, Down: 300, Enable: true})
  248. assertUpDown(t, readTraffic(t, db, email), 200, 200, "before reset")
  249. if err := svc.ResetClientTrafficByEmail(email); err != nil {
  250. t.Fatalf("ResetClientTrafficByEmail: %v", err)
  251. }
  252. assertUpDown(t, readTraffic(t, db, email), 0, 0, "right after reset")
  253. var baselines int64
  254. if err := db.Model(&model.NodeClientTraffic{}).Where("email = ?", email).Count(&baselines).Error; err != nil {
  255. t.Fatalf("count baselines: %v", err)
  256. }
  257. if baselines != 0 {
  258. t.Fatalf("reset must clear node baseline rows, found %d", baselines)
  259. }
  260. // Node still reports its pre-reset cumulative (340 > last synced 300: usage it
  261. // had not synced before the reset). It must not revert the reset.
  262. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 340, Down: 340, Enable: true})
  263. assertUpDown(t, readTraffic(t, db, email), 0, 0, "stale node counter must not revert reset")
  264. // Genuine post-reset usage accrues from the rebaselined counter: 370-340=30.
  265. syncNode(t, svc, 1, "n1-in", xray.ClientTraffic{Email: email, Up: 370, Down: 370, Enable: true})
  266. assertUpDown(t, readTraffic(t, db, email), 30, 30, "post-reset usage accrues")
  267. }
  268. func TestInboundRemoval_KeepsSharedEmailRow(t *testing.T) {
  269. db := initTrafficTestDB(t)
  270. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "shared")
  271. createNodeInboundWithClient(t, db, 2, "n2-in", 41002, "shared")
  272. svc := &InboundService{}
  273. const email = "shared"
  274. settings := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  275. // Baselines set: node1=100, node2=200. Row seeded at 0.
  276. syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  277. syncNodeWithSettings(t, svc, 2, "n2-in", settings, xray.ClientTraffic{Email: email, Up: 200, Down: 200, Enable: true})
  278. // node1 delta=50, node2 delta=60 → total=110.
  279. syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 150, Down: 150, Enable: true})
  280. syncNodeWithSettings(t, svc, 2, "n2-in", settings, xray.ClientTraffic{Email: email, Up: 260, Down: 260, Enable: true})
  281. assertUpDown(t, readTraffic(t, db, email), 110, 110, "baseline sum")
  282. // Node 1 rebuilt (reinstall / another master's reconcile): its inbound
  283. // vanishes from the snapshot. The shared accumulator must survive — losing
  284. // it would let the next node sync re-seed the row with that node's counter
  285. // alone, showing only the last panel's number instead of the sum.
  286. if _, err := svc.setRemoteTrafficLocked(1, &runtime.TrafficSnapshot{}, false, false); err != nil {
  287. t.Fatalf("sync node 1 with empty snapshot: %v", err)
  288. }
  289. assertUpDown(t, readTraffic(t, db, email), 110, 110, "after node 1 inbound removal")
  290. // Node 2 keeps accruing onto the surviving row. node2 delta=300-260=40 → 150.
  291. syncNodeWithSettings(t, svc, 2, "n2-in", settings, xray.ClientTraffic{Email: email, Up: 300, Down: 300, Enable: true})
  292. assertUpDown(t, readTraffic(t, db, email), 150, 150, "after node 2 grows")
  293. }
  294. func TestClientGoneFromOneNode_KeepsSharedEmailRow(t *testing.T) {
  295. db := initTrafficTestDB(t)
  296. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "shared")
  297. createNodeInboundWithClient(t, db, 2, "n2-in", 41002, "shared")
  298. svc := &InboundService{}
  299. const email = "shared"
  300. settings := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  301. // First syncs set baselines (node1=100, node2=200). Row seeded at 0.
  302. syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: email, Up: 100, Down: 100, Enable: true})
  303. syncNodeWithSettings(t, svc, 2, "n2-in", settings, xray.ClientTraffic{Email: email, Up: 200, Down: 200, Enable: true})
  304. // Client detached from node 1's inbound only: its stats vanish from that
  305. // inbound's snapshot while node 2 still hosts the email.
  306. syncNodeWithSettings(t, svc, 1, "n1-in", `{"clients": []}`)
  307. assertUpDown(t, readTraffic(t, db, email), 0, 0, "after client left node 1 — row unchanged at 0")
  308. // Node 2 delta: 240-200=40 → accrues to 40.
  309. syncNodeWithSettings(t, svc, 2, "n2-in", settings, xray.ClientTraffic{Email: email, Up: 240, Down: 240, Enable: true})
  310. assertUpDown(t, readTraffic(t, db, email), 40, 40, "node 2 keeps accruing")
  311. }
  312. // TestStatsUnderSiblingInbound_KeepsNodeBaseline reproduces the recurring
  313. // sweep bug behind #5202: the client is attached to two inbounds of the SAME
  314. // node, the node reports its stats under n1-a only, but the master-side row
  315. // is owned by n1-b's mirror. The per-email sweep for n1-b must not drop the
  316. // (node, email) baseline that n1-a's delta computation needs — doing so every
  317. // cycle froze the client's counter permanently.
  318. func TestStatsUnderSiblingInbound_KeepsNodeBaseline(t *testing.T) {
  319. db := initTrafficTestDB(t)
  320. createNodeInboundWithClient(t, db, 1, "n1-a", 41001, "fresh")
  321. createNodeInbound(t, db, 1, "n1-b", 41002)
  322. svc := &InboundService{}
  323. const email = "fresh"
  324. var ibB model.Inbound
  325. if err := db.Where("tag = ?", "n1-b").First(&ibB).Error; err != nil {
  326. t.Fatalf("load n1-b: %v", err)
  327. }
  328. // Master-side row created when the client was added on the panel, owned by
  329. // n1-b's mirror (e.g. the client form targeted that inbound).
  330. if err := db.Create(&xray.ClientTraffic{InboundId: ibB.Id, Email: email, Enable: true}).Error; err != nil {
  331. t.Fatalf("seed master row: %v", err)
  332. }
  333. settings := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  334. sync := func(up, down int64) {
  335. t.Helper()
  336. snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
  337. {Tag: "n1-a", Settings: settings, ClientStats: []xray.ClientTraffic{{Email: email, Up: up, Down: down, Enable: true}}},
  338. {Tag: "n1-b", Settings: `{"clients": []}`},
  339. }}
  340. if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil {
  341. t.Fatalf("sync: %v", err)
  342. }
  343. }
  344. sync(630, 630)
  345. var baselines int64
  346. if err := db.Model(&model.NodeClientTraffic{}).Where("node_id = ? AND email = ?", 1, email).Count(&baselines).Error; err != nil {
  347. t.Fatalf("count baselines: %v", err)
  348. }
  349. if baselines != 1 {
  350. t.Fatalf("baseline must survive the sibling-inbound sweep, found %d rows", baselines)
  351. }
  352. sync(700, 700)
  353. assertUpDown(t, readTraffic(t, db, email), 70, 70, "delta accrues once baseline survives")
  354. }
  355. // TestMultiAttach_SameNode_DivergentSiblings reproduces #5274: a client is
  356. // attached to several inbounds of the SAME node. Xray reports client traffic
  357. // globally per email, so the node's enriched inbound list copies one shared
  358. // counter onto every inbound the client is on. When those copies diverge — a
  359. // legacy per-inbound row surviving the v3.2.x→v3.3.x upgrade, or any drift —
  360. // the per-inbound delta loop used to treat the lower sibling as a node-counter
  361. // reset and re-add its full value, inflating the client far past real usage.
  362. // The merge must collapse the email to its node-wide total and count it once.
  363. func TestMultiAttach_SameNode_DivergentSiblings(t *testing.T) {
  364. db := initTrafficTestDB(t)
  365. createNodeInboundWithClient(t, db, 1, "n1-a", 41001, "multi")
  366. createNodeInboundWithClient(t, db, 1, "n1-b", 41002, "multi")
  367. createNodeInboundWithClient(t, db, 1, "n1-c", 41003, "multi")
  368. svc := &InboundService{}
  369. const email = "multi"
  370. settings := fmt.Sprintf(`{"clients": [{"email": %q, "enable": true}]}`, email)
  371. // The three inbounds report the same email with diverging values; the
  372. // node's true per-email total is the largest (the shared global counter).
  373. sync := func(a, b, c int64) {
  374. t.Helper()
  375. snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
  376. {Tag: "n1-a", Settings: settings, ClientStats: []xray.ClientTraffic{{Email: email, Up: a, Down: a, Enable: true}}},
  377. {Tag: "n1-b", Settings: settings, ClientStats: []xray.ClientTraffic{{Email: email, Up: b, Down: b, Enable: true}}},
  378. {Tag: "n1-c", Settings: settings, ClientStats: []xray.ClientTraffic{{Email: email, Up: c, Down: c, Enable: true}}},
  379. }}
  380. if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil {
  381. t.Fatalf("sync: %v", err)
  382. }
  383. }
  384. // First-ever sync: row seeded at 0, canon (max of siblings = 100) becomes the
  385. // baseline. The node total is NOT imported as historical traffic — this prevents
  386. // ghost data from a previously-deleted account being counted as real usage.
  387. sync(100, 50, 80)
  388. assertUpDown(t, readTraffic(t, db, email), 0, 0, "first sync seeds at 0 — not the sum (230) nor the max (100)")
  389. // Second sync: canon grew from 100→150, delta=50 accrues. Siblings 60 and 90
  390. // do not re-add their full values — the canon clamp prevents inflation.
  391. sync(150, 60, 90)
  392. assertUpDown(t, readTraffic(t, db, email), 50, 50, "second sync: only the 50-unit increment counts, not every sibling")
  393. // Equal siblings (the healthy current-schema case): canon grew from 150→200,
  394. // delta=50 accrues once.
  395. sync(200, 200, 200)
  396. assertUpDown(t, readTraffic(t, db, email), 100, 100, "equal siblings accrue the single increment")
  397. }
  398. func TestDelClientStat_CleansNodeBaselines(t *testing.T) {
  399. db := initTrafficTestDB(t)
  400. svc := &InboundService{}
  401. const email = "gone"
  402. if err := db.Create(&xray.ClientTraffic{InboundId: 1, Email: email, Enable: true}).Error; err != nil {
  403. t.Fatalf("seed client_traffics: %v", err)
  404. }
  405. if err := db.Create(&model.NodeClientTraffic{NodeId: 1, Email: email, Up: 10, Down: 10}).Error; err != nil {
  406. t.Fatalf("seed node baseline 1: %v", err)
  407. }
  408. if err := db.Create(&model.NodeClientTraffic{NodeId: 2, Email: email, Up: 20, Down: 20}).Error; err != nil {
  409. t.Fatalf("seed node baseline 2: %v", err)
  410. }
  411. if err := svc.DelClientStat(db, email); err != nil {
  412. t.Fatalf("DelClientStat: %v", err)
  413. }
  414. var cnt int64
  415. if err := db.Model(&model.NodeClientTraffic{}).Where("email = ?", email).Count(&cnt).Error; err != nil {
  416. t.Fatalf("count baselines: %v", err)
  417. }
  418. if cnt != 0 {
  419. t.Errorf("expected node baselines cleaned, found %d", cnt)
  420. }
  421. }
  422. func TestNodeDelete_CleansNodeBaselines(t *testing.T) {
  423. db := initTrafficTestDB(t)
  424. nodeSvc := NodeService{}
  425. if err := db.Create(&model.NodeClientTraffic{NodeId: 7, Email: "a", Up: 1, Down: 1}).Error; err != nil {
  426. t.Fatalf("seed node 7 a: %v", err)
  427. }
  428. if err := db.Create(&model.NodeClientTraffic{NodeId: 7, Email: "b", Up: 2, Down: 2}).Error; err != nil {
  429. t.Fatalf("seed node 7 b: %v", err)
  430. }
  431. if err := db.Create(&model.NodeClientTraffic{NodeId: 8, Email: "c", Up: 3, Down: 3}).Error; err != nil {
  432. t.Fatalf("seed node 8 c: %v", err)
  433. }
  434. if err := nodeSvc.Delete(7); err != nil {
  435. t.Fatalf("NodeService.Delete(7): %v", err)
  436. }
  437. var sevenCnt, eightCnt int64
  438. db.Model(&model.NodeClientTraffic{}).Where("node_id = ?", 7).Count(&sevenCnt)
  439. db.Model(&model.NodeClientTraffic{}).Where("node_id = ?", 8).Count(&eightCnt)
  440. if sevenCnt != 0 {
  441. t.Errorf("node 7 baselines not cleaned: %d remain", sevenCnt)
  442. }
  443. if eightCnt != 1 {
  444. t.Errorf("node 8 baseline should survive, found %d", eightCnt)
  445. }
  446. }