Files
mirror-3x-ui/internal/web/service/node_http_fake_test.go
T
Hamed 0afa11ddff fix(nodes): share lightweight remote inbound catalog refreshes (#7313)
Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations.

Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405.

Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark.

Fixes #7303.
2026-12-03 03:26:44 +03:30

148 lines
4.1 KiB
Go

package service
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec"
)
// fakeNodeHTTP emulates a node panel over real HTTP, so the master's Remote
// (tag cache, list fetch, per-op RPC, timeouts) runs for real, not a stub.
type fakeNodeHTTP struct {
srv *httptest.Server
mu sync.Mutex
tags map[string]int
hits map[string]int
caps string
pendingClientAcks int
clientAdds []ClientCreatePayload
clientAddEvents chan ClientCreatePayload
// hold makes requests outside inbound discovery block until the master gives up.
hold bool
release chan struct{}
}
func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP {
t.Helper()
f := &fakeNodeHTTP{
tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{}),
clientAddEvents: make(chan ClientCreatePayload, 16),
}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
f.mu.Lock()
w.Header().Set(wirecodec.CapsHeader, f.caps)
f.mu.Unlock()
if strings.HasSuffix(r.URL.Path, "/inbounds/catalog") || strings.HasSuffix(r.URL.Path, "/inbounds/list") {
f.mu.Lock()
f.hits["list"]++
type ent struct {
Id int `json:"id"`
Tag string `json:"tag"`
}
list := make([]ent, 0, len(f.tags))
for tag, id := range f.tags {
list = append(list, ent{Id: id, Tag: tag})
}
f.mu.Unlock()
b, _ := json.Marshal(list)
_, _ = w.Write([]byte(`{"success":true,"msg":"","obj":` + string(b) + `}`))
return
}
f.mu.Lock()
f.hits[r.URL.Path]++
hold := f.hold
pending := f.pendingClientAcks > 0 && strings.Contains(r.URL.Path, "/clients/")
if pending {
f.pendingClientAcks--
}
f.mu.Unlock()
if strings.HasSuffix(r.URL.Path, "/clients/add") {
var payload ClientCreatePayload
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
f.mu.Lock()
f.clientAdds = append(f.clientAdds, payload)
f.mu.Unlock()
select {
case f.clientAddEvents <- payload:
default:
}
}
if hold {
// Drain first: the server only notices a client disconnect once the
// body is consumed, and Close would otherwise wait on this forever.
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-r.Context().Done():
case <-f.release:
}
return
}
if pending {
_, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`))
return
}
_, _ = w.Write([]byte(`{"success":true,"msg":""}`))
}))
t.Cleanup(f.srv.Close)
// Registered after Close, so it runs first and frees any held handler.
t.Cleanup(func() { close(f.release) })
return f
}
func (f *fakeNodeHTTP) setHold(v bool) {
f.mu.Lock()
defer f.mu.Unlock()
f.hold = v
}
// hitCount is how many requests whose path contains pathPart reached the node.
func (f *fakeNodeHTTP) hitCount(pathPart string) int {
f.mu.Lock()
defer f.mu.Unlock()
n := 0
for path, c := range f.hits {
if strings.Contains(path, pathPart) {
n += c
}
}
return n
}
// realNodeInbound creates a Node row pointing at the fake server plus one
// inbound on it, with NO runtime override so RuntimeFor builds a real Remote.
func realNodeInbound(t *testing.T, f *fakeNodeHTTP, port int, clients []model.Client) *model.Inbound {
t.Helper()
hostPart, portStr, _ := strings.Cut(strings.TrimPrefix(f.srv.URL, "http://"), ":")
srvPort, err := strconv.Atoi(portStr)
if err != nil {
t.Fatalf("parse fake node port: %v", err)
}
node := &model.Node{
Name: fmt.Sprintf("%s-%d", t.Name(), port), Scheme: "http", Address: hostPart, Port: srvPort,
BasePath: "/", ApiToken: "tok", Enable: true, Status: "online",
AllowPrivateAddress: true, TlsVerifyMode: "verify",
}
if err := database.GetDB().Create(node).Error; err != nil {
t.Fatalf("create node: %v", err)
}
ib := nodeInbound(t, node.Id, port, clients)
f.mu.Lock()
f.tags[ib.Tag] = 100 + port%100
f.mu.Unlock()
return ib
}