Files
mirror-3x-ui/internal/web/service/node_http_fake_test.go
T
Hamed 0db9503228 fix(nodes): isolate traffic sync and report client apply outcomes (#7308)
Isolate traffic synchronization with bounded round-robin per-node workers, independent maintenance and publication, cancellation and ordered shutdown drain. Recheck online eligibility inside the serialized writer before merging snapshots and retain the latest valid speed sample per node, with expiry and explicit empty publication.

Report direct per-node applied/pending/failed outcomes without changing local-save success semantics. Propagate downstream pending separately from direct ACKs so acknowledged batch items do not abort subsequent work. Integrate live admission into the existing #7314 ordered dispatcher with separate four-second queue and batch budgets, retaining monotonic dirty generations, exclusive full-delete/reconcile turns, durable deletion outbox, generation-matched settlement, cross-node recreation safeguards and targeted fingerprint invalidation. Preserve legacy peer compatibility and update generated API documentation.

Validation: all 12 CI jobs and Docs CI passed on reviewed head d13850474f (runs 46871519847 and 46871519831). PostgreSQL logs confirm eight ordering regressions, including saturation, lost ACK, cross-node recreation and bulk recovery. Author reports make verify, focused SQLite/PostgreSQL race tests, four mixed-version node E2E pairings and Xray E2E. No independent production-scale latency measurement or universal HTTP timeout guarantee.

Residual follow-ups: possible conservative false-pending result when a final full delete settles an intermediate superseded intent on the same node; add per-logical-operation settlement regression. Verify shutdown drain under a blocked writer/maintenance worker. These static-review concerns remain open for follow-up, not demonstrated data loss or a new deadlock.

Refs #7293
2026-12-02 16:47:26 +03:30

129 lines
3.6 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
// hold makes every non-list request 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{})}
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/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 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
}