node_degraded_snapshot_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "sync"
  9. "testing"
  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. "gorm.io/gorm"
  14. )
  15. // linkCount returns how many client_inbounds links a client currently has,
  16. // across every inbound — the value ReapSyncOrphans checks before deleting.
  17. func linkCount(t *testing.T, db *gorm.DB, email string) int64 {
  18. t.Helper()
  19. var n int64
  20. if err := db.Table("client_inbounds").
  21. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  22. Where("clients.email = ?", email).
  23. Count(&n).Error; err != nil {
  24. t.Fatalf("count links for %q: %v", email, err)
  25. }
  26. return n
  27. }
  28. // A degraded node reporting zero clients for an inbound the hub populates must
  29. // keep its links and never orphan-mark, or SyncInbound/ReapSyncOrphans delete the row.
  30. func TestSetRemoteTraffic_EmptySnapshotKeepsClients(t *testing.T) {
  31. db := initTrafficTestDB(t)
  32. svc := &InboundService{}
  33. seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
  34. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "svc@x")
  35. settings := `{"clients":[{"email":"svc@x","enable":true}]}`
  36. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithClients(t, "n1-in", settings,
  37. xray.ClientTraffic{Email: "svc@x", Enable: true}), false, false); err != nil {
  38. t.Fatalf("seed sync: %v", err)
  39. }
  40. if n := linkCount(t, db, "svc@x"); n != 1 {
  41. t.Fatalf("setup: svc@x links=%d, want 1", n)
  42. }
  43. // The node returns an empty snapshot — the trigger that deleted real clients.
  44. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithoutClients(t, "n1-in"), false, false); err != nil {
  45. t.Fatalf("empty-snapshot sync: %v", err)
  46. }
  47. if rec, _ := countClientRows(t, db, "svc@x"); rec != 1 {
  48. t.Fatalf("empty snapshot deleted the client row: clients=%d, want 1", rec)
  49. }
  50. if n := linkCount(t, db, "svc@x"); n != 1 {
  51. t.Fatalf("empty snapshot stripped the client link: links=%d, want 1", n)
  52. }
  53. if at := readOrphanMark(t, db, "svc@x"); at != 0 {
  54. t.Fatalf("empty snapshot orphan-marked a live client: sync_orphaned_at=%d, want 0", at)
  55. }
  56. // The hub must keep the client in the inbound's settings, or reconcile re-pushes
  57. // an empty blob to the node and the clients never come back (#6734).
  58. var ib model.Inbound
  59. if err := db.Where("tag = ?", "n1-in").First(&ib).Error; err != nil {
  60. t.Fatalf("read central inbound: %v", err)
  61. }
  62. if !strings.Contains(ib.Settings, "svc@x") {
  63. t.Fatalf("empty snapshot blanked the inbound settings: %q", ib.Settings)
  64. }
  65. }
  66. // The guard is narrow: a snapshot still carrying a client is authoritative, so a
  67. // client the node really dropped is unlinked and orphan-marked; only all-empty is degraded.
  68. func TestSetRemoteTraffic_PartialSnapshotStillPrunes(t *testing.T) {
  69. db := initTrafficTestDB(t)
  70. svc := &InboundService{}
  71. seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
  72. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "keep@x")
  73. bothSettings := `{"clients":[{"email":"keep@x","enable":true},{"email":"drop@x","enable":true}]}`
  74. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithClients(t, "n1-in", bothSettings,
  75. xray.ClientTraffic{Email: "keep@x", Enable: true},
  76. xray.ClientTraffic{Email: "drop@x", Enable: true}), false, false); err != nil {
  77. t.Fatalf("seed sync: %v", err)
  78. }
  79. if n := linkCount(t, db, "drop@x"); n != 1 {
  80. t.Fatalf("setup: drop@x links=%d, want 1", n)
  81. }
  82. // Node now reports only keep@x — drop@x was genuinely removed there.
  83. keepOnlySettings := `{"clients":[{"email":"keep@x","enable":true}]}`
  84. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithClients(t, "n1-in", keepOnlySettings,
  85. xray.ClientTraffic{Email: "keep@x", Enable: true}), false, false); err != nil {
  86. t.Fatalf("partial-snapshot sync: %v", err)
  87. }
  88. if n := linkCount(t, db, "keep@x"); n != 1 {
  89. t.Fatalf("partial snapshot dropped a reported client: keep@x links=%d, want 1", n)
  90. }
  91. if n := linkCount(t, db, "drop@x"); n != 0 {
  92. t.Fatalf("partial snapshot kept an unreported client linked: drop@x links=%d, want 0", n)
  93. }
  94. if at := readOrphanMark(t, db, "drop@x"); at <= 0 {
  95. t.Fatalf("partial snapshot did not orphan-mark the removed client: sync_orphaned_at=%d, want >0", at)
  96. }
  97. }
  98. // Keeping the hub's settings is not recovery: the node is only healed once the
  99. // hub actually re-pushes them, which needs a dirty node and a stale fingerprint.
  100. func TestSetRemoteTraffic_EmptySnapshotRepushesHubClients(t *testing.T) {
  101. db := initTrafficTestDB(t)
  102. svc := &InboundService{}
  103. var mu sync.Mutex
  104. var pushed []string
  105. writeOK := func(w http.ResponseWriter, obj any) {
  106. w.Header().Set("Content-Type", "application/json")
  107. _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "msg": "", "obj": obj})
  108. }
  109. mux := http.NewServeMux()
  110. mux.HandleFunc("/panel/api/inbounds/list", func(w http.ResponseWriter, _ *http.Request) {
  111. writeOK(w, []map[string]any{{"id": 7, "tag": "deg-in", "port": 41001, "protocol": "vless"}})
  112. })
  113. mux.HandleFunc("/panel/api/inbounds/update/", func(w http.ResponseWriter, r *http.Request) {
  114. if err := r.ParseForm(); err != nil {
  115. http.Error(w, err.Error(), http.StatusBadRequest)
  116. return
  117. }
  118. mu.Lock()
  119. pushed = append(pushed, r.PostForm.Get("settings"))
  120. mu.Unlock()
  121. writeOK(w, nil)
  122. })
  123. ts := httptest.NewServer(mux)
  124. t.Cleanup(ts.Close)
  125. node := reconcileTestNode(t, ts, "deg-node", "all", nil)
  126. settings := `{"clients":[{"email":"svc@x","enable":true,"id":"11111111-1111-1111-1111-111111111111"}]}`
  127. nid := node.Id
  128. if err := db.Create(&model.Inbound{UserId: 1, Tag: "deg-in", Enable: true, Port: 41001, Protocol: model.VLESS, NodeID: &nid, Settings: settings}).Error; err != nil {
  129. t.Fatalf("create inbound: %v", err)
  130. }
  131. rt := runtime.NewRemote(node, nil)
  132. mgr := runtime.NewManager(runtime.LocalDeps{})
  133. mgr.SetRuntimeOverride(node.Id, rt)
  134. runtime.SetManager(mgr)
  135. t.Cleanup(func() { runtime.SetManager(nil) })
  136. if _, err := svc.setRemoteTrafficLocked(node.Id, snapshotWithClients(t, "deg-in", settings,
  137. xray.ClientTraffic{Email: "svc@x", Enable: true}), false, false); err != nil {
  138. t.Fatalf("seed sync: %v", err)
  139. }
  140. if err := svc.ReconcileNode(context.Background(), rt, node); err != nil {
  141. t.Fatalf("first reconcile: %v", err)
  142. }
  143. mu.Lock()
  144. pushed = nil
  145. mu.Unlock()
  146. if _, err := svc.setRemoteTrafficLocked(node.Id, snapshotWithoutClients(t, "deg-in"), false, false); err != nil {
  147. t.Fatalf("empty-snapshot sync: %v", err)
  148. }
  149. var after model.Node
  150. if err := db.Where("id = ?", node.Id).First(&after).Error; err != nil {
  151. t.Fatalf("reload node: %v", err)
  152. }
  153. if !after.ConfigDirty {
  154. t.Fatal("empty snapshot left the node clean: the job never reconciles it, so the node stays without its clients")
  155. }
  156. if err := svc.ReconcileNode(context.Background(), rt, &after); err != nil {
  157. t.Fatalf("reconcile after empty snapshot: %v", err)
  158. }
  159. mu.Lock()
  160. defer mu.Unlock()
  161. if len(pushed) != 1 || !strings.Contains(pushed[0], "svc@x") {
  162. t.Fatalf("reconcile after empty snapshot pushed %d settings payload(s) %q, want one carrying svc@x", len(pushed), pushed)
  163. }
  164. }
  165. // The traffic a client used while its node reported nothing must still count
  166. // once the node reports it again.
  167. func TestSetRemoteTraffic_EmptySnapshotKeepsTrafficBaseline(t *testing.T) {
  168. db := initTrafficTestDB(t)
  169. svc := &InboundService{}
  170. seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
  171. createNodeInboundWithClient(t, db, 1, "n1-in", 41001, "svc@x")
  172. settings := `{"clients":[{"email":"svc@x","enable":true}]}`
  173. for _, used := range []int64{100, 200} {
  174. syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: "svc@x", Up: used, Down: used, Enable: true})
  175. }
  176. before := readTraffic(t, db, "svc@x")
  177. if _, err := svc.setRemoteTrafficLocked(1, snapshotWithoutClients(t, "n1-in"), false, false); err != nil {
  178. t.Fatalf("empty-snapshot sync: %v", err)
  179. }
  180. syncNodeWithSettings(t, svc, 1, "n1-in", settings, xray.ClientTraffic{Email: "svc@x", Up: 250, Down: 250, Enable: true})
  181. assertUpDown(t, readTraffic(t, db, "svc@x"), before.Up+50, before.Down+50, "after the node recovered")
  182. }