diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e83d681e..cd6827ab2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,16 @@ jobs: exit 1 fi + - name: PostgreSQL node client push ordering + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) + if [ "$passed" -ne 7 ]; then + echo "expected 7 passing PostgreSQL node client ordering tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail diff --git a/internal/database/db.go b/internal/database/db.go index 666f737da..f5f530211 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -91,6 +91,7 @@ func allModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, diff --git a/internal/database/migrate_data.go b/internal/database/migrate_data.go index b9e840104..0f7bf68e8 100644 --- a/internal/database/migrate_data.go +++ b/internal/database/migrate_data.go @@ -8,6 +8,7 @@ import ( "os" "path" "reflect" + "slices" "strings" "time" @@ -59,6 +60,7 @@ func migrationModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, @@ -225,6 +227,16 @@ func copyTable(src, dst *gorm.DB, mdl any) (int, error) { } order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ") table := stmt.Schema.Table + if _, optional := mdl.(*model.NodePendingClientDelete); optional { + // Backups predating the outbox have no pending deletes to copy. + tables, err := src.Migrator().GetTables() + if err != nil { + return 0, err + } + if !slices.Contains(tables, table) { + return 0, nil + } + } columns := stmt.Schema.DBNames ctx := context.Background() diff --git a/internal/database/migrate_data_test.go b/internal/database/migrate_data_test.go index 685463dd0..16d959a17 100644 --- a/internal/database/migrate_data_test.go +++ b/internal/database/migrate_data_test.go @@ -18,13 +18,16 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { t.Skip("set XUI_TEST_PG_DSN to a reachable Postgres to run this test") } - // Seed a SQLite source with the full schema and >500 client_inbounds rows. + // Seed a pre-outbox SQLite source with >500 client_inbounds rows. srcPath := t.TempDir() + "/x-ui.db" src, err := gorm.Open(sqlite.Open(srcPath), &gorm.Config{Logger: logger.Discard}) if err != nil { t.Fatalf("open sqlite: %v", err) } for _, m := range migrationModels() { + if _, pending := m.(*model.NodePendingClientDelete); pending { + continue + } if err := src.AutoMigrate(m); err != nil { t.Fatalf("automigrate %T: %v", m, err) } @@ -61,6 +64,9 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { if got != n { t.Fatalf("client_inbounds rows = %d, want %d", got, n) } + if err := dst.Model(&model.NodePendingClientDelete{}).Count(&got).Error; err != nil || got != 0 { + t.Fatalf("migrated pending delete rows = %d, want 0 (%v)", got, err) + } } func TestMigrateData_PreservesFalseDefaultedColumns(t *testing.T) { @@ -207,3 +213,41 @@ func TestMigrateData_FailedCopyLeavesDestinationUntouched(t *testing.T) { t.Fatalf("failed migration leaked partial rows: evil count = %d, want 0", evil) } } + +func TestCopyPendingClientDeletesAcceptsLegacySourceAndPreservesNewRows(t *testing.T) { + openDB := func(path string) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + conn, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return db + } + src := openDB(t.TempDir() + "/source.db") + dst := openDB(t.TempDir() + "/destination.db") + pending := &model.NodePendingClientDelete{NodeId: 1, Email: "pending@example.test", ClientId: 3, Generation: "queue-generation", LastAttemptAt: 17} + if err := dst.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 0 { + t.Fatalf("copy from source without delete queue: %d rows, %v", n, err) + } + if err := src.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if err := src.Create(pending).Error; err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 1 { + t.Fatalf("copy persisted delete queue: %d rows, %v", n, err) + } + var got model.NodePendingClientDelete + if err := dst.Take(&got).Error; err != nil || got != *pending { + t.Fatalf("copied delete intent = %+v, want %+v (%v)", got, pending, err) + } +} diff --git a/internal/database/model/node_pending_client_delete.go b/internal/database/model/node_pending_client_delete.go new file mode 100644 index 000000000..9d48cc53d --- /dev/null +++ b/internal/database/model/node_pending_client_delete.go @@ -0,0 +1,10 @@ +package model + +// NodePendingClientDelete tracks a permanent delete that the node has not confirmed. +type NodePendingClientDelete struct { + NodeId int `gorm:"primaryKey;autoIncrement:false;index:idx_node_delete_order,priority:1"` + Email string `gorm:"primaryKey;index:idx_node_delete_order,priority:3"` + ClientId int `gorm:"not null"` + Generation string `gorm:"not null"` + LastAttemptAt int64 `gorm:"not null;index:idx_node_delete_order,priority:2"` +} diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 7bff47238..1d7ba96f0 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -65,6 +65,38 @@ func TestReconcileInbound_SkipsUnchanged(t *testing.T) { } } +func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) { + for _, response := range []struct { + name string + body string + failed bool + }{ + {name: "acknowledged", body: `{"success":true}`}, + {name: "uncertain", body: `{"success":false,"msg":"apply failed"}`, failed: true}, + } { + t.Run(response.name, func(t *testing.T) { + srv, _ := newCountingNodeServer(t, response.body) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + affected := &model.Inbound{Tag: "in-1", Protocol: model.VLESS, Settings: `{"clients":[{"email":"delete@example.test"}]}`} + unaffected := &model.Inbound{Tag: "in-2", Protocol: model.VLESS, Settings: `{"clients":[{"email":"keep@example.test"}]}`} + r.AdoptInboundAlias(affected, RemoteInboundOption{Tag: "adopted-1", Id: 1}) + r.AdoptInboundAlias(unaffected, RemoteInboundOption{Tag: "adopted-2", Id: 2}) + if err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { + t.Fatalf("unexpected delete result: %v", err) + } + if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed { + t.Fatalf("unaffected inbound: pushed=%v err=%v", pushed, err) + } + if pushed, err := r.ReconcileInbound(t.Context(), affected, true); err != nil || !pushed { + t.Fatalf("affected inbound: pushed=%v err=%v", pushed, err) + } + if id, err := r.resolveRemoteID(t.Context(), unaffected.Tag); err != nil || id != 2 { + t.Fatalf("unaffected alias: id=%d err=%v", id, err) + } + }) + } +} + type nodeCallCounts struct { adds atomic.Int32 inboundUpdates atomic.Int32 diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index df8e2d721..8a2288868 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -97,7 +97,7 @@ type Remote struct { // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. - pushedFP map[string]string + pushedFP map[string]pushedInboundState // supportsZstd is learned from the node's X-3x-Node-Caps response header; once // seen, config pushes to this node are zstd-compressed. Old nodes never set // it, so they keep receiving plain bodies (mixed-version safe). @@ -137,7 +137,7 @@ func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { snapshotGate: make(chan struct{}, 1), remoteIDByTag: make(map[string]int), adoptedAliases: make(map[string]string), - pushedFP: make(map[string]string), + pushedFP: make(map[string]pushedInboundState), egressResolver: r, } } @@ -655,7 +655,7 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists r.mu.RLock() prev, ok := r.pushedFP[ib.Tag] r.mu.RUnlock() - if ok && prev == fp { + if ok && prev.fingerprint == fp { return false, nil } } else { @@ -670,9 +670,9 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists // recordPushedInbound stamps the fingerprint after a full-payload push — the // only operation that proves the node holds the entire wire payload. func (r *Remote) recordPushedInbound(ib *model.Inbound) { - fp := wireFingerprint(wireInbound(ib, r.node.Id)) + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() - r.pushedFP[ib.Tag] = fp + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -713,11 +713,12 @@ func (r *Remote) ForgetInbound(tag string) { // AdoptInboundAlias records a deployed alias without mutating either panel. // The runtime association is rediscovered after a master restart. func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) { + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag - r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id)) + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -738,14 +739,50 @@ func (r *Remote) AdoptedInboundAliases() []string { // the next reconcile re-sends the full inbound. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) { prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id)) - nextFP := wireFingerprint(wireInbound(ib, r.node.Id)) + next := stampPushedInbound(ib, r.node.Id) r.mu.Lock() - if r.pushedFP[ib.Tag] == prevFP { - r.pushedFP[ib.Tag] = nextFP + if r.pushedFP[ib.Tag].fingerprint == prevFP { + r.pushedFP[ib.Tag] = next } r.mu.Unlock() } +type pushedInboundClient struct { + Email string `json:"email"` +} + +type pushedInboundState struct { + fingerprint string + clients []pushedInboundClient + clientsKnown bool +} + +func stampPushedInbound(ib *model.Inbound, nodeID int) pushedInboundState { + var settings struct { + Clients []pushedInboundClient `json:"clients"` + } + err := json.Unmarshal([]byte(ib.Settings), &settings) + return pushedInboundState{ + fingerprint: wireFingerprint(wireInbound(ib, nodeID)), + clients: settings.Clients, + clientsKnown: err == nil, + } +} + +// A node-wide delete can remove a client from several inbounds, even when its +// reply times out. Only those previously stamped with that client can change. +func (r *Remote) forgetPushedClient(email string) { + r.mu.Lock() + defer r.mu.Unlock() + for tag, state := range r.pushedFP { + if !state.clientsKnown || slices.ContainsFunc(state.clients, func(client pushedInboundClient) bool { + return client.Email == email + }) { + delete(r.pushedFP, tag) + } + } +} + // wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect. func wireFingerprint(v url.Values) string { sum := sha256.Sum256([]byte(v.Encode())) @@ -805,12 +842,17 @@ func (r *Remote) DeleteClient(ctx context.Context, email string) error { } _, err := r.do(ctx, http.MethodPost, "panel/api/clients/del/"+url.PathEscape(email), nil) + r.forgetPushedClient(email) if err == nil { return nil } var apiErr *remoteAPIError - if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") { - return nil + if errors.As(err, &apiErr) { + absent := fmt.Sprintf("client %q not found in any inbound or client record", email) + message := strings.TrimSpace(apiErr.msg) + if message == absent || strings.HasSuffix(message, " ("+absent+")") { + return nil + } } return err } diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index ea249ba19..5bb9050eb 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "slices" "strings" "time" @@ -681,7 +682,8 @@ func (s *ClientService) bulkAdjustInboundClients( adTagIneligible: map[string]bool{}, } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -816,7 +818,7 @@ func (s *ClientService) bulkAdjustInboundClients( // Serialize against the traffic poll to avoid the cross-transaction // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -827,9 +829,6 @@ func (s *ClientService) bulkAdjustInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -847,28 +846,28 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - for email := range foundEmails { - entry := plan[email] - updated := *entry.record.ToClient() - if entry.applyExpiry { - updated.ExpiryTime = entry.newExpiry + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for email := range foundEmails { + entry := plan[email] + updated := *entry.record.ToClient() + if entry.applyExpiry { + updated.ExpiryTime = entry.newExpiry + } + if entry.applyTotal { + updated.TotalGB = entry.newTotal + } + if adTag != "" && oldInbound.Protocol == model.MTProto { + updated.AdTag = wantAdTag + } + updated.UpdatedAt = nowMs + err := rt.UpdateUser(ctx, oldInbound, email, updated) + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - if entry.applyTotal { - updated.TotalGB = entry.newTotal - } - if adTag != "" && oldInbound.Protocol == model.MTProto { - updated.AdTag = wantAdTag - } - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - // First failure ends the batch push; the reconcile converges the rest. - break - } - } + return true + }) } } } @@ -1057,7 +1056,8 @@ func (s *ClientService) bulkDelInboundClients( res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}} defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1190,9 +1190,17 @@ func (s *ClientService) bulkDelInboundClients( } } - // Serialize against the traffic poll to avoid the cross-transaction - // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + var dispatchEmails []string + if oldInbound.NodeID != nil { + for email := range wantedEmails { + if _, skip := res.perEmailSkipped[email]; !skip { + dispatchEmails = append(dispatchEmails, email) + } + } + slices.Sort(dispatchEmails) + } + var pending []model.NodePendingClientDelete + txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -1203,10 +1211,8 @@ func (s *ClientService) bulkDelInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } - return nil + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, dispatchEmails) + return err }) if txErr != nil { for email := range wantedEmails { @@ -1238,30 +1244,22 @@ func (s *ClientService) bulkDelInboundClients( } } } else { - dispatchEmails := make([]string, 0, len(wantedEmails)) - for email := range wantedEmails { - if _, skip := res.perEmailSkipped[email]; !skip { - dispatchEmails = append(dispatchEmails, email) - } - } - if len(dispatchEmails) > nodeBulkPushThreshold { + if len(pending) == 0 || len(pending) > nodeBulkPushThreshold { return res } rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr) } else if push { - for _, email := range dispatchEmails { - ctx, cancel := nodePushContext() - err1 := rt.DeleteClient(ctx, email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - // The node is already dirty, so one reconcile converges the rest of - // the batch instead of paying another deadline per client. - break + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, row := range pending { + if err := applyNodeClientDelete(ctx, rt, row); err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } } - } + return true + }) } } @@ -1714,7 +1712,8 @@ func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult { res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}} - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1813,7 +1812,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, push = false } - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } @@ -1824,9 +1823,6 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -1862,23 +1858,19 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - pushFailed := false - for _, ch := range changed { - updated := ch.client - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - pushFailed = true - // First failure ends the batch push; the reconcile converges the rest. - break + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, ch := range changed { + updated := ch.client + updated.UpdatedAt = nowMs + err := rt.UpdateUser(ctx, oldInbound, ch.email, updated) + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - } - if !pushFailed { advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } return res diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 6a1c4842c..2ee15e988 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -140,7 +140,8 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if len(recs) == 0 { return false, nil } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -248,7 +249,7 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId // Persist the batch deletion atomically, serialized against the traffic poll // to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { for _, t := range targets { if t.emailShared || keepTraffic { continue @@ -276,63 +277,50 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return needRestart, txErr } - // Resolve the node push plan once for the whole batch instead of per email. - var nodeRt runtime.Runtime - nodePush := false if oldInbound.NodeID != nil { rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { return needRestart, perr } - nodeRt, nodePush = rt, push - // Large batches collapse into one reconcile push rather than M deletes. - if nodePush && len(targets) > nodeBulkPushThreshold { - nodePush = false + if push && len(targets) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, target := range targets { + if target.email == "" { + continue + } + err := rt.DeleteUser(ctx, oldInbound, target.email) + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } + } + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + return true + }) } + return needRestart, nil } - // Apply runtime deletes after commit — outside the serialized writer so a - // slow node call can't stall traffic accounting. - nodePushFailed := false for _, t := range targets { - if len(t.email) == 0 { + if t.email == "" || !t.needApiDel || !t.notDepleted { continue } - if oldInbound.NodeID == nil { - if t.needApiDel && t.notDepleted { - rt, rterr := inboundSvc.runtimeFor(oldInbound) - if rterr != nil { - needRestart = true - } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil { - if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) { - needRestart = true - } - } else if endDroppedClientSessions(oldInbound) { - needRestart = true - } - } - } else if nodePush && !nodePushFailed { - // First failure ends the batch push; the reconcile converges the rest. - ctx, cancel := nodePushContext() - err1 := nodeRt.DeleteUser(ctx, oldInbound, t.email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1) - nodePushFailed = true + rt, rterr := inboundSvc.runtimeFor(oldInbound) + if rterr != nil { + needRestart = true + } else if err := rt.RemoveUser(context.Background(), oldInbound, t.email); err != nil { + if !strings.Contains(err.Error(), fmt.Sprintf("User %s not found.", t.email)) { + needRestart = true } + } else if endDroppedClientSessions(oldInbound) { + needRestart = true } } - if nodePush && !nodePushFailed { - advancePushedInbound(nodeRt, prevSettings, string(newSettings), oldInbound) - } return needRestart, nil } @@ -406,8 +394,8 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { defer InvalidateSubData() - lock := lockInbound(data.Id) - defer lock.Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -611,7 +599,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } needRestart := false - nextOrphanOffset := lock.orphanOffset + nextOrphanOffset := mutation.lock.orphanOffset prunedOrphans := false rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) @@ -621,7 +609,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // lockInbound is per-inbound, so the pre-tx cross-inbound checks race // concurrent writers on other inbounds — re-run them in here (#6225). if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG { @@ -651,7 +639,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } // Confirm absence in the writer so an earlier committed re-add survives. - compacted, next, err := compactAddOrphans(tx, oldClients, lock.orphanOffset) + compacted, next, err := compactAddOrphans(tx, oldClients, mutation.lock.orphanOffset) if err != nil { return err } @@ -679,14 +667,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr } - lock.orphanOffset = nextOrphanOffset + mutation.lock.orphanOffset = nextOrphanOffset // Apply to the running runtime after commit — outside the serialized writer // so a slow node call can't stall traffic accounting. @@ -721,34 +706,25 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } - } else { - // Large batches would be M sequential per-client RPCs; the inbound's saved - // settings already hold the final set, so mark dirty and let one reconcile - // push converge the node instead. - if push && len(clients) > nodeBulkPushThreshold { - push = false - } - for _, client := range clients { - // /clients/add on the node historically coerced enable=true; skip live - // push for disabled clients and leave dirty so reconcile converges. - if !client.Enable { - push = false - continue - } - if push { - ctx, cancel := nodePushContext() + } else if push && len(clients) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + for _, client := range clients { + // Older nodes coerce enable=true. Reconcile the rest of this batch. + if !client.Enable { + return false + } err1 := rt.AddClient(ctx, oldInbound, client) - cancel() if err1 != nil { logger.Warning("Error in adding client on", rt.Name(), ":", err1) - push = false + return false } } - } - // AddClient only pushed the new clients. Reconcile any orphan removals. - if push && !prunedOrphans { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + // AddClient only pushed the new clients. Reconcile any orphan removals. + if !prunedOrphans { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + return !prunedOrphans + }) } return needRestart, nil @@ -756,7 +732,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) { defer InvalidateSubData() - defer lockInbound(data.Id).Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -1058,7 +1035,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // Same re-check-inside-the-writer rule as AddInboundClient (#6225): // the pre-tx pass can race a concurrent writer on another inbound. if oldInbound.Protocol == model.WireGuard { @@ -1164,9 +1141,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr @@ -1216,14 +1190,14 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - } else { + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } } else { logger.Debug("Client old email not found") @@ -1235,7 +1209,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) { defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1270,7 +1245,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo } } - if !found { + if !found && (!fullDelete || oldInbound.NodeID == nil) { return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email) } db := database.GetDB() @@ -1320,7 +1295,12 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // Persist the deletion atomically, serialized against the traffic poll to // avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + var pending []model.NodePendingClientDelete + work := nodeClientDelta + if fullDelete { + work = nodeFullClientDelete + } + if txErr := mutation.commit(oldInbound, work, func(tx *gorm.DB) error { if !emailShared && !keepTraffic { if e := inboundSvc.DelClientIPs(tx, email); e != nil { logger.Error("Error in delete client IPs") @@ -1339,8 +1319,9 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) + if fullDelete { + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, []string{email}) + return err } return nil }); txErr != nil { @@ -1386,19 +1367,24 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // must remove the node's client record too, not just detach it from // this inbound (#5797). if push { - ctx, cancel := nodePushContext() - var err1 error - if fullDelete { - err1 = rt.DeleteClient(ctx, email) - } else { - err1 = rt.DeleteUser(ctx, oldInbound, email) - } - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - } else { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + mutation.push(rt, oldInbound, func(ctx context.Context) bool { + var err error + if fullDelete { + for _, row := range pending { + err = applyNodeClientDelete(ctx, rt, row) + } + } else { + err = rt.DeleteUser(ctx, oldInbound, email) + } + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } + if !fullDelete { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + return true + }) } } } diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index e457d830f..1eda01a15 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -303,7 +303,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ wantedIds = append(wantedIds, id) } - relinked, err := s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune) + relinked, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) if err != nil { return err } @@ -359,7 +359,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ // reconcileInboundLinks writes only the client_inbounds rows that differ and returns // their clients. prune also removes links absent from wantedFlow, as only a full sync may. -func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { var current []model.ClientInbound if prune { if err := tx.Where("inbound_id = ?", inboundId).Find(¤t).Error; err != nil { @@ -447,6 +447,19 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted }).CreateInBatches(toInsert, 200).Error; err != nil { return nil, err } + if nodeID != nil { + reattached := make([]int, 0, len(toInsert)) + for _, link := range toInsert { + reattached = append(reattached, link.ClientId) + } + for _, batch := range chunkInts(reattached, sqlInChunk) { + emails := tx.Model(&model.ClientRecord{}).Select("email").Where("id IN ?", batch) + if err := tx.Where("node_id = ? AND email IN (?)", *nodeID, emails). + Delete(&model.NodePendingClientDelete{}).Error; err != nil { + return nil, err + } + } + } } relinked := append([]int(nil), toDelete...) diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go new file mode 100644 index 000000000..b00a47ec2 --- /dev/null +++ b/internal/web/service/client_node_dispatch.go @@ -0,0 +1,194 @@ +package service + +import ( + "container/list" + "context" + "sync" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +var ( + nodeConfigDispatchMu sync.Mutex + nodeConfigDispatch = map[int]*nodeConfigQueue{} +) + +type nodeConfigQueue struct { + groups list.List + reconciles int +} + +// Inbounds in the same group can push concurrently. A node-wide operation +// waits for the preceding group to drain before the next group can run. +type nodeConfigGroup struct { + position *list.Element + exclusive bool + inbounds map[int]*list.List +} + +type nodeConfigTurn struct { + nodeID int + inboundID int + queue *nodeConfigQueue + group *nodeConfigGroup + position *list.Element + ready chan struct{} + work nodeConfigWork +} + +type nodeConfigWork uint8 + +const ( + nodeClientDelta nodeConfigWork = iota + nodeFullClientDelete + nodeFullReconcile +) + +func reserveNodeConfigTurn(nodeID, inboundID int, work nodeConfigWork) *nodeConfigTurn { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q := nodeConfigDispatch[nodeID] + if q == nil { + q = &nodeConfigQueue{} + nodeConfigDispatch[nodeID] = q + } + // A reconcile can see later commits. It converges overlapping deltas, + // while node-wide deletes still run because they also remove client records. + if q.reconciles > 0 && work == nodeClientDelta { + return nil + } + exclusive := work != nodeClientDelta + if exclusive { + inboundID = 0 + } + var group *nodeConfigGroup + if last := q.groups.Back(); last != nil { + group = last.Value.(*nodeConfigGroup) + } + if group == nil || group.exclusive != exclusive { + group = &nodeConfigGroup{exclusive: exclusive, inbounds: make(map[int]*list.List)} + group.position = q.groups.PushBack(group) + } + lane := group.inbounds[inboundID] + if lane == nil { + lane = &list.List{} + group.inbounds[inboundID] = lane + } + turn := &nodeConfigTurn{ + nodeID: nodeID, inboundID: inboundID, queue: q, group: group, ready: make(chan struct{}), work: work, + } + turn.position = lane.PushBack(turn) + if work == nodeFullReconcile { + q.reconciles++ + } + if q.groups.Front() == group.position && lane.Front() == turn.position { + close(turn.ready) + } + return turn +} + +func (t *nodeConfigTurn) wait(ctx context.Context) bool { + select { + case <-t.ready: + return ctx.Err() == nil + case <-ctx.Done(): + return false + } +} + +func (t *nodeConfigTurn) release() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if t.position == nil { + return + } + q, group := t.queue, t.group + lane := group.inbounds[t.inboundID] + wasReady := q.groups.Front() == group.position && lane.Front() == t.position + lane.Remove(t.position) + t.position = nil + if t.work == nodeFullReconcile { + q.reconciles-- + } + if front := lane.Front(); front != nil { + if wasReady { + close(front.Value.(*nodeConfigTurn).ready) + } + return + } + delete(group.inbounds, t.inboundID) + if len(group.inbounds) > 0 { + return + } + q.groups.Remove(group.position) + if next := q.groups.Front(); next == nil { + delete(nodeConfigDispatch, t.nodeID) + } else if wasReady { + for _, lane := range next.Value.(*nodeConfigGroup).inbounds { + close(lane.Front().Value.(*nodeConfigTurn).ready) + } + } +} + +type inboundClientMutation struct { + lock *inboundMutationLock + turn *nodeConfigTurn +} + +func beginInboundClientMutation(inboundID int) *inboundClientMutation { + return &inboundClientMutation{lock: lockInbound(inboundID)} +} + +func (m *inboundClientMutation) unlock() { + if m.lock != nil { + m.lock.Unlock() + m.lock = nil + } +} + +func (m *inboundClientMutation) close() { + m.unlock() + if m.turn != nil { + m.turn.release() + } +} + +func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error { + if inbound.NodeID == nil { + return runSerializedTx(write) + } + nodeID := *inbound.NodeID + return runSerializedTxThen(func(tx *gorm.DB) error { + if err := write(tx); err != nil { + return err + } + return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID) + }, func() { + m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work) + }) +} + +func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context) bool) { + m.unlock() + if m.turn == nil { + return + } + waitCtx, stopWaiting := nodePushContext() + ready := m.turn.wait(waitCtx) + stopWaiting() + if !ready { + return + } + ctx, cancel := nodePushContext() + defer cancel() + complete := false + defer func() { + if remote, ok := rt.(*runtime.Remote); ok && !complete && m.turn.work != nodeFullClientDelete { + remote.ForgetPushedInbound(inbound.Tag) + } + }() + complete = apply(ctx) +} diff --git a/internal/web/service/client_node_order_test.go b/internal/web/service/client_node_order_test.go new file mode 100644 index 000000000..f3f1d1a5b --- /dev/null +++ b/internal/web/service/client_node_order_test.go @@ -0,0 +1,734 @@ +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) error { + r.calls <- "add " + client.Email + if client.Email != r.blockedEmail { + return nil + } + if r.waitForTimeout { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { + return 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 call.Err() + } + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error { + r.calls <- "update " + email + " " + client.Comment + return nil +} + +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error { + r.calls <- "detach " + email + return 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) + } + }) + } +} diff --git a/internal/web/service/client_node_push_test.go b/internal/web/service/client_node_push_test.go index 11119848f..9d6b135cd 100644 --- a/internal/web/service/client_node_push_test.go +++ b/internal/web/service/client_node_push_test.go @@ -1,11 +1,14 @@ package service import ( + "os" + "path/filepath" "testing" "time" "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" ) // TestResetTrafficAcrossNodesPushesConcurrently covers the panel's per-client @@ -73,12 +76,11 @@ func TestNodePushGivesUpBeforeTheRemoteTimeout(t *testing.T) { // TestBulkDeleteStopsPushingToAHungNode pins the batch circuit-break: once one // push times out, the rest of the batch defers to the reconcile as well. func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { - setupBulkDB(t) - startSerializedWriter(t) + setupClientNodeOrderDB(t) useTestRuntimeManager(t) f := newFakeNodeHTTP(t) - realNodeInbound(t, f, 53200, []model.Client{ + ib := realNodeInbound(t, f, 53200, []model.Client{ {Email: "b1@x", ID: "66666666-1111-2222-3333-444444444441", SubID: "sub-b1", Enable: true}, {Email: "b2@x", ID: "66666666-1111-2222-3333-444444444442", SubID: "sub-b2", Enable: true}, {Email: "b3@x", ID: "66666666-1111-2222-3333-444444444443", SubID: "sub-b3", Enable: true}, @@ -96,4 +98,21 @@ func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { if elapsed >= 2*nodeClientPushTimeout { t.Fatalf("deleting 3 clients took %v against a hung node, want a single %v deadline, not one per client", elapsed, nodeClientPushTimeout) } + if err := database.CloseDB(); err != nil { + t.Fatal(err) + } + if err := database.InitDB(filepath.Join(os.Getenv("XUI_DB_FOLDER"), "x-ui.db")); err != nil { + t.Fatal(err) + } + f.setHold(false) + var node model.Node + if err := database.GetDB().First(&node, *ib.NodeID).Error; err != nil { + t.Fatal(err) + } + if err := (&InboundService{}).ReconcileNode(t.Context(), runtime.NewRemote(&node, nil), &node); err != nil { + t.Fatal(err) + } + if got := f.hitCount("/clients/del/"); got != 4 { + t.Fatalf("delete requests including replay after reopening = %d, want 4 (one timed out, then all three retried)", got) + } } diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 5ca1f4bc8..2b4887144 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -137,14 +137,23 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, return nil } nodeID := n.Id + turn := reserveNodeConfigTurn(nodeID, 0, nodeFullReconcile) + defer turn.release() + if !turn.wait(ctx) { + return ctx.Err() + } + var errs []error + if err := deliverNodeClientDeletes(ctx, nodeID, rt); err != nil { + errs = append(errs, err) + } db := database.GetDB() var inbounds []*model.Inbound if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil { - return err + return errors.Join(append(errs, err)...) } remoteInbounds, err := rt.ListInboundOptions(ctx) if err != nil { - return err + return errors.Join(append(errs, err)...) } remoteTags := make([]string, 0, len(remoteInbounds)) remoteTagSet := make(map[string]struct{}, len(remoteTags)) @@ -154,7 +163,6 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, } prefix := nodeTagPrefix(&nodeID) desiredTags := make(map[string]struct{}, len(inbounds)*2) - var errs []error for _, ib := range inbounds { desiredTags[ib.Tag] = struct{}{} // existsOnNode: does the node already report this inbound under any of the diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index ce6f56f45..bc57a7114 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -34,6 +34,7 @@ func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraff func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart bool, clientsDisabled bool, err error) { var disabledNodeIDs []int var remotePlans []trafficInboundUpdatePlan + var remoteTurns []*nodeConfigTurn var renewed []string committed := false // The periodic poll takes the background lane: an operator's save or reset @@ -46,6 +47,9 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b committed = true var inner error needRestart, clientsDisabled, disabledNodeIDs, remotePlans, renewed, inner = s.maintainTrafficLocked() + if inner == nil { + remoteTurns = reserveTrafficRemoteTurns(remotePlans) + } return inner }) if err != nil { @@ -55,9 +59,16 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b } return } + defer func() { + for _, turn := range remoteTurns { + if turn != nil { + turn.release() + } + } + }() s.resetMtprotoClientQuotas(renewed) // Off the serial writer: a hanging node must not stall traffic accounting. - needRestart = s.applyTrafficRemotePlans(remotePlans) || needRestart + needRestart = s.applyTrafficRemotePlans(remotePlans, remoteTurns) || needRestart if len(disabledNodeIDs) > 0 { s.restartRemoteNodesOnDepletion(disabledNodeIDs) } diff --git a/internal/web/service/inbound_traffic_apply.go b/internal/web/service/inbound_traffic_apply.go index d2d65afd5..f0553c679 100644 --- a/internal/web/service/inbound_traffic_apply.go +++ b/internal/web/service/inbound_traffic_apply.go @@ -7,6 +7,7 @@ import ( "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" "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" @@ -60,32 +61,54 @@ func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error { return nil } -// applyTrafficRemotePlans is bounded like every per-client node push: the nodes are -// already dirty, so an offline or slow one defers to the reconcile. -func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan) bool { +// Reserve on the writer after maintenance commits so a newer client edit cannot pass it. +func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) []*nodeConfigTurn { + if len(plans) == 0 { + return nil + } + turns := make([]*nodeConfigTurn, len(plans)) + for i := range plans { + ib := &plans[i].newInbound + if ib.NodeID != nil { + turns[i] = reserveNodeConfigTurn(*ib.NodeID, ib.Id, nodeClientDelta) + } + } + return turns +} + +// The wait and pushes share one budget per node. Dirty state covers a skipped push. +func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan, turns []*nodeConfigTurn) bool { byNode := make(map[int][]int) var nodeIDs []int for i := range plans { - nodeID := 0 - if plans[i].newInbound.NodeID != nil { - nodeID = *plans[i].newInbound.NodeID + id := plans[i].newInbound.NodeID + if id == nil || turns[i] == nil { + continue } + nodeID := *id if _, seen := byNode[nodeID]; !seen { nodeIDs = append(nodeIDs, nodeID) } byNode[nodeID] = append(byNode[nodeID], i) } failed, panics := fanoutInboundResults(nodeIDs, nodeFanoutConcurrency, func(n int) bool { - // One budget per node, not per inbound: a node choosing how many inbounds it reports - // must not choose how long the sync job waits on it before serving other nodes. ctx, cancel := nodePushContext() defer cancel() indexes := byNode[nodeIDs[n]] nodeFailed, nodePanics := fanoutInboundResults(indexes, inboundFanoutConcurrency, func(k int) bool { - plan := &plans[indexes[k]] + index := indexes[k] + turn := turns[index] + defer turn.release() + if !turn.wait(ctx) { + return false + } + plan := &plans[index] rt, push, _, err := s.nodePushPlan(&plan.newInbound) if err == nil && push { err = rt.UpdateInbound(ctx, &plan.oldInbound, &plan.newInbound) + if remote, ok := rt.(*runtime.Remote); ok && err != nil { + remote.ForgetPushedInbound(plan.newInbound.Tag) + } } if err != nil { logger.Debug("traffic post-commit remote apply failed:", err) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 25ed1f493..735448b24 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -883,6 +883,9 @@ func (s *NodeService) Delete(id int) error { if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingReset{}).Error; err != nil { return err } + if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingClientDelete{}).Error; err != nil { + return err + } guids := []string{synthNodeGuid(id)} if guid != "" { guids = append(guids, guid) @@ -1076,11 +1079,12 @@ func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error { if tx == nil { return errors.New("nil db transaction") } + now := time.Now().UnixMilli() return tx.Model(model.Node{}). Where("id = ?", id). Updates(map[string]any{ "config_dirty": true, - "config_dirty_at": time.Now().UnixMilli(), + "config_dirty_at": gorm.Expr(database.GreatestExpr("COALESCE(config_dirty_at, 0) + 1", "?"), now), }).Error } diff --git a/internal/web/service/node_bulk_dispatch_test.go b/internal/web/service/node_bulk_dispatch_test.go index 2c572f8d3..6e33f9702 100644 --- a/internal/web/service/node_bulk_dispatch_test.go +++ b/internal/web/service/node_bulk_dispatch_test.go @@ -355,8 +355,8 @@ func TestNodeBulkDeleteCompletesAcrossPresentAndMissingSettings(t *testing.T) { if result.Deleted != 1 || len(result.Skipped) != 0 { t.Fatalf("BulkDelete result = %+v, want one deleted client", result) } - if got := fake.deleteClient.Load(); got != 2 { - t.Fatalf("remote DeleteClient calls = %d, want one per node inbound", got) + if got := fake.deleteClient.Load(); got != 1 { + t.Fatalf("remote DeleteClient calls = %d, want one full delete for the node", got) } } diff --git a/internal/web/service/node_client_delete_queue.go b/internal/web/service/node_client_delete_queue.go new file mode 100644 index 000000000..e494420ed --- /dev/null +++ b/internal/web/service/node_client_delete_queue.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "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 queueNodeClientDeletes(tx *gorm.DB, nodeID *int, emails []string) ([]model.NodePendingClientDelete, error) { + if nodeID == nil || len(emails) == 0 { + return nil, nil + } + ids := make(map[string]int, len(emails)) + for _, batch := range chunkStrings(emails, sqlInChunk) { + var records []model.ClientRecord + if err := tx.Select("id", "email").Where("email IN ?", batch).Find(&records).Error; err != nil { + return nil, err + } + for _, record := range records { + ids[record.Email] = record.Id + } + } + generation := uuid.NewString() + rows := make([]model.NodePendingClientDelete, 0, len(emails)) + for _, email := range emails { + rows = append(rows, model.NodePendingClientDelete{ + NodeId: *nodeID, Email: email, ClientId: ids[email], Generation: generation, + }) + } + err := tx.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, + DoUpdates: clause.AssignmentColumns([]string{"client_id", "generation", "last_attempt_at"}), + }).CreateInBatches(rows, 200).Error + return rows, err +} + +func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm.DB { + return db.Model(&model.NodePendingClientDelete{}). + Where("node_pending_client_deletes.node_id = ? AND node_pending_client_deletes.email = ? AND node_pending_client_deletes.generation = ?", + row.NodeId, row.Email, row.Generation) +} + +// applyNodeClientDelete runs under the node-wide turn. Later attached clients +// push after this turn or are restored by the dirty generation on reconcile. +func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) error { + db := database.GetDB().WithContext(ctx) + var target struct { + Desired bool + } + result := sameNodeClientDelete(db, row). + Select("EXISTS (" + + "SELECT 1 FROM client_inbounds JOIN inbounds ON inbounds.id = client_inbounds.inbound_id " + + "WHERE client_inbounds.client_id = clients.id AND inbounds.node_id = node_pending_client_deletes.node_id) AS desired"). + Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email"). + Limit(1).Scan(&target) + if result.Error != nil || result.RowsAffected == 0 { + return result.Error + } + // Only a desired attachment on this node supersedes its pending delete. + // Recreating the email elsewhere must not leave the old node record behind. + if !target.Desired { + if err := rt.DeleteClient(ctx, row.Email); err != nil { + return err + } + } + return sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error +} + +const nodeClientDeletePage = 200 + +// Reconciliation holds the exclusive node turn while delivering one bounded +// page. A failed page keeps the node dirty so snapshots cannot readopt clients. +func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtime) error { + db := database.GetDB().WithContext(ctx) + var rows []model.NodePendingClientDelete + if err := db.Where("node_id = ?", nodeID).Order("last_attempt_at, email"). + Limit(nodeClientDeletePage).Find(&rows).Error; err != nil { + return err + } + if len(rows) == 0 { + return nil + } + sendCtx, cancel := context.WithTimeout(ctx, nodeClientPushTimeout) + defer cancel() + var firstErr error + for _, row := range rows { + if err := applyNodeClientDelete(sendCtx, rt, row); err != nil { + if firstErr == nil { + firstErr = err + } + // Rotate a failing row behind entries that have not had a turn. + if err := sameNodeClientDelete(db, row).Update("last_attempt_at", time.Now().UnixNano()).Error; err != nil { + return errors.Join(firstErr, err) + } + if sendCtx.Err() != nil { + break + } + } + } + if firstErr != nil { + return fmt.Errorf("deliver node client deletes: %w", firstErr) + } + if len(rows) == nodeClientDeletePage { + var remaining int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ?", nodeID). + Limit(1).Select("1").Scan(&remaining).Error; err != nil { + return err + } + if remaining != 0 { + return errors.New("more node client deletes awaiting delivery") + } + } + return nil +} diff --git a/internal/web/service/node_reset_undelivered_test.go b/internal/web/service/node_reset_undelivered_test.go index 278d1c2b0..00d300357 100644 --- a/internal/web/service/node_reset_undelivered_test.go +++ b/internal/web/service/node_reset_undelivered_test.go @@ -388,7 +388,7 @@ func TestTrafficRemotePlansWaitOneBudgetPerNode(t *testing.T) { plans[i] = trafficInboundUpdatePlan{oldInbound: ib, newInbound: ib} } start := time.Now() - (&InboundService{}).applyTrafficRemotePlans(plans) + (&InboundService{}).applyTrafficRemotePlans(plans, reserveTrafficRemoteTurns(plans)) if took := time.Since(start); took > nodeClientPushTimeout+2*time.Second { t.Fatalf("pushing %d inbounds to one hanging node took %v", len(plans), took) } diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index a40b17484..017fc8acf 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -167,6 +167,11 @@ func drainTrafficWriter(adminQueue, bgQueue chan *trafficWriteRequest) { // remote node call would stall all traffic accounting for up to the remote // timeout. Apply runtime changes after this returns. func runSerializedTx(fn func(tx *gorm.DB) error) error { + return runSerializedTxThen(fn, nil) +} + +// afterCommit runs on the writer in commit order and must not wait or perform I/O. +func runSerializedTxThen(fn func(tx *gorm.DB) error, afterCommit func()) error { return submitTrafficWrite(func() error { state := &serializedTx{} err := database.GetDB().Transaction(func(tx *gorm.DB) error { @@ -176,6 +181,9 @@ func runSerializedTx(fn func(tx *gorm.DB) error) error { if err == nil { // Still on the writer, so no node merge runs between the commit and the lift. withdrawClientTombstones(state.createdClientEmails...) + if afterCommit != nil { + afterCommit() + } } return err })