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

200 lines
6.3 KiB
Go

package controller
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func TestClientUpdateReportsTimedOutOnlineNodeAndKeepsLocalSave(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db"))
service.StartTrafficWriter()
t.Cleanup(service.StopTrafficWriter)
runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}}))
t.Cleanup(func() { runtime.SetManager(nil) })
const email = "partial-node@example.test"
db := database.GetDB()
var nodes []model.Node
var inbounds []model.Inbound
const (
timeout = iota
downstream
recovered
)
var slowMode atomic.Int32
slowStarted := make(chan struct{}, 1)
healthyApplied := make(chan struct{}, 1)
for index, slow := range []bool{false, true} {
tag := fmt.Sprintf("in-%d", 15110+index)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
fmt.Fprintf(w, "{\"success\":true,\"obj\":[{\"id\":1,\"tag\":%q}]}", tag)
} else if strings.Contains(r.URL.Path, "/clients/update/") {
if slow {
switch slowMode.Load() {
case timeout:
_, _ = io.Copy(io.Discard, r.Body)
slowStarted <- struct{}{}
<-r.Context().Done()
return
case downstream:
fmt.Fprint(w, "{\"success\":true,\"obj\":{\"nodePending\":true}}")
return
}
} else {
select {
case healthyApplied <- struct{}{}:
default:
}
}
fmt.Fprint(w, "{\"success\":true}")
} else {
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
parsed, err := url.Parse(srv.URL)
if err != nil {
t.Fatal(err)
}
port, err := strconv.Atoi(parsed.Port())
if err != nil {
t.Fatal(err)
}
node := model.Node{
Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port,
Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify",
AllowPrivateAddress: true, Enable: true, Status: "online",
}
if err := db.Create(&node).Error; err != nil {
t.Fatal(err)
}
inbound := model.Inbound{
UserId: 1, Enable: true, Tag: tag, Port: 15110 + index,
Protocol: model.VLESS, Settings: "{\"clients\":[],\"decryption\":\"none\"}", StreamSettings: "{\"network\":\"tcp\",\"security\":\"none\"}",
}
if err := db.Create(&inbound).Error; err != nil {
t.Fatal(err)
}
nodes = append(nodes, node)
inbounds = append(inbounds, inbound)
}
clientSvc, inboundSvc := &service.ClientService{}, &service.InboundService{}
if _, err := clientSvc.Create(inboundSvc, &service.ClientCreatePayload{
Client: model.Client{Email: email, ID: "11111111-2222-4333-8444-555555555555", Enable: true},
InboundIds: []int{inbounds[0].Id, inbounds[1].Id},
}); err != nil {
t.Fatal(err)
}
for i, inbound := range inbounds {
if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Update("node_id", nodes[i].Id).Error; err != nil {
t.Fatal(err)
}
}
gin.SetMode(gin.TestMode)
router := gin.New()
NewClientController(router.Group("/panel/api/clients"))
type applyEnvelope struct {
Success bool
Obj service.ClientNodeApplyResponse
}
request := func(comment string) *httptest.ResponseRecorder {
body := fmt.Sprintf("{\"comment\":%q}", comment)
req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/update/"+email, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
return response
}
decode := func(response *httptest.ResponseRecorder) applyEnvelope {
t.Helper()
var msg applyEnvelope
if err := json.Unmarshal(response.Body.Bytes(), &msg); err != nil {
t.Fatal(err)
}
if !msg.Success || len(msg.Obj.NodeResults) != 2 {
t.Fatalf("expected local success and both node results, got %s", response.Body.String())
}
return msg
}
started := time.Now()
done := make(chan *httptest.ResponseRecorder, 1)
finished := make(chan struct{})
go func() {
defer close(finished)
done <- request("saved locally")
}()
t.Cleanup(func() { <-finished })
wait := func(ch <-chan struct{}) {
t.Helper()
select {
case <-ch:
case <-time.After(3 * time.Second):
t.Fatal("expected RPC did not start before the slow node's deadline")
}
}
wait(slowStarted)
wait(healthyApplied)
writerStarted := time.Now()
if _, _, err := inboundSvc.AddTraffic(nil, nil); err != nil {
t.Fatal(err)
}
t.Logf("fixture writer barrier while RPC in flight: %s", time.Since(writerStarted))
select {
case <-done:
t.Fatal("unrelated writer work was held behind the slow RPC")
default:
}
msg := decode(<-done)
t.Logf("fixture timed-out request: %s", time.Since(started))
if got := msg.Obj.NodeResults[0]; got.NodeID != nodes[0].Id || got.Status != "applied" {
t.Fatalf("healthy node outcome: %+v", got)
}
if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.NodeID != nodes[1].Id || got.Status != "pending" || got.Reason != "timeout" {
t.Fatalf("slow node outcome: %+v", got)
}
if stored, err := clientSvc.GetRecordByEmail(nil, email); err != nil || stored.Comment != "saved locally" {
t.Fatalf("local edit not persisted: record=%+v error=%v", stored, err)
}
if err := db.First(&nodes[1], nodes[1].Id).Error; err != nil {
t.Fatal(err)
}
if !nodes[1].ConfigDirty || nodes[1].Status != "online" {
t.Fatalf("timed-out online node lost its durable reconcile flag: %+v", nodes[1])
}
slowMode.Store(downstream)
msg = decode(request("downstream pending"))
if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.Status != "pending" || got.Reason != "downstream_pending" {
t.Fatalf("forwarded pending result was lost: %+v", msg.Obj)
}
slowMode.Store(recovered)
started = time.Now()
msg = decode(request("both acknowledged"))
t.Logf("fixture healthy request: %s", time.Since(started))
if got := msg.Obj.NodeResults[1]; msg.Obj.NodePending || got.Status != "applied" || got.Reason != "" {
t.Fatalf("recovered node outcome: %+v", msg.Obj)
}
}