1
0

node_sweep_guard_test.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package service
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. "gorm.io/gorm"
  10. )
  11. func countClientRows(t *testing.T, db *gorm.DB, email string) (records, traffics int64) {
  12. t.Helper()
  13. if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).Count(&records).Error; err != nil {
  14. t.Fatalf("count clients %q: %v", email, err)
  15. }
  16. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Count(&traffics).Error; err != nil {
  17. t.Fatalf("count client_traffics %q: %v", email, err)
  18. }
  19. return records, traffics
  20. }
  21. func seedNodeRow(t *testing.T, db *gorm.DB, n *model.Node) {
  22. t.Helper()
  23. if err := db.Create(n).Error; err != nil {
  24. t.Fatalf("create node: %v", err)
  25. }
  26. }
  27. func snapshotWithClients(t *testing.T, tag, settings string, stats ...xray.ClientTraffic) *runtime.TrafficSnapshot {
  28. t.Helper()
  29. return &runtime.TrafficSnapshot{
  30. Inbounds: []*model.Inbound{{Tag: tag, Settings: settings, ClientStats: stats}},
  31. }
  32. }
  33. func snapshotWithoutClients(t *testing.T, tag string) *runtime.TrafficSnapshot {
  34. t.Helper()
  35. return snapshotWithClients(t, tag, `{"clients":[]}`)
  36. }
  37. func snapshotWithTwoInbounds(t *testing.T, tagA, settingsA, emailA, tagB, settingsB, emailB string) *runtime.TrafficSnapshot {
  38. t.Helper()
  39. return &runtime.TrafficSnapshot{
  40. Inbounds: []*model.Inbound{
  41. {Tag: tagA, Settings: settingsA, ClientStats: []xray.ClientTraffic{{Email: emailA, Enable: true}}},
  42. {Tag: tagB, Settings: settingsB, ClientStats: []xray.ClientTraffic{{Email: emailB, Enable: true}}},
  43. },
  44. }
  45. }
  46. // The job samples config_dirty before the snapshot round-trip; a client added
  47. // in that window is deleted again unless the merge re-reads the flag itself.
  48. func TestSetRemoteTrafficRereadsConfigDirty(t *testing.T) {
  49. db := initTrafficTestDB(t)
  50. svc := &InboundService{}
  51. seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
  52. const email = "carol"
  53. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, email)
  54. settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, email)
  55. syncNodeWithSettings(t, svc, 1, "n1-in", settings,
  56. xray.ClientTraffic{Email: email, Up: 1, Down: 1, Enable: true})
  57. if rec, _ := countClientRows(t, db, email); rec != 1 {
  58. t.Fatalf("setup: client not attached, got %d rows", rec)
  59. }
  60. if err := db.Model(model.Node{}).Where("id = ?", 1).Update("config_dirty", true).Error; err != nil {
  61. t.Fatalf("mark node dirty: %v", err)
  62. }
  63. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithoutClients(t, "n1-in"), false); err != nil {
  64. t.Fatalf("setRemoteTrafficLocked: %v", err)
  65. }
  66. rec, traf := countClientRows(t, db, email)
  67. if rec != 1 || traf != 1 {
  68. t.Fatalf("stale dirty=false wiped a client added mid-flight: clients=%d client_traffics=%d, want 1/1", rec, traf)
  69. }
  70. }
  71. // FilterNodeSnapshot stops reporting a deselected tag; reading that absence as
  72. // "the node deleted it" wiped the master's copy of an inbound still running.
  73. func TestDeselectedTagIsNotSwept(t *testing.T) {
  74. db := initTrafficTestDB(t)
  75. svc := &InboundService{}
  76. seedNodeRow(t, db, &model.Node{
  77. Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true,
  78. InboundSyncMode: "selected", InboundTags: []string{"keep"},
  79. })
  80. createNodeInboundWithClient(t, db, 1, "keep", 41001, "kept@x")
  81. createNodeInboundWithClient(t, db, 1, "drop", 41002, "dropped@x")
  82. keepSettings := `{"clients":[{"email":"kept@x","enable":true}]}`
  83. dropSettings := `{"clients":[{"email":"dropped@x","enable":true}]}`
  84. snap := snapshotWithTwoInbounds(t, "keep", keepSettings, "kept@x", "drop", dropSettings, "dropped@x")
  85. if _, err := svc.setRemoteTrafficLocked(1, snap, false); err != nil {
  86. t.Fatalf("seed sync: %v", err)
  87. }
  88. if rec, traf := countClientRows(t, db, "dropped@x"); rec != 1 || traf != 1 {
  89. t.Fatalf("setup: dropped@x not seeded, clients=%d client_traffics=%d", rec, traf)
  90. }
  91. keepOnly := snapshotWithClients(t, "keep", keepSettings, xray.ClientTraffic{Email: "kept@x", Enable: true})
  92. if _, err := svc.setRemoteTrafficLocked(1, keepOnly, false); err != nil {
  93. t.Fatalf("post-deselect sync: %v", err)
  94. }
  95. rec, traf := countClientRows(t, db, "dropped@x")
  96. if rec != 1 || traf != 1 {
  97. t.Fatalf("deselecting a tag deleted its clients: clients=%d client_traffics=%d, want 1/1", rec, traf)
  98. }
  99. var inbounds int64
  100. if err := db.Model(model.Inbound{}).Where("tag = ?", "drop").Count(&inbounds).Error; err != nil {
  101. t.Fatalf("count inbounds: %v", err)
  102. }
  103. if inbounds != 1 {
  104. t.Fatalf("deselecting a tag deleted the inbound the node still serves: got %d rows, want 1", inbounds)
  105. }
  106. }
  107. func TestSyncInboundStoresTrimmedEmail(t *testing.T) {
  108. db := initTrafficTestDB(t)
  109. svc := &ClientService{}
  110. ib := &model.Inbound{UserId: 1, Tag: "trim-in", Enable: true, Port: 41501, Protocol: model.VLESS}
  111. if err := database.GetDB().Create(ib).Error; err != nil {
  112. t.Fatalf("create inbound: %v", err)
  113. }
  114. padded := "bob "
  115. clients := []model.Client{{Email: padded, Enable: true}}
  116. if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
  117. t.Fatalf("first SyncInbound: %v", err)
  118. }
  119. var stored []string
  120. if err := db.Model(&model.ClientRecord{}).Pluck("email", &stored).Error; err != nil {
  121. t.Fatalf("read clients: %v", err)
  122. }
  123. if len(stored) != 1 || stored[0] != "bob" {
  124. t.Fatalf("stored email = %q, want the trimmed %q — the lookup key must match what is written", stored, "bob")
  125. }
  126. if err := svc.SyncInbound(nil, ib.Id, clients); err != nil {
  127. t.Fatalf("second SyncInbound must not hit a unique-constraint on the untrimmed row: %v", err)
  128. }
  129. var links int64
  130. if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", ib.Id).Count(&links).Error; err != nil {
  131. t.Fatalf("count links: %v", err)
  132. }
  133. if links != 1 {
  134. t.Fatalf("links after re-sync = %d, want 1", links)
  135. }
  136. }