node_client_traffic_sum_test.go 22 KB

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