diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e9311d42..02477501a 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)$' -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))$' -count=1 -v | tee /tmp/postgres-node-client-order.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) - if [ "$passed" -ne 8 ]; then - echo "expected 8 passing PostgreSQL node client ordering tests, got $passed" >&2 + if [ "$passed" -ne 13 ]; then + echo "expected 13 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 6cf4f7388..aec14b4c2 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -39,7 +39,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged atomic.Int32 + var lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -88,6 +88,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": compact.Add(1) + case "/panel/api/clients/add": + clientAdds.Add(1) } proxy.ServeHTTP(w, req) })) @@ -101,10 +103,14 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { t.Fatal(err) } inboundPort := freePort(t) + secondaryPort := freePort(t) var source inboundView if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + if version.master == current { + node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) + } master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) @@ -136,6 +142,25 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { master.start() eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) }) } + if version.master == current { + first, hasFirst := master.inboundOnPort(inboundPort) + second, hasSecond := master.inboundOnPort(secondaryPort) + if !hasFirst || !hasSecond { + t.Fatal("master did not adopt both inbounds") + } + const email = "matrix-shared-create" + master.call(http.MethodPost, "/panel/api/clients/add", map[string]any{ + "client": map[string]any{"email": email, "enable": true}, "inboundIds": []int{first.Id, second.Id}, + }) + if got := clientAdds.Load(); got != 1 { + t.Fatalf("node-sync received %d add requests, want one", got) + } + 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) + } + } + } }) } } diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 1287fa777..b2b5c43d7 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -269,7 +269,7 @@ func (a *ClientController) create(c *gin.Context) { return } clientSvc := a.clientService.TrackNodeApplies() - needRestart, err := clientSvc.Create(&a.inboundService, &payload) + needRestart, err := clientSvc.CreateWithContext(c.Request.Context(), &a.inboundService, &payload) // Flagged before the error check: a partly-applied create leaves clients // committed on the inbounds that succeeded, and those still need the restart. if needRestart { diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index a54cb27d5..f2e13b453 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -2,12 +2,14 @@ package web import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "path/filepath" "reflect" + "slices" "strconv" "strings" "sync" @@ -235,6 +237,35 @@ func TestMasterNodeContract(t *testing.T) { t.Fatalf("node clients = %v, want c3 among them", got) } }}, + {"AddClientGroup attaches one client to two inbounds", []string{"AddClientGroup"}, func() error { + second := masterInbound("grouped", false) + second.Tag, second.Port = "in-51002-tcp", 51002 + if err := master.AddInbound(ctx, second); err != nil { + return err + } + client, err := json.Marshal(model.Client{ + Email: "grouped", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000004", SubID: "s-grouped", Enable: true, + }) + if err != nil { + return err + } + _, ack, err := master.AddClientGroup(ctx, []string{contractTag, second.Tag}, client) + if err == nil && !slices.Equal(ack, []bool{true, true}) { + return fmt.Errorf("acknowledged inbounds %v, want both", ack) + } + return err + }, func(t *testing.T) { + for _, tag := range []string{contractTag, "in-51002-tcp"} { + inbound, ok := nodeRow(t, tag) + if !ok { + t.Fatalf("node has no inbound %s", tag) + } + clients, err := (&service.InboundService{}).GetClients(inbound) + if err != nil || !slices.ContainsFunc(clients, func(c model.Client) bool { return c.Email == "grouped" }) { + t.Fatalf("node inbound %s received no grouped client, err=%v", tag, err) + } + } + }}, {"UpdateUser changes the client's limits", []string{"UpdateUser"}, func() error { _, err := master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, TotalGB: 5 << 30, @@ -421,14 +452,15 @@ func TestMasterNodeContract(t *testing.T) { // Remote methods that never reach the node, or that this table must not run. var remoteMethodsOutsideContract = map[string]string{ - "Name": "local label", - "RecordAdoptedInbound": "local fingerprint bookkeeping", - "AdoptInboundAlias": "local alias bookkeeping", - "AdoptedInboundAliases": "local alias bookkeeping", - "AdvancePushedInbound": "local fingerprint bookkeeping", - "ForgetPushedInbound": "local fingerprint bookkeeping", - "ForgetInbound": "local bookkeeping for an inbound the node no longer has", - "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", + "Name": "local label", + "RecordAdoptedInbound": "local fingerprint bookkeeping", + "AdoptInboundAlias": "local alias bookkeeping", + "AdoptedInboundAliases": "local alias bookkeeping", + "AdvancePushedInbound": "local fingerprint bookkeeping", + "PreparePushedInboundAdvance": "local fingerprint bookkeeping", + "ForgetPushedInbound": "local fingerprint bookkeeping", + "ForgetInbound": "local bookkeeping for an inbound the node no longer has", + "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", } // A Remote method with no cell is how activeInbounds and bulkResetTraffic diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 8448cabc1..3790076ff 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -473,19 +473,21 @@ func stripNodeInboundTagPrefix(nodeID int, tag string) string { // that lives on only one of the two panels: the node may carry the bare tag // while the central panel stores the prefixed form, or vice versa. func (r *Remote) cacheGetTag(tag string) (int, bool) { - if id, ok := r.cacheGet(tag); ok { + r.mu.RLock() + defer r.mu.RUnlock() + return r.cachedTagID(tag) +} + +func (r *Remote) cachedTagID(tag string) (int, bool) { + if id, ok := r.remoteIDByTag[tag]; ok { return id, true } prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - return r.cacheGet(stripped) + tag = stripped + } else { + tag = prefix + tag } - return r.cacheGet(prefix + tag) -} - -func (r *Remote) cacheGet(tag string) (int, bool) { - r.mu.RLock() - defer r.mu.RUnlock() id, ok := r.remoteIDByTag[tag] return id, ok } @@ -738,13 +740,21 @@ func (r *Remote) AdoptedInboundAliases() []string { // node held the exact pre-edit state; otherwise the stale fingerprint stays and // the next reconcile re-sends the full inbound. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) { + r.PreparePushedInboundAdvance(prevIb, ib)() +} + +// PreparePushedInboundAdvance keeps large settings blobs out of pending client batches. +func (r *Remote) PreparePushedInboundAdvance(prevIb, ib *model.Inbound) func() { + tag := ib.Tag prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id)) next := stampPushedInbound(ib, r.node.Id) - r.mu.Lock() - if r.pushedFP[ib.Tag].fingerprint == prevFP { - r.pushedFP[ib.Tag] = next + return func() { + r.mu.Lock() + defer r.mu.Unlock() + if r.pushedFP[tag].fingerprint == prevFP { + r.pushedFP[tag] = next + } } - r.mu.Unlock() } type pushedInboundClient struct { @@ -813,10 +823,49 @@ 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) } - payload := map[string]any{ - "client": client, - "inboundIds": []int{id}, + return r.postClientAdd(ctx, []int{id}, client) +} + +// AddClientGroup returns the subset of tags acknowledged by one existing add RPC. +func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json.RawMessage) (ClientApplyResult, []bool, error) { + var refreshErr error + for _, tag := range tags { + if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { + refreshErr = r.refreshRemoteIDs(ctx) + break + } } + ids := make([]int, 0, len(tags)) + acknowledged := make([]bool, len(tags)) + seen := make(map[int]struct{}, len(tags)) + var missing []error + r.mu.RLock() + for i, tag := range tags { + id, ok := r.cachedTagID(tag) + if !ok || id <= 0 { + missing = append(missing, fmt.Errorf("%w: tag %q on node %s", errRemoteInboundNotFound, tag, r.node.Name)) + continue + } + acknowledged[i] = true + if _, duplicate := seen[id]; !duplicate { + ids = append(ids, id) + seen[id] = struct{}{} + } + } + r.mu.RUnlock() + unresolved := errors.Join(refreshErr, errors.Join(missing...)) + if len(ids) == 0 { + return ClientApplyResult{}, nil, unresolved + } + result, err := r.postClientAdd(ctx, ids, client) + if err != nil { + return result, nil, errors.Join(err, unresolved) + } + return result, acknowledged, unresolved +} + +func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (ClientApplyResult, 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) } diff --git a/internal/web/service/client_create_dispatch.go b/internal/web/service/client_create_dispatch.go new file mode 100644 index 000000000..00a686005 --- /dev/null +++ b/internal/web/service/client_create_dispatch.go @@ -0,0 +1,141 @@ +package service + +import ( + "context" + "encoding/json" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type queuedClientCreate struct { + turn *nodeConfigTurn + remote *runtime.Remote + tag string + client string + advance func() +} + +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 + if !prunedOrphans { + q.advance = remote.PreparePushedInboundAdvance(previous, inbound) + } +} + +func (s *ClientService) pushClientCreates(parent context.Context, pushes []queuedClientCreate) (bool, error) { + ctx, cancel := context.WithTimeout(parent, nodeClientPushTimeout) + defer cancel() + byNode := make(map[int][]*queuedClientCreate) + var nodeOrder []int + for i := range pushes { + push := &pushes[i] + if push.turn == nil { + continue + } + nodeID := push.turn.nodeID + if len(byNode[nodeID]) == 0 { + nodeOrder = append(nodeOrder, nodeID) + } + byNode[nodeID] = append(byNode[nodeID], push) + } + + applies := make([]inboundApply, 0, 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) + return false, nil + }}) + } + return fanoutInboundApplies(applies) +} + +func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, pending []*queuedClientCreate) { + queue := pending[0].turn.queue + nodeID := pending[0].turn.nodeID + defer func() { + for _, push := range pending { + push.turn.release() + } + }() + for len(pending) > 0 { + if err := ctx.Err(); err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + return + } + changed := queue.changes() + type batchKey struct { + remote *runtime.Remote + client string + } + var batches [][]*queuedClientCreate + positions := make(map[batchKey]int) + var waiting []*queuedClientCreate + for _, push := range pending { + select { + case <-push.turn.ready: + key := batchKey{remote: push.remote, client: push.client} + i, found := positions[key] + if !found { + i = len(batches) + positions[key] = i + batches = append(batches, nil) + } + batches[i] = append(batches[i], push) + default: + waiting = append(waiting, push) + } + } + if len(batches) == 0 { + select { + case <-changed: + case <-ctx.Done(): + } + continue + } + // 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() + } + } + pending = waiting + } +} + +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) + return + } + if !queue.acquireLive() { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + defer queue.releaseLive() + tags := make([]string, len(batch)) + for i, push := range batch { + tags[i] = push.tag + } + remote := batch[0].remote + started := time.Now() + result, acknowledged, err := remote.AddClientGroup(ctx, tags, json.RawMessage(batch[0].client)) + if err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Warning("Error applying clients on", remote.Name(), ":", err) + } + for i, push := range batch { + if i >= len(acknowledged) || !acknowledged[i] || push.advance == nil { + remote.ForgetPushedInbound(push.tag) + s.recordClientNodePush(nodeID, i < len(acknowledged) && acknowledged[i] && result.DownstreamPending, result, nil) + continue + } + 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()) +} diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 4b8ada29c..94b92815a 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -56,6 +56,246 @@ func TestCreateAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { } } +func TestCreateGroupsCompatibleInboundsOnOneRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40301, nil) + ids := []int{first.Id} + remoteIDs := []int{101} + for i := 1; i < 11; i++ { + ib := nodeInbound(t, *first.NodeID, 40301+i, nil) + ids = append(ids, ib.Id) + remoteIDs = append(remoteIDs, 101+i) + fake.tags[ib.Tag] = 101 + i + } + + svc := (&ClientService{}).TrackNodeApplies() + const email = "grouped@x" + const uuid = "bbbbbbbb-1111-2222-3333-555555555555" + for range 2 { + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, ID: uuid, SubID: "sub-grouped", Enable: true}, InboundIds: ids, + }) + if err != nil { + t.Fatal(err) + } + } + + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + if len(pushes) != 1 { + t.Fatalf("client add RPCs = %d, want one for all 11 inbounds and none on retry", len(pushes)) + } + slices.Sort(pushes[0].InboundIds) + if !slices.Equal(pushes[0].InboundIds, remoteIDs) || pushes[0].Client.ID != uuid { + t.Fatalf("node received wrong IDs or credentials: %+v", pushes[0]) + } + rec := lookupClientRecord(t, email) + attached, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil { + t.Fatal(err) + } + slices.Sort(attached) + if !slices.Equal(attached, ids) { + t.Fatalf("local attachments = %v, want %v", attached, ids) + } + if r := svc.NodeApplyResponse(); r == nil || r.NodePending || !slices.Equal(r.NodeResults, []ClientNodeApplyOutcome{ + {NodeID: *first.NodeID, Status: "applied"}, + }) { + t.Fatalf("node outcome = %+v, want applied", r) + } +} + +func TestCreateSplitsFlowAndSendsResolvedInbounds(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + raw := realNodeInbound(t, fake, 40321, nil) + tls := nodeInbound(t, *raw.NodeID, 40322, nil) + missing := nodeInbound(t, *raw.NodeID, 40323, nil) + if err := database.GetDB().Model(tls).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil { + t.Fatal(err) + } + fake.tags[tls.Tag] = 122 + + svc := (&ClientService{}).TrackNodeApplies() + const flow = "xtls-rprx-vision" + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "split@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Flow: flow, Enable: true}, + InboundIds: []int{raw.Id, tls.Id, missing.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + 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) + } + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: *raw.NodeID, Status: "pending", Reason: "push_failed"}} + if res == nil || !res.NodePending || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } + _, _, dirty, _, err := (&NodeService{}).NodeSyncState(*raw.NodeID) + if err != nil || !dirty { + t.Fatalf("missing inbound must leave a durable reconcile: dirty=%t err=%v", dirty, err) + } +} + +func TestCreateUsesEffectiveAllowedIPsOnRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + wg := realNodeInbound(t, fake, 40331, nil) + awg := nodeInbound(t, *wg.NodeID, 40332, nil) + for _, inbound := range []struct { + id int + protocol model.Protocol + settings string + }{ + {id: wg.Id, protocol: model.WireGuard, settings: wgServerSettings()}, + {id: awg.Id, protocol: model.AmneziaWG, settings: amneziawgClientTestSettings}, + } { + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", inbound.id). + Updates(map[string]any{"protocol": inbound.protocol, "settings": inbound.settings}).Error; err != nil { + t.Fatal(err) + } + } + fake.tags[awg.Tag] = 132 + + _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{ + Email: "split-tunnel@x", Enable: true, + AllowedIPsByInbound: map[int][]string{wg.Id: {"10.0.0.9/32"}, awg.Id: {"10.8.1.9/32"}}, + }, + InboundIds: []int{wg.Id, awg.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + if len(pushes) != 2 { + t.Fatalf("node received %d add requests, want 2 distinct tunnel payloads", len(pushes)) + } + for i, addr := range []string{"10.0.0.9/32", "10.8.1.9/32"} { + push := pushes[i] + if !slices.Equal(push.InboundIds, []int{131 + i}) || !slices.Equal(push.Client.AllowedIPs, []string{addr}) || + len(push.Client.AllowedIPsByInbound) != 0 { + t.Fatalf("tunnel %d payload = %+v, want remote inbound %d and %s", i, push, 131+i, addr) + } + } +} + +func TestCreateDispatchesReadyLaneBeforeBlockedLane(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40341, nil) + second := nodeInbound(t, *first.NodeID, 40342, nil) + fake.tags[second.Tag] = 142 + predecessor := reserveNodeConfigTurn(*first.NodeID, first.Id, nodeClientDelta) + defer predecessor.release() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "ordered-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: []int{first.Id, second.Id}, + }) + }() + t.Cleanup(func() { + cancel() + <-done + }) + wantRPC := func(remoteID int) { + t.Helper() + select { + case got := <-fake.clientAddEvents: + if !slices.Equal(got.InboundIds, []int{remoteID}) { + t.Fatalf("node received inbound IDs %v, want [%d]", got.InboundIds, remoteID) + } + case <-time.After(5 * time.Second): + t.Fatalf("ready inbound %d was not dispatched", remoteID) + } + } + wantRPC(142) + predecessor.release() + wantRPC(141) + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(5 * time.Second): + t.Fatal("create waited after both requests were delivered") + } +} + +func TestCreateCancellationStopsFurtherNodeWaves(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + const nodeCount = inboundFanoutConcurrency + 1 + fakes := make([]*fakeNodeHTTP, nodeCount) + var ids []int + for i := range nodeCount { + fakes[i] = newFakeNodeHTTP(t) + fakes[i].setHold(true) + ids = append(ids, realNodeInbound(t, fakes[i], 40351+i, nil).Id) + } + + svc := (&ClientService{}).TrackNodeApplies() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "cancel-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: ids, + }) + }() + t.Cleanup(func() { cancel(); <-done }) + deadline := time.After(5 * time.Second) + for _, fake := range fakes[:inboundFanoutConcurrency] { + select { + case <-fake.clientAddEvents: + case <-deadline: + t.Fatal("the first wave did not reach every admitted node") + } + } + cancel() + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(3 * time.Second): + t.Fatal("cancelled pushes held up the create") + } + if got := fakes[nodeCount-1].hitCount("/clients/add"); got != 0 { + t.Fatalf("queued node received %d RPCs after request cancellation", got) + } + rec := lookupClientRecord(t, "cancel-add@x") + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || len(links) != nodeCount { + t.Fatalf("cancellation lost a committed membership: %v, err=%v", links, err) + } + if res := svc.NodeApplyResponse(); res == nil || !res.NodePending || len(res.NodeResults) != nodeCount { + t.Fatalf("node outcome = %+v, want all %d pending", res, nodeCount) + } +} + func TestAttachAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { setupBulkDB(t) svc := &ClientService{} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 687f45f01..4e3bb8b44 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -1,6 +1,7 @@ package service import ( + "context" "encoding/base64" "encoding/json" "errors" @@ -203,6 +204,11 @@ func quotaDisabledEmails(tx *gorm.DB, within []string) ([]string, error) { // Create applies the client to every requested inbound: one failing inbound no // longer aborts the others, so the error can name several and needRestart holds. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { + return s.CreateWithContext(context.Background(), inboundSvc, payload) +} + +// CreateWithContext applies the request context to delivery after the local commits. +func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { if payload == nil { return false, common.NewError("empty payload") } @@ -317,7 +323,11 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate } adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } - needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds) + pushes := make([]queuedClientCreate, len(adds)) + needRestart, saveErr := s.fanoutInboundClientAdds(inboundSvc, adds, pushes) + remoteRestart, pushErr := s.pushClientCreates(ctx, pushes) + needRestart = needRestart || remoteRestart + fanoutErr := errors.Join(saveErr, pushErr) if fanoutErr != nil { // Never on a failed create: this retrims the devices of an email that // already existed, and a create the panel reported as failed must not. @@ -384,12 +394,15 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { return needRestart.Load(), errors.Join(errs...) } -// fanoutInboundClientAdds applies one payload per inbound. -func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { +func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound, pushes []queuedClientCreate) (bool, error) { applies := make([]inboundApply, 0, len(adds)) - for _, add := range adds { + for i, add := range adds { + var queued *queuedClientCreate + if pushes != nil { + queued = &pushes[i] + } applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { - return s.AddInboundClient(inboundSvc, add) + return s.addInboundClient(inboundSvc, add, queued) }}) } return fanoutInboundApplies(applies) @@ -1319,7 +1332,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] } adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } - return s.fanoutInboundClientAdds(inboundSvc, adds) + return s.fanoutInboundClientAdds(inboundSvc, adds, nil) } func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) { diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index ca0746a39..d3a453efb 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -397,6 +397,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c } func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { + return s.addInboundClient(inboundSvc, data, nil) +} + +func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, queued *queuedClientCreate) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -712,6 +716,26 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } else if push && len(clients) <= nodeBulkPushThreshold { + if remote, ok := rt.(*runtime.Remote); ok && queued != nil && len(clients) == 1 { + if mutation.turn == nil || !clients[0].Enable { + s.recordClientNodeDeferred(oldInbound.NodeID) + } else { + mutation.unlock() + client := clients[0] + // Create already selected the effective addresses for this inbound. + client.AllowedIPsByInbound = nil + raw, err := json.Marshal(client) + if err != nil { + s.recordClientNodePush(*oldInbound.NodeID, true, runtime.ClientApplyResult{}, err) + return needRestart, nil + } + previous := *oldInbound + previous.Settings = prevSettings + queued.prepare(mutation.turn, remote, &previous, oldInbound, string(raw), prunedOrphans) + mutation.turn = nil + } + return needRestart, nil + } mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, client := range clients { // Older nodes coerce enable=true. Reconcile the rest of this batch. diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go index fc3aae0aa..244f7a64c 100644 --- a/internal/web/service/client_node_dispatch.go +++ b/internal/web/service/client_node_dispatch.go @@ -22,6 +22,7 @@ type nodeConfigQueue struct { groups list.List reconciles int live int + changed chan struct{} } // Inbounds in the same group can push concurrently. A node-wide operation @@ -109,6 +110,10 @@ func (t *nodeConfigTurn) release() { return } q, group := t.queue, t.group + if q.changed != nil { + close(q.changed) + q.changed = nil + } lane := group.inbounds[t.inboundID] wasReady := q.groups.Front() == group.position && lane.Front() == t.position lane.Remove(t.position) @@ -136,6 +141,31 @@ func (t *nodeConfigTurn) release() { } } +func (q *nodeConfigQueue) changes() <-chan struct{} { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.changed == nil { + q.changed = make(chan struct{}) + } + return q.changed +} + +func (q *nodeConfigQueue) acquireLive() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.live >= inboundFanoutConcurrency { + return false + } + q.live++ + return true +} + +func (q *nodeConfigQueue) releaseLive() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q.live-- +} + type inboundClientMutation struct { lock *inboundMutationLock turn *nodeConfigTurn @@ -211,19 +241,11 @@ func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbou return } // Conflicting turns wait without consuming a live slot. - nodeConfigDispatchMu.Lock() - if m.turn.queue.live >= inboundFanoutConcurrency { - nodeConfigDispatchMu.Unlock() + if !m.turn.queue.acquireLive() { s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) return } - m.turn.queue.live++ - nodeConfigDispatchMu.Unlock() - defer func() { - nodeConfigDispatchMu.Lock() - m.turn.queue.live-- - nodeConfigDispatchMu.Unlock() - }() + defer m.turn.queue.releaseLive() ctx, cancel := nodePushContext() defer cancel() complete := false diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index b5ce92530..aaf21b930 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -25,6 +25,8 @@ type fakeNodeHTTP struct { hits map[string]int caps string pendingClientAcks int + clientAdds []ClientCreatePayload + clientAddEvents chan ClientCreatePayload // hold makes every non-list request block until the master gives up. hold bool release chan struct{} @@ -32,7 +34,10 @@ type fakeNodeHTTP struct { func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { t.Helper() - f := &fakeNodeHTTP{tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{})} + 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() @@ -62,6 +67,20 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { 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.