Files
mirror-3x-ui/internal/web/service/client_node_push_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

278 lines
10 KiB
Go

package service
import (
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
// TestResetTrafficAcrossNodesPushesConcurrently covers the panel's per-client
// traffic reset, which propagated to nodes one round-trip after another.
func TestResetTrafficAcrossNodesPushesConcurrently(t *testing.T) {
setupBulkDB(t)
startSerializedWriter(t)
const nodes = inboundFanoutConcurrency + 1
const email = "reset@x"
bar := newApplyBarrier(inboundFanoutConcurrency)
seedClientAcrossNodes(t, bar, nodes, 46801, email, "88888888-1111-2222-3333-444444444444")
bar.arm()
if _, err := (&ClientService{}).ResetTrafficByEmail(&InboundService{}, email); err != nil {
t.Fatalf("ResetTrafficByEmail across %d node inbounds: %v", nodes, err)
}
if got := bar.maxPar.Load(); got != inboundFanoutConcurrency {
t.Fatalf("peak node pushes in flight = %d, want overlap at the %d cap (barrier timed out: %v)",
got, inboundFanoutConcurrency, bar.expired.Load())
}
}
// TestNodePushGivesUpBeforeTheRemoteTimeout pins that an edit gives up on a node
// that hangs on the push at the deadline, leaving it dirty for the reconcile.
func TestNodePushGivesUpBeforeTheRemoteTimeout(t *testing.T) {
setupBulkDB(t)
startSerializedWriter(t)
useTestRuntimeManager(t)
db := database.GetDB()
const uuid = "77777777-1111-2222-3333-444444444444"
f := newFakeNodeHTTP(t)
ib := realNodeInbound(t, f, 53100, []model.Client{{Email: "hung@x", ID: uuid, SubID: "sub-hung", Enable: true}})
rec := lookupClientRecord(t, "hung@x")
f.setHold(true)
start := time.Now()
if _, err := (&ClientService{}).Update(&InboundService{}, rec.Id, model.Client{
Email: "hung@x", ID: uuid, SubID: "sub-hung", Enable: true, Comment: "edited",
}, 0); err != nil {
t.Fatalf("Update against a hung node: %v", err)
}
elapsed := time.Since(start)
// Both bounds: no push at all would also finish fast and leave the node dirty.
if got := f.hitCount("/clients/update/"); got != 1 {
t.Fatalf("clients/update requests reaching the hung node = %d, want exactly 1", got)
}
if elapsed < nodeClientPushTimeout-200*time.Millisecond {
t.Fatalf("edit returned after %v, before the %v push deadline: the push was never awaited", elapsed, nodeClientPushTimeout)
}
if elapsed >= 2*nodeClientPushTimeout {
t.Fatalf("edit took %v against a hung node: it waited out the remote timeout instead of the %v push deadline", elapsed, nodeClientPushTimeout)
}
var node model.Node
if err := db.Where("id = ?", *ib.NodeID).First(&node).Error; err != nil {
t.Fatalf("read node: %v", err)
}
if !node.ConfigDirty {
t.Fatal("the node whose push timed out must stay dirty, or nothing ever converges it")
}
}
// TestBulkDeleteStopsPushingToAHungNode pins the batch circuit-break: once one
// push times out, the rest of the batch defers to the reconcile as well.
func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) {
setupClientNodeOrderDB(t)
useTestRuntimeManager(t)
f := newFakeNodeHTTP(t)
ib := realNodeInbound(t, f, 53200, []model.Client{
{Email: "b1@x", ID: "66666666-1111-2222-3333-444444444441", SubID: "sub-b1", Enable: true},
{Email: "b2@x", ID: "66666666-1111-2222-3333-444444444442", SubID: "sub-b2", Enable: true},
{Email: "b3@x", ID: "66666666-1111-2222-3333-444444444443", SubID: "sub-b3", Enable: true},
})
f.setHold(true)
start := time.Now()
if _, _, err := (&ClientService{}).BulkDelete(&InboundService{}, []string{"b1@x", "b2@x", "b3@x"}, false); err != nil {
t.Fatalf("BulkDelete against a hung node: %v", err)
}
elapsed := time.Since(start)
if got := f.hitCount("/clients/del/"); got != 1 {
t.Fatalf("clients/del requests sent to the hung node = %d, want 1: the batch kept paying a deadline per client", got)
}
if elapsed >= 2*nodeClientPushTimeout {
t.Fatalf("deleting 3 clients took %v against a hung node, want a single %v deadline, not one per client", elapsed, nodeClientPushTimeout)
}
if err := database.CloseDB(); err != nil {
t.Fatal(err)
}
if err := database.InitDB(filepath.Join(os.Getenv("XUI_DB_FOLDER"), "x-ui.db")); err != nil {
t.Fatal(err)
}
f.setHold(false)
var node model.Node
if err := database.GetDB().First(&node, *ib.NodeID).Error; err != nil {
t.Fatal(err)
}
if err := (&InboundService{}).ReconcileNode(t.Context(), runtime.NewRemote(&node, nil), &node); err != nil {
t.Fatal(err)
}
if got := f.hitCount("/clients/del/"); got != 4 {
t.Fatalf("delete requests including replay after reopening = %d, want 4 (one timed out, then all three retried)", got)
}
}
func TestClientBatchesContinueAfterDownstreamPendingAck(t *testing.T) {
tests := []struct {
name string
path string
run func(*testing.T, *ClientService, *InboundService, *model.Inbound, []string) error
}{
{"full delete", "/clients/del/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error {
_, _, err := svc.BulkDelete(inbounds, emails, false)
return err
}},
{"disable", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error {
_, _, err := svc.BulkSetEnable(inbounds, emails, false)
return err
}},
{"adjust", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error {
_, _, err := svc.BulkAdjust(inbounds, emails, 1, 0, "", nil, "")
return err
}},
{"detach", "/detach", func(t *testing.T, svc *ClientService, inbounds *InboundService, ib *model.Inbound, emails []string) error {
records := make([]*model.ClientRecord, 0, len(emails))
for _, email := range emails {
record := lookupClientRecord(t, email)
records = append(records, &record)
}
_, err := svc.delInboundClients(inbounds, ib.Id, records, true)
return err
}},
{"add", "/clients/add", func(t *testing.T, svc *ClientService, inbounds *InboundService, original *model.Inbound, _ []string) error {
target := *original
target.Settings = clientsSettings(t, makeNodeClients(3))
_, err := svc.AddInboundClient(inbounds, &target)
return err
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setupBulkDB(t)
startSerializedWriter(t)
useTestRuntimeManager(t)
fake := newFakeNodeHTTP(t)
fake.mu.Lock()
fake.pendingClientAcks = 1
fake.mu.Unlock()
const batchSize = 3
clients := makeNodeClients(batchSize)
emails := make([]string, 0, batchSize)
for i := range clients {
clients[i].Email = "seed-" + clients[i].Email
clients[i].SubID = clients[i].Email
clients[i].ExpiryTime = time.Now().Add(24 * time.Hour).UnixMilli()
emails = append(emails, clients[i].Email)
}
inbound := realNodeInbound(t, fake, 53300, clients)
for _, client := range clients {
mkTraffic(t, inbound.Id, client.Email, 0, 0, 0, client.ExpiryTime, true)
}
svc := (ClientService{}).TrackNodeApplies()
if err := tt.run(t, &svc, &InboundService{}, inbound, emails); err != nil {
t.Fatal(err)
}
if got := fake.hitCount(tt.path); got != batchSize {
t.Errorf("node received %d requests, want %d after acknowledging downstream pending", got, batchSize)
}
result := svc.NodeApplyResponse()
want := ClientNodeApplyOutcome{NodeID: *inbound.NodeID, Status: "pending", Reason: "downstream_pending"}
if result == nil || !result.NodePending || len(result.NodeResults) != 1 || result.NodeResults[0] != want {
t.Errorf("%s report = %+v, want one downstream pending outcome", tt.name, result)
}
})
}
}
func TestNodeClientCapacityPreservesPermanentDelete(t *testing.T) {
setupClientNodeOrderDB(t)
useTestRuntimeManager(t)
node := newFakeNodeHTTP(t)
const email = "durable-under-load@example.test"
target := realNodeInbound(t, node, 53400, []model.Client{{Email: email, ID: "a820e1e7-7bc8-4cc3-a5e4-cd8805271ea7", Enable: true}})
nodeID := *target.NodeID
inboundSvc := &InboundService{}
adds := make([]*model.Inbound, 0, inboundFanoutConcurrency+1)
for i := range inboundFanoutConcurrency + 1 {
ib := nodeInbound(t, nodeID, 53401+i, nil)
node.mu.Lock()
node.tags[ib.Tag] = 200 + i
node.mu.Unlock()
adds = append(adds, &model.Inbound{
Id: ib.Id, Protocol: ib.Protocol,
Settings: clientsSettings(t, []model.Client{{
Email: fmt.Sprintf("load-%d@example.test", i),
ID: fmt.Sprintf("66666666-1111-2222-3333-%012d", i+1), Enable: true,
}}),
})
}
node.setHold(true)
errs := make(chan error, inboundFanoutConcurrency)
var wg sync.WaitGroup
t.Cleanup(wg.Wait)
for _, add := range adds[:inboundFanoutConcurrency] {
wg.Go(func() {
_, err := (&ClientService{}).AddInboundClient(inboundSvc, add)
errs <- err
})
}
deadline := time.Now().Add(2 * time.Second)
for node.hitCount("/clients/add") < inboundFanoutConcurrency {
if time.Now().After(deadline) {
t.Fatal("parallel RPCs did not occupy all live slots")
}
time.Sleep(5 * time.Millisecond)
}
clientSvc := (ClientService{}).TrackNodeApplies()
if _, err := clientSvc.AddInboundClient(inboundSvc, adds[inboundFanoutConcurrency]); err != nil {
t.Fatal(err)
}
report := clientSvc.NodeApplyResponse()
if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "busy" ||
node.hitCount("/clients/add") != inboundFanoutConcurrency {
t.Fatalf("saturated delta must save without taking a live slot: %+v", report)
}
earlier := reserveNodeConfigTurn(nodeID, target.Id, nodeClientDelta)
defer earlier.release()
record := lookupClientRecord(t, email)
deleteSvc := (ClientService{}).TrackNodeApplies()
if _, err := deleteSvc.Delete(inboundSvc, record.Id, false); err != nil {
t.Fatal(err)
}
report = deleteSvc.NodeApplyResponse()
if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "timeout" ||
node.hitCount("/clients/del/") != 0 {
t.Fatalf("exclusive delete must defer when its queue wait expires: %+v", report)
}
earlier.release()
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
node.setHold(false)
var row model.Node
if err := database.GetDB().First(&row, nodeID).Error; err != nil {
t.Fatal(err)
}
if err := inboundSvc.ReconcileNode(t.Context(), runtime.NewRemote(&row, nil), &row); err != nil {
t.Fatal(err)
}
if got := node.hitCount("/clients/del/"); got != 1 {
t.Fatalf("reconcile sent %d permanent deletes after saturation, want one", got)
}
}