1
0

node_http_fake_test.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. )
  15. // fakeNodeHTTP emulates a node panel over real HTTP, so the master's Remote
  16. // (tag cache, list fetch, per-op RPC, timeouts) runs for real, not a stub.
  17. type fakeNodeHTTP struct {
  18. srv *httptest.Server
  19. mu sync.Mutex
  20. tags map[string]int
  21. hits map[string]int
  22. // hold makes every non-list request block until the master gives up.
  23. hold bool
  24. release chan struct{}
  25. }
  26. func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP {
  27. t.Helper()
  28. f := &fakeNodeHTTP{tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{})}
  29. f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  30. w.Header().Set("Content-Type", "application/json")
  31. if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
  32. f.mu.Lock()
  33. f.hits["list"]++
  34. type ent struct {
  35. Id int `json:"id"`
  36. Tag string `json:"tag"`
  37. }
  38. list := make([]ent, 0, len(f.tags))
  39. for tag, id := range f.tags {
  40. list = append(list, ent{Id: id, Tag: tag})
  41. }
  42. f.mu.Unlock()
  43. b, _ := json.Marshal(list)
  44. _, _ = w.Write([]byte(`{"success":true,"msg":"","obj":` + string(b) + `}`))
  45. return
  46. }
  47. f.mu.Lock()
  48. f.hits[r.URL.Path]++
  49. hold := f.hold
  50. f.mu.Unlock()
  51. if hold {
  52. // Drain first: the server only notices a client disconnect once the
  53. // body is consumed, and Close would otherwise wait on this forever.
  54. _, _ = io.Copy(io.Discard, r.Body)
  55. select {
  56. case <-r.Context().Done():
  57. case <-f.release:
  58. }
  59. return
  60. }
  61. _, _ = w.Write([]byte(`{"success":true,"msg":""}`))
  62. }))
  63. t.Cleanup(f.srv.Close)
  64. // Registered after Close, so it runs first and frees any held handler.
  65. t.Cleanup(func() { close(f.release) })
  66. return f
  67. }
  68. func (f *fakeNodeHTTP) setHold(v bool) {
  69. f.mu.Lock()
  70. defer f.mu.Unlock()
  71. f.hold = v
  72. }
  73. // hitCount is how many requests whose path contains pathPart reached the node.
  74. func (f *fakeNodeHTTP) hitCount(pathPart string) int {
  75. f.mu.Lock()
  76. defer f.mu.Unlock()
  77. n := 0
  78. for path, c := range f.hits {
  79. if strings.Contains(path, pathPart) {
  80. n += c
  81. }
  82. }
  83. return n
  84. }
  85. // realNodeInbound creates a Node row pointing at the fake server plus one
  86. // inbound on it, with NO runtime override so RuntimeFor builds a real Remote.
  87. func realNodeInbound(t *testing.T, f *fakeNodeHTTP, port int, clients []model.Client) *model.Inbound {
  88. t.Helper()
  89. hostPart, portStr, _ := strings.Cut(strings.TrimPrefix(f.srv.URL, "http://"), ":")
  90. srvPort, err := strconv.Atoi(portStr)
  91. if err != nil {
  92. t.Fatalf("parse fake node port: %v", err)
  93. }
  94. node := &model.Node{
  95. Name: fmt.Sprintf("%s-%d", t.Name(), port), Scheme: "http", Address: hostPart, Port: srvPort,
  96. BasePath: "/", ApiToken: "tok", Enable: true, Status: "online",
  97. AllowPrivateAddress: true, TlsVerifyMode: "verify",
  98. }
  99. if err := database.GetDB().Create(node).Error; err != nil {
  100. t.Fatalf("create node: %v", err)
  101. }
  102. ib := nodeInbound(t, node.Id, port, clients)
  103. f.mu.Lock()
  104. f.tags[ib.Tag] = 100 + port%100
  105. f.mu.Unlock()
  106. return ib
  107. }