diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e9311d42..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)$' -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 8 ]; then - echo "expected 8 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 6cf4f7388..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) { @@ -39,7 +45,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 +94,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 +109,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 +148,50 @@ 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) + } + 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/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..7f9eab52f 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,12 +823,59 @@ 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 remoteClientApplyResult(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 + } } - env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) - return remoteClientApplyResult(env, err) + 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 + } + env, err := r.postClientAdd(ctx, ids, client) + if err != nil { + return ClientApplyResult{}, nil, errors.Join(err, 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) (*envelope, error) { + payload := map[string]any{"client": client, "inboundIds": ids} + 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 new file mode 100644 index 000000000..47ec3db5c --- /dev/null +++ b/internal/web/service/client_create_dispatch.go @@ -0,0 +1,193 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "runtime/debug" + "sync" + "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() + 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) + } +} + +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)) + // 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, spare, group) + return false, nil + }}) + } + return fanoutInboundApplies(applies) +} + +func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) { + queue := pending[0].turn.queue + nodeID := pending[0].turn.nodeID + defer func() { + for _, push := range 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) + 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 { + 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) + return + } + if !queue.acquireLive() { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + 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 + } + 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 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 4b8ada29c..940ca93e4 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -56,6 +56,248 @@ 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() + 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) + } + 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() + 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)) + } + 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_create_order_test.go b/internal/web/service/client_create_order_test.go new file mode 100644 index 000000000..7e6cfb191 --- /dev/null +++ b/internal/web/service/client_create_order_test.go @@ -0,0 +1,308 @@ +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 change == "update" || change == "rename" { + for { + stored, ok := settingsClient(t, ibs[0].Id, updateEmail) + if ok && stored.Comment == "committed later" { + break + } + after = waitCommit(after) + } + } + 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 687f45f01..e35b4b6fb 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,21 +323,19 @@ 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) - 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. - return needRestart, fanoutErr - } - // nil means omitted and preserves the stored binding. - if client.ClientHostRuleIds != nil { - if err := database.GetDB().Model(&model.ClientRecord{}). + pushes := make([]queuedClientCreate, len(adds)) + needRestart, saveErr := s.fanoutInboundClientAdds(inboundSvc, adds, pushes) + // Finish create metadata before remote delivery can overlap a later rename. + if saveErr == nil && client.ClientHostRuleIds != nil { + saveErr = database.GetDB().Model(&model.ClientRecord{}). Where("email = ?", client.Email). - Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error; err != nil { - return needRestart, err - } + Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error } - return needRestart, s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + if saveErr == nil { + saveErr = s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + } + remoteRestart, pushErr := s.pushClientCreates(ctx, pushes) + return needRestart || remoteRestart, errors.Join(saveErr, pushErr) } // inboundFanoutConcurrency caps how many inbounds one client op applies at @@ -384,12 +388,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) @@ -1143,6 +1150,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 @@ -1319,7 +1338,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..74e01da35 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,29 @@ 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 + 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 + } 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.