diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02477501a..54c7e2e04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -158,10 +158,10 @@ jobs: - name: PostgreSQL node client push ordering run: | set -o pipefail - go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush|Create(GroupsCompatibleInboundsOnOneRemote|SplitsFlowAndSendsResolvedInbounds|UsesEffectiveAllowedIPsOnRemote|DispatchesReadyLaneBeforeBlockedLane|CancellationStopsFurtherNodeWaves))$' -count=1 -v | tee /tmp/postgres-node-client-order.log + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush|Create(GroupsCompatibleInboundsOnOneRemote|SplitsFlowAndSendsResolvedInbounds|UsesEffectiveAllowedIPsOnRemote|DispatchesReadyLaneBeforeBlockedLane|CancellationStopsFurtherNodeWaves)|GroupedCreate(ReconcilesUnsentRebasedSettings|RecoversIndeterminateDelivery|RepairsDeferredTargets|DispatchesIndependentReadyPayload|OrdersLaterClientMutations|ReconcileBarrierDrainsAfterAcknowledgment|KeepsFifthNodeDurablyPendingWhenBudgetExpires|PreservesProtocolCredentials))$' -count=1 -v | tee /tmp/postgres-node-client-order.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) - if [ "$passed" -ne 13 ]; then - echo "expected 13 passing PostgreSQL node client ordering tests, got $passed" >&2 + if [ "$passed" -ne 21 ]; then + echo "expected 21 passing PostgreSQL node client ordering tests, got $passed" >&2 exit 1 fi diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index aec14b4c2..dcdbf55cf 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -3,6 +3,7 @@ package nodee2e import ( "bytes" "compress/gzip" + "context" "encoding/json" "fmt" "io" @@ -11,9 +12,14 @@ import ( "net/http/httputil" "net/url" "os" + "slices" "strconv" "sync/atomic" "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) func TestNodeSnapshotVersionCompatibility(t *testing.T) { @@ -155,9 +161,34 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { if got := clientAdds.Load(); got != 1 { t.Fatalf("node-sync received %d add requests, want one", got) } + var tags []string for _, port := range []int{inboundPort, secondaryPort} { if ib, ok := node.inboundOnPort(port); !ok || ib.client(email) == nil { t.Fatalf("node did not apply the grouped client on port %d", port) + } else { + tags = append(tags, ib.Tag) + } + } + admin := runtime.NewRemote(&model.Node{ + Name: "matrix-admin", Scheme: "http", Address: address.Hostname(), Port: port, + BasePath: "/", ApiToken: node.token, Enable: true, AllowPrivateAddress: true, + }, nil) + const adminEmail = "matrix-admin-create" + raw, err := json.Marshal(vlessClient(adminEmail)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + if _, ack, err := admin.AddClientGroup(ctx, tags, raw); err != nil || !slices.Equal(ack, []bool{true, true}) { + t.Fatalf("admin grouped add acknowledged %v, err=%v", ack, err) + } + if got := clientAdds.Load(); got != 2 { + t.Fatalf("admin sent %d add requests, want one", got-1) + } + for _, port := range []int{inboundPort, secondaryPort} { + if ib, ok := node.inboundOnPort(port); !ok || ib.client(adminEmail) == nil { + t.Fatalf("admin grouped client absent on port %d", port) } } } diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 3790076ff..7f9eab52f 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -823,7 +823,7 @@ func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model. if err != nil { return ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) } - return r.postClientAdd(ctx, []int{id}, client) + return remoteClientApplyResult(r.postClientAdd(ctx, []int{id}, client)) } // AddClientGroup returns the subset of tags acknowledged by one existing add RPC. @@ -857,17 +857,25 @@ func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json. if len(ids) == 0 { return ClientApplyResult{}, nil, unresolved } - result, err := r.postClientAdd(ctx, ids, client) + env, err := r.postClientAdd(ctx, ids, client) if err != nil { - return result, nil, errors.Join(err, unresolved) + return ClientApplyResult{}, nil, errors.Join(err, unresolved) } - return result, acknowledged, unresolved + var ack struct { + NodePending bool `json:"nodePending"` + } + // Legacy success replies omit obj or send null. + if len(env.Obj) != 0 { + if err := json.Unmarshal(env.Obj, &ack); err != nil { + return ClientApplyResult{}, nil, errors.Join(fmt.Errorf("decode grouped client add acknowledgment: %w", err), unresolved) + } + } + return ClientApplyResult{DownstreamPending: ack.NodePending}, acknowledged, unresolved } -func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (ClientApplyResult, error) { +func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (*envelope, error) { payload := map[string]any{"client": client, "inboundIds": ids} - env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) - return remoteClientApplyResult(env, err) + return r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) } func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { diff --git a/internal/web/service/client_create_dispatch.go b/internal/web/service/client_create_dispatch.go index 00a686005..47ec3db5c 100644 --- a/internal/web/service/client_create_dispatch.go +++ b/internal/web/service/client_create_dispatch.go @@ -3,6 +3,9 @@ package service import ( "context" "encoding/json" + "fmt" + "runtime/debug" + "sync" "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" @@ -11,15 +14,17 @@ import ( ) type queuedClientCreate struct { - turn *nodeConfigTurn - remote *runtime.Remote - tag string - client string - advance func() + turn *nodeConfigTurn + remote *runtime.Remote + tag string + client string + advance func() + queuedAt time.Time } func (q *queuedClientCreate) prepare(turn *nodeConfigTurn, remote *runtime.Remote, previous, inbound *model.Inbound, client string, prunedOrphans bool) { q.turn, q.remote, q.tag, q.client = turn, remote, inbound.Tag, client + q.queuedAt = time.Now() if !prunedOrphans { q.advance = remote.PreparePushedInboundAdvance(previous, inbound) } @@ -43,17 +48,19 @@ func (s *ClientService) pushClientCreates(parent context.Context, pushes []queue } applies := make([]inboundApply, 0, len(byNode)) + // Reserve one delivery slot per admitted node. Extra groups use spare capacity. + spare := make(chan struct{}, max(0, inboundFanoutConcurrency-len(byNode))) for _, nodeID := range nodeOrder { group := byNode[nodeID] applies = append(applies, inboundApply{id: group[0].turn.inboundID, nodeID: &nodeID, run: func() (bool, error) { - s.pushClientCreatesOnNode(ctx, group) + s.pushClientCreatesOnNode(ctx, spare, group) return false, nil }}) } return fanoutInboundApplies(applies) } -func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, pending []*queuedClientCreate) { +func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) { queue := pending[0].turn.queue nodeID := pending[0].turn.nodeID defer func() { @@ -61,6 +68,9 @@ func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, pending []* push.turn.release() } }() + var workers sync.WaitGroup + defer workers.Wait() + primary := make(chan struct{}, 1) for len(pending) > 0 { if err := ctx.Err(); err != nil { s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) @@ -98,15 +108,46 @@ func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, pending []* } // Release ready lanes before waiting for lanes behind a node-wide turn. for _, batch := range batches { - s.applyClientCreateBatch(ctx, nodeID, queue, batch) - for _, push := range batch { - push.turn.release() + slot := reserveClientCreateSlot(ctx, primary, spare) + if slot == nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, ctx.Err()) + return + } + run := func() { + defer func() { <-slot }() + defer func() { + for _, push := range batch { + push.turn.release() + } + }() + s.applyClientCreateBatch(ctx, nodeID, queue, batch) + } + if len(batches) == 1 && len(waiting) == 0 { + run() + } else { + workers.Go(run) } } pending = waiting } } +func reserveClientCreateSlot(ctx context.Context, primary, spare chan struct{}) chan struct{} { + select { + case primary <- struct{}{}: + return primary + default: + } + select { + case primary <- struct{}{}: + return primary + case spare <- struct{}{}: + return spare + case <-ctx.Done(): + return nil + } +} + func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, queue *nodeConfigQueue, batch []*queuedClientCreate) { if err := ctx.Err(); err != nil { s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) @@ -117,6 +158,16 @@ func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, return } defer queue.releaseLive() + defer func() { + if panicValue := recover(); panicValue != nil { + for _, push := range batch { + push.remote.ForgetPushedInbound(push.tag) + } + err := fmt.Errorf("panic applying grouped client create: %v", panicValue) + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Errorf("%v for node %d\n%s", err, nodeID, debug.Stack()) + } + }() tags := make([]string, len(batch)) for i, push := range batch { tags[i] = push.tag @@ -137,5 +188,6 @@ func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, push.advance() s.recordClientNodePush(nodeID, true, result, nil) } - logger.Debugf("client create node apply: node_id=%d inbounds=%d rpc_ms=%d", nodeID, len(tags), time.Since(started).Milliseconds()) + logger.Debugf("client create node apply: node_id=%d inbounds=%d queue_wait_ms=%d rpc_ms=%d", + nodeID, len(tags), started.Sub(batch[0].queuedAt).Milliseconds(), time.Since(started).Milliseconds()) } diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 94b92815a..940ca93e4 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -132,6 +132,7 @@ func TestCreateSplitsFlowAndSendsResolvedInbounds(t *testing.T) { fake.mu.Lock() pushes := slices.Clone(fake.clientAdds) fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) if len(pushes) != 2 || !slices.Equal(pushes[0].InboundIds, []int{121}) || !slices.Equal(pushes[1].InboundIds, []int{122}) || pushes[0].Client.Flow != "" || pushes[1].Client.Flow != flow { t.Fatalf("wrong delivery for mixed flow and missing tag: %+v", pushes) @@ -181,6 +182,7 @@ func TestCreateUsesEffectiveAllowedIPsOnRemote(t *testing.T) { fake.mu.Lock() pushes := slices.Clone(fake.clientAdds) fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) if len(pushes) != 2 { t.Fatalf("node received %d add requests, want 2 distinct tunnel payloads", len(pushes)) } diff --git a/internal/web/service/client_create_order_test.go b/internal/web/service/client_create_order_test.go new file mode 100644 index 000000000..ce7541068 --- /dev/null +++ b/internal/web/service/client_create_order_test.go @@ -0,0 +1,299 @@ +package service + +import ( + "context" + "net/http" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "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" +) + +func TestGroupedCreateOrdersLaterClientMutations(t *testing.T) { + for _, change := range []string{"update", "rename", "detach", "delete", "delete and reattach"} { + t.Run(change, func(t *testing.T) { + peer, node, ibs, _ := setupGroupedCreatePeer(t) + db := database.GetDB() + svc, inboundSvc := &ClientService{}, &InboundService{} + client := groupedRecoveryClient("ordered-group@x") + updateEmail := client.Email + if change == "rename" { + updateEmail = "renamed-group@x" + } + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + var requests atomic.Int32 + calls := make(chan string, 8) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + calls <- "add" + if requests.Add(1) == 1 { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + peer.mutate = func(w http.ResponseWriter, r *http.Request) { + calls <- r.URL.Path + _, _ = w.Write([]byte(`{"success":true}`)) + } + async := func(op func() (bool, error)) <-chan error { + done := make(chan error, 1) + workers.Go(func() { _, err := op(); done <- err }) + return done + } + created := async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id, ibs[1].Id}}) + }) + waitTrafficWriterSignal(t, blocked, "grouped create never reached the node") + original := lookupClientRecord(t, client.Email) + before := groupedDirtyGeneration(t, node.Id) + const callback = "test:observe-later-grouped-commit" + marked := make(chan struct{}, 8) + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "nodes" && strings.Contains(tx.Statement.SQL.String(), "config_dirty_at") { + marked <- struct{}{} + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + waitCommit := func(previous int64) int64 { + t.Helper() + deadline := time.After(2 * time.Second) + for { + select { + case <-marked: + case <-deadline: + t.Fatal("later local mutation did not advance the dirty generation") + } + if err := submitTrafficWrite(func() error { return nil }); err != nil { + t.Fatal(err) + } + if generation := groupedDirtyGeneration(t, node.Id); generation > previous { + return generation + } + } + } + mutated := async(func() (bool, error) { + switch change { + case "update", "rename": + next := client + next.Comment, next.Email = "committed later", updateEmail + return svc.UpdateByEmail(inboundSvc, client.Email, next, 0, ibs[0].Id) + case "detach": + return svc.DetachByEmail(inboundSvc, ibs[0].Id, client.Email) + default: + return svc.DeleteByEmail(inboundSvc, client.Email, false) + } + }) + after := waitCommit(before) + if strings.HasPrefix(change, "delete") { + for { + links, err := svc.GetInboundIdsForRecord(original.Id) + if err != nil { + t.Fatal(err) + } + if len(links) == 0 { + break + } + after = waitCommit(after) + } + } + deletes := func() int64 { + t.Helper() + var n int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, client.Email).Count(&n).Error; err != nil { + t.Fatal(err) + } + return n + } + var reattached <-chan error + if strings.HasPrefix(change, "delete") && deletes() != 1 { + t.Fatal("queued full delete has no durable outbox entry") + } + if change == "delete and reattach" { + reattached = async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id}}) + }) + waitCommit(after) + } + if err := (&NodeService{}).ClearNodeDirty(node.Id, before); err != nil { + t.Fatal(err) + } + groupedDirtyGeneration(t, node.Id) + if len(calls) != 1 { + t.Fatalf("later operation reached peer before grouped create acknowledgment (%d calls)", len(calls)) + } + free() + done := []<-chan error{created, mutated} + if reattached != nil { + done = append(done, reattached) + } + for i, settled := range done { + if err := waitTrafficWriterErr(t, settled); err != nil { + t.Fatalf("operation %d failed: %v", i+1, err) + } + } + var got []string + for len(calls) > 0 { + got = append(got, <-calls) + } + second := "/panel/api/clients/update/" + client.Email + switch change { + case "detach": + second = "/panel/api/clients/" + client.Email + "/detach" + case "delete": + second = "/panel/api/clients/del/" + client.Email + case "delete and reattach": + second = "add" + } + if !slices.Equal(got, []string{"add", second}) { + t.Fatalf("remote order = %v, want [add %s]", got, second) + } + if deletes() != 0 { + t.Fatal("completed or superseded delete was retained") + } + if reattached != nil { + rec := lookupClientRecord(t, client.Email) + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || !slices.Equal(links, []int{ibs[0].Id}) { + t.Fatalf("later attachment lost: %v, err=%v", links, err) + } + } + }) + } +} + +func TestGroupedCreateKeepsFifthNodeDurablyPendingWhenBudgetExpires(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const nodes = inboundFanoutConcurrency + 1 + var peers []*fakeNodeHTTP + var ids []int + var healthy *model.Inbound + for i := range nodes { + fake := newFakeNodeHTTP(t) + fake.setHold(i < inboundFanoutConcurrency) + peers = append(peers, fake) + healthy = realNodeInbound(t, fake, 46231+i, nil) + ids = append(ids, healthy.Id) + } + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + started := time.Now() + client := groupedRecoveryClient("fifth-destination@x") + if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: ids}); err != nil { + t.Fatal(err) + } + elapsed := time.Since(started) + if elapsed >= 2*nodeClientPushTimeout { + t.Fatalf("create took %v, want one delivery window", elapsed) + } + status := svc.NodeApplyResponse() + if status == nil || !status.NodePending || len(status.NodeResults) != nodes { + t.Fatalf("node outcomes = %+v, want %d pending", status, nodes) + } + for i, p := range peers { + want := 1 + if i == inboundFanoutConcurrency { + want = 0 + } + if got := p.hitCount("/clients/add"); got != want { + t.Fatalf("peer %d received %d adds, want %d with shared timeout", i, got, want) + } + if outcome := status.NodeResults[i]; outcome.Status != "pending" || outcome.Reason != "timeout" { + t.Fatalf("peer %d outcome = %+v, want timeout", i, outcome) + } + } + inboundID := *healthy.NodeID + groupedDirtyGeneration(t, inboundID) + if got := settingsClientEmails(t, healthy.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("healthy peer membership was dropped: %v", got) + } + var node model.Node + if err := database.GetDB().First(&node, inboundID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&inboundID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + if err := inboundSvc.ReconcileNode(ctx, rt.(*runtime.Remote), &node); err != nil { + t.Fatal(err) + } + if got := peers[nodes-1].hitCount("/inbounds/update/"); got != 1 { + t.Fatalf("healthy peer received %d recovery updates, want 1", got) + } + t.Logf("four slow deliveries used %v and the fifth peer converged on reconciliation", elapsed) +} + +func TestGroupedCreateReconcileBarrierDrainsAfterAcknowledgment(t *testing.T) { + peer, node, ibs, remote := setupGroupedCreatePeer(t) + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + created, reconciled := make(chan error, 1), make(chan error, 1) + inboundSvc := &InboundService{} + workers.Go(func() { + _, err := (&ClientService{}).Create(inboundSvc, &ClientCreatePayload{ + Client: groupedRecoveryClient("reconcile-barrier@x"), InboundIds: []int{ibs[0].Id, ibs[1].Id}, + }) + created <- err + }) + waitTrafficWriterSignal(t, blocked, "grouped add never reached peer") + workers.Go(func() { reconciled <- inboundSvc.ReconcileNode(t.Context(), remote, node) }) + deadline := time.Now().Add(2 * time.Second) + for { + nodeConfigDispatchMu.Lock() + q := nodeConfigDispatch[node.Id] + waiting := q != nil && q.reconciles == 1 + nodeConfigDispatchMu.Unlock() + if waiting { + break + } + select { + case err := <-reconciled: + t.Fatalf("reconcile overtook the blocked grouped create, err=%v", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("reconciliation never reached the node-wide barrier") + } + time.Sleep(time.Millisecond) + } + free() + for _, done := range []<-chan error{created, reconciled} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + assertGroupedRecovery(t, peer, node, remote, ibs, 1, nil) +} diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go new file mode 100644 index 000000000..65567d38e --- /dev/null +++ b/internal/web/service/client_create_reconcile_test.go @@ -0,0 +1,487 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "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" +) + +type groupedCreatePeer struct { + mu sync.Mutex + tags map[string]int + settings map[int]string + adds []ClientCreatePayload + updates []int + respond func(http.ResponseWriter, *http.Request, ClientCreatePayload, func(int)) + mutate func(http.ResponseWriter, *http.Request) +} + +func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + p.mu.Lock() + catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) + for tag, id := range p.tags { + catalog = append(catalog, runtime.RemoteInboundOption{Id: id, Tag: tag}) + } + p.mu.Unlock() + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": catalog}) + case strings.HasSuffix(r.URL.Path, "/clients/add"): + var payload ClientCreatePayload + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + p.mu.Lock() + p.adds = append(p.adds, payload) + p.mu.Unlock() + apply := func(count int) { + p.mu.Lock() + defer p.mu.Unlock() + for _, id := range payload.InboundIds[:count] { + var settings map[string]any + _ = json.Unmarshal([]byte(p.settings[id]), &settings) + clients, _ := settings["clients"].([]any) + if slices.ContainsFunc(clients, func(entry any) bool { + _, email := clientEntryEmail(entry) + return email == payload.Client.Email + }) { + continue + } + settings["clients"] = append(clients, payload.Client) + encoded, _ := json.Marshal(settings) + p.settings[id] = string(encoded) + } + } + if p.respond != nil { + p.respond(w, r, payload, apply) + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + case strings.Contains(r.URL.Path, "/inbounds/update/"): + _, suffix, _ := strings.Cut(r.URL.Path, "/inbounds/update/") + id, err := strconv.Atoi(suffix) + if err != nil || r.ParseForm() != nil || r.Form.Get("settings") == "" { + http.Error(w, "missing inbound ID or settings", http.StatusBadRequest) + return + } + p.mu.Lock() + p.settings[id] = r.Form.Get("settings") + p.updates = append(p.updates, id) + p.mu.Unlock() + _, _ = w.Write([]byte(`{"success":true}`)) + default: + if p.mutate == nil { + http.NotFound(w, r) + } else { + p.mutate(w, r) + } + } +} + +func TestGroupedCreateRecoversIndeterminateDelivery(t *testing.T) { + for _, tc := range []struct { + name string + reason string + reply func(w http.ResponseWriter, r *http.Request, apply func(int)) + }{ + {"partially applied HTTP error", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + http.Error(w, "second write failed", http.StatusInternalServerError) + }}, + {"lost acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + }}, + {"deadline after persistence", "timeout", func(_ http.ResponseWriter, r *http.Request, apply func(int)) { + apply(2) + <-r.Context().Done() + }}, + {"malformed acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":"unknown"}}`)) + }}, + {"downstream pending", "downstream_pending", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`)) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + peer.respond = func(w http.ResponseWriter, r *http.Request, _ ClientCreatePayload, apply func(int)) { + tc.reply(w, r, apply) + } + client := groupedRecoveryClient("unknown-delivery@x") + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + payload := &ClientCreatePayload{Client: client, InboundIds: []int{inbounds[0].Id, inbounds[1].Id}} + if _, err := svc.Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + wantGroupedOutcome(t, &svc, node.Id, "pending", tc.reason) + dirtyAt := groupedDirtyGeneration(t, node.Id) + if _, err := (&ClientService{}).Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + if got := groupedDirtyGeneration(t, node.Id); dirtyAt != got { + t.Fatalf("idempotent create changed generation from %d to %d", dirtyAt, got) + } + for _, inbound := range inbounds { + if got := settingsClientEmails(t, inbound.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("master inbound %d lost or duplicated commits: %v", inbound.Id, got) + } + } + want := []int{101, 102} + if tc.reason == "downstream_pending" { + want = nil + } + assertGroupedRecovery(t, peer, node, remote, inbounds, 1, want) + }) + } +} + +func TestGroupedCreateDispatchesIndependentReadyPayload(t *testing.T) { + peer, _, inbounds, _ := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + if err := database.GetDB().Model(first).Update("stream_settings", `{"network":"tcp","security":"reality"}`).Error; err != nil { + t.Fatal(err) + } + slow, healthy, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + t.Cleanup(free) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + if slices.Equal(payload.InboundIds, []int{101}) && payload.Client.Flow == "xtls-rprx-vision" { + close(slow) + select { + case <-release: + case <-r.Context().Done(): + return + } + } else if slices.Equal(payload.InboundIds, []int{102}) && payload.Client.Flow == "" { + close(healthy) + } else { + http.Error(w, "unexpected grouping", http.StatusBadRequest) + return + } + apply(1) + _, _ = w.Write([]byte(`{"success":true}`)) + } + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) + done := make(chan struct{}) + var createErr error + t.Cleanup(func() { cancel(); free(); <-done }) + go func() { + defer close(done) + client := groupedRecoveryClient("independent-flow@x") + client.Flow = "xtls-rprx-vision" + _, createErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: client, InboundIds: []int{first.Id, second.Id}, + }) + }() + for _, call := range []<-chan struct{}{slow, healthy} { + select { + case <-call: + case <-ctx.Done(): + t.Fatal("independent payload waited behind the parked RPC") + } + } + free() + <-done + if createErr != nil { + t.Fatal(createErr) + } +} + +func TestGroupedCreateRepairsDeferredTargets(t *testing.T) { + for _, scenario := range []string{"missing tag", "disabled client", "pruned orphan", "one rollback", "transport panic"} { + t.Run(scenario, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + db := database.GetDB() + wantAdds, status, reason, want := 1, "pending", "deferred", []int{101} + client := groupedRecoveryClient("recover-target@x") + switch scenario { + case "missing tag": + delete(peer.tags, first.Tag) + reason = "push_failed" + case "disabled client": + client.Enable = false + wantAdds, want = 0, []int{101, 102} + case "pruned orphan": + first.Settings = clientsSettings(t, []model.Client{groupedRecoveryClient("removed@x")}) + if err := db.Model(first).Update("settings", first.Settings).Error; err != nil { + t.Fatal(err) + } + remote.RecordAdoptedInbound(first) + peer.settings[101] = first.Settings + case "one rollback": + status, reason, want = "failed", "local_save_failed", nil + const callback = "test:grouped-create-local-rollback" + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + vars := tx.Statement.Vars + if tx.Statement.Table == "inbounds" && len(vars) == 2 && vars[1] == first.Id { + _ = tx.AddError(errors.New("forced create rollback")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + case "transport panic": + wantAdds, reason, want = 0, "push_failed", []int{101, 102} + failing := *node + failing.OutboundTag = "test-egress" + remote = runtime.NewRemote(&failing, panickingCreateEgress{}) + runtime.GetManager().SetRuntimeOverride(node.Id, remote) + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + } + } + svc := (&ClientService{}).TrackNodeApplies() + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}}) + if scenario == "one rollback" { + if err == nil || !strings.Contains(err.Error(), "forced create rollback") { + t.Fatalf("partial local failure = %v", err) + } + if _, ok := settingsClient(t, first.Id, client.Email); ok { + t.Fatal("rolled back inbound retained its client") + } + } else if err != nil { + t.Fatal(err) + } + if _, ok := settingsClient(t, second.Id, client.Email); !ok { + t.Fatal("successful inbound lost its committed client") + } + wantGroupedOutcome(t, &svc, node.Id, status, reason) + groupedDirtyGeneration(t, node.Id) + if scenario == "transport panic" { + nodeConfigDispatchMu.Lock() + leftover := nodeConfigDispatch[node.Id] + nodeConfigDispatchMu.Unlock() + if leftover != nil { + t.Fatal("recovered transport panic left a reserved node turn") + } + remote = runtime.NewRemote(node, nil) + } + peer.mu.Lock() + peer.tags[first.Tag] = 101 + peer.mu.Unlock() + assertGroupedRecovery(t, peer, node, remote, inbounds, wantAdds, want) + }) + } +} + +type panickingCreateEgress struct{} + +func (panickingCreateEgress) NodeEgressProxyURL(int) string { panic("fixture egress failure") } + +func TestGroupedCreatePreservesProtocolCredentials(t *testing.T) { + for _, tc := range []struct { + protocol model.Protocol + settings string + check func(model.Client) bool + }{ + {model.Shadowsocks, `{"clients":[],"method":"2022-blake3-aes-128-gcm"}`, func(c model.Client) bool { + return validShadowsocksClientKey("2022-blake3-aes-128-gcm", c.Password) + }}, + {model.MTProto, `{"clients":[],"fakeTlsDomain":"example.test"}`, func(c model.Client) bool { return c.Secret != "" }}, + {model.TUIC, `{"clients":[]}`, func(c model.Client) bool { return c.ID != "" && c.Password != "" }}, + } { + t.Run(string(tc.protocol), func(t *testing.T) { + peer, _, inbounds, remote := setupGroupedCreatePeer(t) + db := database.GetDB() + var ids []int + for _, ib := range inbounds { + if err := db.Model(ib).Updates(map[string]any{"protocol": tc.protocol, "settings": tc.settings}).Error; err != nil { + t.Fatal(err) + } + ids = append(ids, ib.Id) + } + first, second := inbounds[0], inbounds[1] + delete(peer.tags, first.Tag) + peer.tags["adopted-legacy-tag"] = 101 + remote.AdoptInboundAlias(first, runtime.RemoteInboundOption{Tag: "adopted-legacy-tag", Id: 101}) + delete(peer.tags, second.Tag) + peer.tags["n"+strconv.Itoa(*second.NodeID)+"-"+second.Tag] = 102 + + const email = "protocol-default-create" + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, Enable: true}, InboundIds: ids, + }); err != nil { + t.Fatal(err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || !tc.check(adds[0].Client) { + t.Fatalf("expected one acknowledged %s add with generated credentials and both mapped IDs", tc.protocol) + } + want := adds[0].Client + for _, ib := range inbounds { + local, ok := settingsClient(t, ib.Id, email) + if !ok || local.ID != want.ID || local.Secret != want.Secret || local.Password != want.Password { + t.Fatalf("grouped RPC changed the local %s credentials for inbound %d", tc.protocol, ib.Id) + } + } + }) + } +} + +func groupedRecoveryClient(email string) model.Client { + return model.Client{ + Email: email, Enable: true, ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: email, + } +} + +func wantGroupedOutcome(t *testing.T, svc *ClientService, nodeID int, status, reason string) { + t.Helper() + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: nodeID, Status: status, Reason: reason}} + if res == nil || res.NodePending != (status == "pending") || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } +} + +func groupedDirtyGeneration(t *testing.T, nodeID int) int64 { + t.Helper() + _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(nodeID) + if err != nil || !dirty || generation <= 0 { + t.Fatalf("node dirty=%t generation=%d err=%v", dirty, generation, err) + } + return generation +} + +func assertGroupedRecovery(t *testing.T, peer *groupedCreatePeer, node *model.Node, remote *runtime.Remote, inbounds []*model.Inbound, addCount int, wantUpdates []int) { + t.Helper() + svc := &InboundService{} + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + for range 2 { + if err := svc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + slices.Sort(peer.updates) + if len(peer.adds) != addCount || !slices.Equal(peer.updates, wantUpdates) { + t.Fatalf("add RPCs=%d, repaired IDs=%v, want %d and %v", len(peer.adds), peer.updates, addCount, wantUpdates) + } + for _, ib := range inbounds { + master := settingsClientEmails(t, ib.Id) + var doc struct{ Clients []model.Client } + if err := json.Unmarshal([]byte(peer.settings[peer.tags[ib.Tag]]), &doc); err != nil { + t.Fatal(err) + } + if got := emailsOf(doc.Clients); !slices.Equal(got, master) { + t.Fatalf("node inbound %q has %v, master has %v", ib.Tag, got, master) + } + } +} + +func setupGroupedCreatePeer(t *testing.T) (*groupedCreatePeer, *model.Node, []*model.Inbound, *runtime.Remote) { + t.Helper() + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}} + srv := httptest.NewServer(http.HandlerFunc(peer.serve)) + t.Cleanup(srv.Close) + nodeHTTP := &fakeNodeHTTP{srv: srv, tags: peer.tags} + first := realNodeInbound(t, nodeHTTP, 46201, nil) + second := nodeInbound(t, *first.NodeID, 46202, nil) + peer.tags[second.Tag] = 102 + var node model.Node + if err := database.GetDB().First(&node, *first.NodeID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&node.Id) + if err != nil { + t.Fatal(err) + } + remote, ok := rt.(*runtime.Remote) + if !ok { + t.Fatalf("runtime = %T, want actual remote", rt) + } + inbounds := []*model.Inbound{first, second} + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + peer.settings[peer.tags[inbound.Tag]] = inbound.Settings + } + return peer, &node, inbounds, remote +} + +func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + changed := inbounds[0] + client := model.Client{ + Email: "group-rebased@x", Enable: true, + ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased", + } + db := database.GetDB() + var reads atomic.Int32 + const callback = "test:concurrent-settings-before-grouped-write" + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + read, ok := tx.Statement.Dest.(*model.Inbound) + if ok && read.Id == changed.Id && reads.Add(1) == 3 { + _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id). + Update("settings", `{"clients":[],"decryption":"none"}`).Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + _, createErr := svc.Create(inboundSvc, &ClientCreatePayload{ + Client: client, InboundIds: []int{changed.Id, inbounds[1].Id}, + }) + if createErr != nil { + t.Fatal(createErr) + } + for _, inbound := range inbounds { + if c, ok := settingsClient(t, inbound.Id, client.Email); !ok || c.ID != client.ID { + t.Fatalf("master lost grouped client in inbound %d: %+v", inbound.Id, c) + } + } + stored, err := inboundSvc.GetInbound(changed.Id) + if err != nil || !strings.Contains(stored.Settings, `"decryption": "none"`) { + t.Fatalf("master lost concurrent settings change: %+v, %v", stored, err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + delivered := peer.settings[101] + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || adds[0].Client.Email != client.Email || + strings.Contains(delivered, "decryption") || !strings.Contains(delivered, client.Email) { + t.Fatalf("grouped add was not limited to the new client: %+v, peer settings %s", adds, delivered) + } + for range 2 { + if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + if !slices.Equal(peer.updates, []int{101}) || peer.settings[101] != stored.Settings { + t.Fatalf("reconcile updates=%v settings=%s, want exactly one repair of inbound 101", peer.updates, peer.settings[101]) + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 4e3bb8b44..b2be85424 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -1156,6 +1156,18 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b } if err := runSerializedTx(func(tx *gorm.DB) error { + // A later create can commit while this delete's node turn is waiting. + var attached []int + if err := tx.Table("client_inbounds"). + Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). + Where("clients.id = ? OR clients.email = ?", id, existing.Email). + Limit(1).Pluck("client_inbounds.client_id", &attached).Error; err != nil { + return err + } + if len(attached) != 0 { + return nil + } if existing.Email != "" { if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil { return err diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index d3a453efb..74e01da35 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -731,7 +731,10 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model } previous := *oldInbound previous.Settings = prevSettings - queued.prepare(mutation.turn, remote, &previous, oldInbound, string(raw), prunedOrphans) + pushed := *oldInbound + // The add RPC omits unrelated settings merged by the write transaction. + pushed.Settings = string(newSettings) + queued.prepare(mutation.turn, remote, &previous, &pushed, string(raw), prunedOrphans) mutation.turn = nil } return needRestart, nil