package service import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "strings" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "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/testpg" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" "github.com/mhsanaei/3x-ui/v3/internal/xray" ) type blockedClientPushRuntime struct { fakeNodeRuntime calls chan string release <-chan struct{} blockedEmail string waitForTimeout bool expired atomic.Bool } func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "add " + client.Email if client.Email != r.blockedEmail { return runtime.ClientApplyResult{}, nil } if r.waitForTimeout { if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { return runtime.ClientApplyResult{}, errors.New("push timeout was not enforced") } // Give the node a shorter deadline so this case exercises RPC ordering // and the queue-expiry regression can test the separate wait budget. call, cancel := context.WithTimeout(ctx, nodeClientPushTimeout/2) defer cancel() <-call.Done() r.expired.Store(errors.Is(call.Err(), context.DeadlineExceeded)) return runtime.ClientApplyResult{}, call.Err() } select { case <-r.release: return runtime.ClientApplyResult{}, nil case <-ctx.Done(): return runtime.ClientApplyResult{}, ctx.Err() } } func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "update " + email + " " + client.Comment return runtime.ClientApplyResult{}, nil } func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) (runtime.ClientApplyResult, error) { r.calls <- "detach " + email return runtime.ClientApplyResult{}, nil } func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { r.calls <- "lifecycle " + inbound.Tag return nil } func setupClientNodeOrderDB(t *testing.T) { t.Helper() cleanup, err := testpg.IsolatePackage("client_node_order") if err != nil { t.Fatal(err) } t.Cleanup(cleanup) setupBulkDB(t) startSerializedWriter(t) } func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) { for _, tc := range []struct { name string timeout bool }{ {name: "successful push"}, {name: "ambiguous timeout", timeout: true}, } { t.Run(tc.name, func(t *testing.T) { setupClientNodeOrderDB(t) nodeID, _ := setupNodeRuntime(t) release := make(chan struct{}) unblock := sync.OnceFunc(func() { close(release) }) const email = "ordered@example.test" blocked := &blockedClientPushRuntime{ calls: make(chan string, 8), release: release, blockedEmail: email, waitForTimeout: tc.timeout, } mgr := runtime.GetManager() mgr.SetRuntimeOverride(nodeID, blocked) ib := nodeInbound(t, nodeID, 46001, nil) siblingInbound := nodeInbound(t, nodeID, 46003, nil) controlNode := model.Node{Name: "control", Address: "127.0.0.1", Port: 2097, ApiToken: "token", Enable: true, Status: "online"} if err := database.GetDB().Create(&controlNode).Error; err != nil { t.Fatal(err) } control := &fakeNodeRuntime{} mgr.SetRuntimeOverride(controlNode.Id, control) other := nodeInbound(t, controlNode.Id, 46002, nil) clientSvc, inboundSvc := &ClientService{}, &InboundService{} client := model.Client{Email: email, ID: uuid.NewString(), Enable: true} changed := client changed.Comment = "committed update" sibling := model.Client{Email: "control@example.test", ID: uuid.NewString(), Enable: true} sameNode := model.Client{Email: "same-node@example.test", ID: uuid.NewString(), Enable: true} data := func(inbound *model.Inbound, client model.Client) *model.Inbound { return &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client})} } addData, updateData, controlData := data(ib, client), data(ib, changed), data(other, sibling) siblingData := data(siblingInbound, sameNode) var wg sync.WaitGroup t.Cleanup(func() { unblock() wg.Wait() }) async := func(operation func() (bool, error)) <-chan error { done := make(chan error, 1) wg.Go(func() { restart, err := operation() if restart { err = errors.Join(err, errors.New("requested a local restart for a remote mutation")) } done <- err }) return done } expectCall := func(want string) { t.Helper() select { case got := <-blocked.calls: if got != want { t.Fatalf("node operation = %q, want %q", got, want) } case <-time.After(nodeClientPushTimeout + time.Second): t.Fatalf("node never received %q", want) } } waitSettings := func(id int, contains string, present bool) { t.Helper() start := time.Now() for { current, err := inboundSvc.GetInbound(id) if err == nil && strings.Contains(current.Settings, contains) == present { t.Logf("local commit observed after %s while first RPC was blocked", time.Since(start)) return } if time.Since(start) >= time.Second { t.Fatalf("local settings did not reach %q present=%t while first RPC was blocked (last read err=%v)", contains, present, err) } time.Sleep(5 * time.Millisecond) } } add := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, addData) }) expectCall("add " + client.Email) start := time.Now() locked := make(chan time.Duration, 1) wg.Go(func() { start := time.Now() lockInbound(ib.Id).Unlock() locked <- time.Since(start) }) select { case took := <-locked: t.Logf("inbound mutation lock acquired in %s while first RPC was blocked", took) case <-time.After(time.Second): t.Fatal("first RPC still holds the inbound mutation lock") } writerStart := time.Now() if err := runSerializedTx(func(*gorm.DB) error { return nil }); err != nil { t.Fatal(err) } t.Logf("independent writer turn took %s while first RPC was blocked", time.Since(writerStart)) update := async(func() (bool, error) { return clientSvc.UpdateInboundClient(inboundSvc, updateData, client.Email) }) waitSettings(ib.Id, changed.Comment, true) detach := async(func() (bool, error) { return clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, client.Email, true, false) }) waitSettings(ib.Id, client.Email, false) sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) }) waitSettings(siblingInbound.Id, sameNode.Email, true) expectCall("add " + sameNode.Email) if err := waitTrafficWriterErr(t, sameNodeDone); err != nil { t.Fatal(err) } controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) }) select { case err := <-controlDone: if err != nil || control.addClient.Load() != 1 { t.Fatalf("control inbound did not complete independently: %v (pushes=%d)", err, control.addClient.Load()) } case <-time.After(time.Second): t.Fatal("control inbound waited for unrelated node") } select { case got := <-blocked.calls: t.Fatalf("%q overtook the first RPC", got) default: } unblock() expectCall("update " + client.Email + " " + changed.Comment) t.Logf("first RPC held its dispatch turn for %s", time.Since(start)) if tc.timeout && !blocked.expired.Load() { t.Fatal("the first push did not finish through its deadline") } expectCall("detach " + client.Email) for i, done := range []<-chan error{add, update, detach} { select { case err := <-done: if err != nil { t.Fatal(fmt.Errorf("operation %d reported %w after commit", i, err)) } case <-time.After(time.Second): t.Fatalf("operation %d did not complete", i) } } if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { t.Fatalf("node dirty=%t error=%v after committed client batch", dirty, err) } }) } } func TestNodeClientQueueTimeoutDefersCommittedDelta(t *testing.T) { setupClientNodeOrderDB(t) nodeID, fake := setupNodeRuntime(t) inbound := nodeInbound(t, nodeID, 46004, nil) first := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) t.Cleanup(first.release) email := "wait-deadline@example.test" data := &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{{ Email: email, ID: uuid.NewString(), Enable: true, }})} inboundSvc, clientSvc := &InboundService{}, &ClientService{} done := make(chan error, 1) completed := make(chan struct{}) t.Cleanup(func() { first.release() <-completed }) go func() { defer close(completed) _, err := clientSvc.AddInboundClient(inboundSvc, data) done <- err }() select { case err := <-done: if err != nil { t.Fatal(err) } case <-time.After(nodeClientPushTimeout + 2*time.Second): t.Fatal("client request waited for a dispatch turn past its deadline") } if fake.addClient.Load() != 0 { t.Fatal("expired client push overtook the in-flight operation") } current, err := inboundSvc.GetInbound(inbound.Id) if err != nil || !strings.Contains(current.Settings, email) { t.Fatalf("expired queue wait lost the committed client: %v", err) } if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { t.Fatalf("expired queue wait did not leave the node dirty: dirty=%v err=%v", dirty, err) } first.release() next := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) defer next.release() select { case <-next.ready: default: t.Fatal("expired dispatch turn blocked the next mutation") } } func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) { setupClientNodeOrderDB(t) nodeID, _ := setupNodeRuntime(t) mgr := runtime.GetManager() release := make(chan struct{}) unblock := sync.OnceFunc(func() { close(release) }) const email = "depleted-while-pushing@example.test" blocked := &blockedClientPushRuntime{calls: make(chan string, 4), release: release, blockedEmail: email} mgr.SetRuntimeOverride(nodeID, blocked) ib := nodeInbound(t, nodeID, 46012, nil) inboundSvc := &InboundService{} client := model.Client{Email: email, ID: uuid.NewString(), Enable: true, TotalGB: 5} add := &model.Inbound{Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client})} var wg sync.WaitGroup t.Cleanup(func() { unblock() wg.Wait() }) addDone := make(chan error, 1) wg.Go(func() { _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) addDone <- err }) select { case got := <-blocked.calls: if got != "add "+client.Email { t.Fatalf("first node operation = %q", got) } case <-time.After(3 * time.Second): t.Fatal("node did not receive the add") } depletionDone := make(chan error, 1) wg.Go(func() { _, disabled, err := inboundSvc.AddTraffic(nil, []*xray.ClientTraffic{{Email: client.Email, Up: 10}}) if !disabled { err = errors.Join(err, errors.New("traffic did not disable the depleted client")) } depletionDone <- err }) deadline := time.Now().Add(time.Second) for readTraffic(t, database.GetDB(), client.Email).Enable { if time.Now().After(deadline) { t.Fatal("depletion did not commit while the add was blocked") } time.Sleep(5 * time.Millisecond) } select { case got := <-blocked.calls: t.Fatalf("node operation %q overtook the pending add", got) case <-time.After(100 * time.Millisecond): } unblock() select { case got := <-blocked.calls: if got != "lifecycle "+ib.Tag { t.Fatalf("second node operation = %q, want the depletion update", got) } case <-time.After(time.Second): t.Fatal("node did not receive the depletion update") } for _, done := range []<-chan error{addDone, depletionDone} { if err := waitTrafficWriterErr(t, done); err != nil { t.Fatal(err) } } } func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) { setupClientNodeOrderDB(t) mgr := useTestRuntimeManager(t) const tag = "in-46011" listStarted := make(chan struct{}) releaseList := make(chan struct{}) release := sync.OnceFunc(func() { close(releaseList) }) var lists atomic.Int32 pushedSettings := make(chan string, 4) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var obj any switch r.URL.Path { case "/panel/api/inbounds/list": if lists.Add(1) == 1 { close(listStarted) select { case <-r.Context().Done(): return case <-releaseList: } } obj = []map[string]any{{"id": 1, "tag": tag}} case "/panel/api/inbounds/update/1": if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } pushedSettings <- r.Form.Get("settings") default: http.NotFound(w, r) return } _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) })) t.Cleanup(server.Close) t.Cleanup(release) node := reconcileTestNode(t, server, "reconcile-overlap", "all", nil) remote := runtime.NewRemote(node, nil) fast := &fakeNodeRuntime{} mgr.SetRuntimeOverride(node.Id, fast) ib := nodeInbound(t, node.Id, 46011, nil) clientSvc, inboundSvc, nodeSvc := &ClientService{}, &InboundService{}, &NodeService{} // Exercise generation ordering even when the previous timestamp is ahead of the clock. oldGeneration := time.Now().Add(time.Minute).UnixMilli() if err := database.GetDB().Model(node).Updates(map[string]any{ "config_dirty": true, "config_dirty_at": oldGeneration, }).Error; err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() reconciled := make(chan error, 1) go func() { reconciled <- inboundSvc.ReconcileNode(ctx, remote, node) }() waitTrafficWriterSignal(t, listStarted, "reconcile never reached the remote list") client := model.Client{Email: "during-reconcile@example.test", ID: uuid.NewString(), Enable: true} if needRestart, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client}), }); needRestart || err != nil { t.Fatalf("add during reconcile: restart=%t err=%v", needRestart, err) } if got := fast.addClient.Load(); got != 0 { t.Fatalf("%d incremental pushes overlapped a reconcile of older settings", got) } release() if err := waitTrafficWriterErr(t, reconciled); err != nil { t.Fatal(err) } select { case pushed := <-pushedSettings: if strings.Contains(pushed, client.Email) { t.Fatalf("first reconcile should still carry the pre-add settings, got %s", pushed) } default: t.Fatal("first reconcile did not push the captured configuration") } if err := nodeSvc.ClearNodeDirty(node.Id, oldGeneration); err != nil { t.Fatal(err) } _, _, dirty, generation, err := nodeSvc.NodeSyncState(node.Id) if err != nil || !dirty || generation <= oldGeneration { t.Fatalf("new generation lost after stale reconcile: dirty=%t generation=%d previous=%d err=%v", dirty, generation, oldGeneration, err) } if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { t.Fatal(err) } select { case pushed := <-pushedSettings: if !strings.Contains(pushed, client.Email) { t.Fatalf("next reconcile did not deliver the committed client: %s", pushed) } default: t.Fatal("next reconcile did not push the new configuration") } } func TestNodeWideDeleteSkipsReattachmentSentByQueuedReconcile(t *testing.T) { setupClientNodeOrderDB(t) mgr := useTestRuntimeManager(t) const primaryTag, blockerTag, recreatedTag = "in-46013", "in-46014", "in-46015" const email = "recreated@example.test" firstPush := make(chan struct{}) releaseFirstPush := make(chan struct{}) release := sync.OnceFunc(func() { close(releaseFirstPush) }) var hasClient atomic.Bool hasClient.Store(true) var adds, deletes, blockerUpdates, recreatedUpdates atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var obj any switch r.URL.Path { case "/panel/api/inbounds/list": obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}, {"id": 3, "tag": recreatedTag}} case "/panel/api/clients/add": if adds.Add(1) == 1 { close(firstPush) select { case <-r.Context().Done(): return case <-releaseFirstPush: } } case "/panel/api/inbounds/update/1": case "/panel/api/inbounds/update/3": recreatedUpdates.Add(1) if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } hasClient.Store(strings.Contains(r.Form.Get("settings"), "recreated configuration")) case "/panel/api/inbounds/update/2": blockerUpdates.Add(1) case "/panel/api/clients/del/" + email: deletes.Add(1) hasClient.Store(false) default: http.NotFound(w, r) return } _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) })) t.Cleanup(server.Close) var wg sync.WaitGroup t.Cleanup(func() { release() wg.Wait() }) node := reconcileTestNode(t, server, "reconcile-full-delete", "all", nil) remote := runtime.NewRemote(node, nil) mgr.SetRuntimeOverride(node.Id, remote) client := model.Client{Email: email, ID: uuid.NewString(), SubID: "reconcile-recreated", Enable: true} inbound := nodeInbound(t, node.Id, 46013, []model.Client{client}) blocker := nodeInbound(t, node.Id, 46014, nil) recreated := nodeInbound(t, node.Id, 46015, nil) inboundSvc, clientSvc := &InboundService{}, &ClientService{} addPayload := &model.Inbound{Id: blocker.Id, Protocol: model.VLESS, Settings: clientsSettings(t, []model.Client{{ Email: "first-push@example.test", ID: uuid.NewString(), Enable: true, }})} async := func(run func() error) <-chan error { done := make(chan error, 1) wg.Go(func() { done <- run() }) return done } waitUntil := func(message string, ready func() bool) { t.Helper() deadline := time.Now().Add(time.Second) for !ready() { if time.Now().After(deadline) { t.Fatal(message) } time.Sleep(5 * time.Millisecond) } } added := async(func() error { _, err := clientSvc.AddInboundClient(inboundSvc, addPayload) return err }) waitTrafficWriterSignal(t, firstPush, "first AddClient never reached the node") ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second) defer cancel() reconciled := async(func() error { return inboundSvc.ReconcileNode(ctx, remote, node) }) waitUntil("reconcile did not queue behind the first add", func() bool { nodeConfigDispatchMu.Lock() defer nodeConfigDispatchMu.Unlock() queue := nodeConfigDispatch[node.Id] return queue != nil && queue.reconciles > 0 }) deleted := async(func() error { _, err := clientSvc.DelInboundClientByEmail(inboundSvc, inbound.Id, email, true, true) return err }) waitUntil("full delete did not commit behind the reconcile", func() bool { current, err := inboundSvc.GetInbound(inbound.Id) return err == nil && !strings.Contains(current.Settings, email) }) client.Comment = "recreated configuration" if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ Id: recreated.Id, Protocol: recreated.Protocol, Settings: clientsSettings(t, []model.Client{client}), }); err != nil { t.Fatal(err) } release() for _, done := range []<-chan error{added, reconciled, deleted} { if err := waitTrafficWriterErr(t, done); err != nil { t.Fatal(err) } } if adds.Load() != 1 || deletes.Load() != 0 || !hasClient.Load() { t.Fatalf("queued delete touched the reattachment: adds=%d deletes=%d client=%t", adds.Load(), deletes.Load(), hasClient.Load()) } if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { t.Fatal(err) } if !hasClient.Load() || recreatedUpdates.Load() != 1 { t.Fatalf("reconcile unnecessarily re-sent the reattachment (pushes=%d)", recreatedUpdates.Load()) } if blockerUpdates.Load() != 1 { t.Fatalf("reconcile re-sent unrelated inbound (pushes=%d)", blockerUpdates.Load()) } } func TestNodeWideDeleteRetriesAfterQueueExpiry(t *testing.T) { for _, mode := range []string{"expired queue", "lost acknowledgment", "recreated client", "recreated on another node"} { t.Run(mode, func(t *testing.T) { setupClientNodeOrderDB(t) mgr := useTestRuntimeManager(t) const email = "durable-delete@example.test" const tag = "in-46019" var remoteRecord, remoteLink, dropAck atomic.Bool var deletes atomic.Int32 remoteRecord.Store(true) remoteLink.Store(true) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { response := map[string]any{"success": true} switch r.URL.Path { case "/panel/api/inbounds/list": response["obj"] = []map[string]any{{"id": 1, "tag": tag}} case "/panel/api/inbounds/update/1": if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } remoteLink.Store(strings.Contains(r.Form.Get("settings"), email)) case "/panel/api/clients/add": remoteLink.Store(true) remoteRecord.Store(true) case "/panel/api/clients/del/" + email: deletes.Add(1) remoteLink.Store(false) if !remoteRecord.Swap(false) { response["success"] = false response["msg"] = fmt.Sprintf("Error (client %q not found in any inbound or client record)", email) } if dropAck.CompareAndSwap(true, false) { <-r.Context().Done() return } default: http.NotFound(w, r) return } _ = json.NewEncoder(w).Encode(response) })) t.Cleanup(server.Close) node := reconcileTestNode(t, server, "durable-client-delete", "all", nil) remote := runtime.NewRemote(node, nil) mgr.SetRuntimeOverride(node.Id, remote) client := model.Client{Email: email, ID: uuid.NewString(), SubID: "durable-delete", Enable: true} inbound := nodeInbound(t, node.Id, 46019, []model.Client{client}) inboundSvc, clientSvc := &InboundService{}, &ClientService{} record := lookupClientRecord(t, email) if mode == "expired queue" { earlier := reserveNodeConfigTurn(node.Id, inbound.Id, nodeClientDelta) defer earlier.release() start := time.Now() if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { t.Fatal(err) } if elapsed := time.Since(start); elapsed >= 2*nodeClientPushTimeout || deletes.Load() != 0 { t.Fatalf("delete ignored its queue budget: elapsed=%v RPCs=%d", elapsed, deletes.Load()) } earlier.release() } else { if err := database.GetDB().Model(node).Update("status", "offline").Error; err != nil { t.Fatal(err) } if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { t.Fatal(err) } if err := database.GetDB().Model(node).Update("status", "online").Error; err != nil { t.Fatal(err) } } if _, err := clientSvc.GetRecordByEmail(nil, email); !errors.Is(err, gorm.ErrRecordNotFound) { t.Fatalf("master still has the deleted record: %v", err) } if !remoteRecord.Load() || !remoteLink.Load() { t.Fatal("fixture deleted the node client before delivery") } wantCalls := int32(1) var otherNode *model.Node var otherInbound *model.Inbound var otherRuntime *fakeNodeRuntime if mode == "recreated on another node" { otherNode = &model.Node{Name: "other-delete-node", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Status: "online"} if err := database.GetDB().Create(otherNode).Error; err != nil { t.Fatal(err) } otherRuntime = &fakeNodeRuntime{} mgr.SetRuntimeOverride(otherNode.Id, otherRuntime) otherInbound = nodeInbound(t, otherNode.Id, 46020, nil) client.ID = uuid.NewString() if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ Id: otherInbound.Id, Protocol: otherInbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), }); err != nil { t.Fatal(err) } if got := lookupClientRecord(t, email); got.Id == record.Id { t.Fatal("test did not create a new client incarnation on the other node") } var pending int64 if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, email).Count(&pending).Error; err != nil || pending != 1 { t.Fatalf("recreation on another node must keep the original pending delete: %d (%v)", pending, err) } } if mode == "recreated client" { client.ID = uuid.NewString() if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), }); err != nil { t.Fatal(err) } if got := lookupClientRecord(t, email); got.Id == record.Id { t.Fatal("test did not create a new client incarnation") } wantCalls = 0 } if mode == "lost acknowledgment" { dropAck.Store(true) ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) err := inboundSvc.ReconcileNode(ctx, remote, node) cancel() if !errors.Is(err, context.DeadlineExceeded) || remoteRecord.Load() || remoteLink.Load() { t.Fatalf("expected remote commit with an uncertain reply: %v", err) } wantCalls = 2 } if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { t.Fatal(err) } wantPresent := mode == "recreated client" if deletes.Load() != wantCalls || remoteRecord.Load() != wantPresent || remoteLink.Load() != wantPresent { t.Fatalf("node after replay: RPCs=%d record=%v membership=%v", deletes.Load(), remoteRecord.Load(), remoteLink.Load()) } if otherNode != nil { current, err := inboundSvc.GetInbound(otherInbound.Id) if err != nil || !strings.Contains(current.Settings, email) { t.Fatalf("reconcile changed the other node's desired client: %v", err) } if otherRuntime.addClient.Load() != 1 || otherRuntime.deleteClient.Load() != 0 { t.Fatalf("other node RPCs: adds=%d deletes=%d", otherRuntime.addClient.Load(), otherRuntime.deleteClient.Load()) } if got := lookupClientRecord(t, email); got.Id == record.Id { t.Fatal("reconcile did not preserve the new client record") } } var pending int64 if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ?", node.Id).Count(&pending).Error; err != nil || pending != 0 { t.Fatalf("pending deletes after reconciliation: %d (%v)", pending, err) } }) } }