From 7a5a25fae225e83431656a705ef57055f9997bad Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 2 Dec 2026 17:44:17 +0330 Subject: [PATCH] perf(nodes): reuse client link changes during full reconciliation (#7344) Reuse client records and successful link diffs during full node snapshot reconciliation. Preserve master-owned comments on existing records while importing new comments; omit comment writes so concurrent operator updates survive. Deduplicate detached IDs across successful inbound savepoints and mark only globally unattached clients in bounded 400-ID batches inside the existing transaction; roll back on orphan-mark write failure. Integrate against current main while preserving #7314 target-node pending-delete cancellation and cross-node recreation guarantees, #7315 staged traffic and batched baseline writes, and #7308 serialized eligibility checks. Preserve orphan recovery, degraded-inbound safeguards and idempotent snapshot replay. Validation: all 12 CI jobs passed on 51e627739ef632e86f4f180d91cae4cd8f8c714d (run 46895213148). PostgreSQL logs confirm four new reconciliation tests, both contention/baseline regressions and eight ordering/durable-delete regressions. Author reports focused SQLite/PostgreSQL 18 race tests, make verify and all four mixed-version node E2E pairings. Author-reported controlled 4096-client PostgreSQL 18 fixture: idle SQL statements 350 -> 270, changing-counter statements 552 -> 472, rows read 151832 -> 102680. Idle writer p50/p95 490/597 -> 430/466 ms; counter writer 489/521 -> 449/519 ms. Idle cycle p50/p95 1118/1277 -> 1015/1050 ms; counter cycle 1121/1172 -> 1046/1135 ms. Worst counter cycle effectively unchanged. These fixture results are not independent production measurements. Production tail latency, shared-client compact-cache reuse and migration coordination remain separate follow-ups. Refs #7305 --- .github/workflows/ci.yml | 16 + internal/web/service/client_link.go | 46 ++- internal/web/service/client_sync_orphan.go | 18 +- internal/web/service/inbound_node.go | 99 +----- .../service/node_full_reconciliation_test.go | 336 ++++++++++++++++++ 5 files changed, 406 insertions(+), 109 deletions(-) create mode 100644 internal/web/service/node_full_reconciliation_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9639a7fc8..767a5f045 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,22 @@ jobs: exit 1 fi + - name: PostgreSQL node client reconciliation + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeFullReconciliation|NodeMerge(BatchesBaselinesForActiveClients|LetsSubscriptionTouchDuringClientReconciliationPostgres)$)' -count=1 -v | tee /tmp/postgres-node-client-reconciliation.log + passed=$(grep -c -- '^--- PASS: TestNodeFullReconciliation' /tmp/postgres-node-client-reconciliation.log || true) + if [ "$passed" -ne 4 ]; then + echo "expected 4 passing node client reconciliation tests, got $passed" >&2 + exit 1 + fi + for test in TestNodeMergeBatchesBaselinesForActiveClients TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres; do + if ! grep -q -- "^--- PASS: $test " /tmp/postgres-node-client-reconciliation.log; then + echo "expected PostgreSQL regression to pass: $test" >&2 + exit 1 + fi + done + - name: PostgreSQL node counter reset regressions run: | set -o pipefail diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index 1eda01a15..ddf69e9ac 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -106,7 +106,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor // SyncInbound makes the inbound's client records and links match clients // exactly: links for clients no longer in the set are removed. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error { - return s.syncInboundClients(tx, inboundId, clients, nil, true) + return s.syncInboundClients(tx, inboundId, clients, nil, true, nil) } // withClientSyncSavepoint lets a caller continue only after a failed sync is undone. @@ -132,10 +132,14 @@ func withClientSyncSavepoint(tx *gorm.DB, sync func() error) (rejected, fatal er // the whole point being that a one-client edit must not rewrite the inbound's // entire membership set (#6252). func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error { - return s.syncInboundClients(tx, inboundId, changed, detachEmails, false) + return s.syncInboundClients(tx, inboundId, changed, detachEmails, false, nil) } -func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error { +type nodeInboundSyncResult struct { + detached []int +} + +func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool, node *nodeInboundSyncResult) error { if err := validateClientsRenewal(clients); err != nil { return err } @@ -239,6 +243,9 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } before := *row + if node != nil { + incoming.Comment = before.Comment + } applyClientRecordMerge(row, incoming) _, outranked := onLowerTunnel[row.Id] _, wireguardOutranked := onLowerWireguard[row.Id] @@ -255,6 +262,10 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } // Keep GORM's save hooks and serializers while writing the agreed timestamp once. save := tx.Session(&gorm.Session{NowFunc: func() time.Time { return time.UnixMilli(preservedUpdatedAt) }}) + if node != nil { + // An operator can change the note while this node merge is open. + save = save.Omit("Comment") + } if err := save.Save(row).Error; err != nil { return err } @@ -303,7 +314,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ wantedIds = append(wantedIds, id) } - relinked, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) + relinked, detached, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) if err != nil { return err } @@ -354,22 +365,25 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ // A failed validation can roll back the row while the outer transaction commits. liftTombstonesOnCommit(tx, toCreate) + if node != nil { + node.detached = detached + } return nil } // 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, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +// affected and detached client IDs. Only full sync prunes links absent from wantedFlow. +func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) (relinked, detached []int, err error) { var current []model.ClientInbound if prune { if err := tx.Where("inbound_id = ?", inboundId).Find(¤t).Error; err != nil { - return nil, err + return nil, nil, err } } else { for _, batch := range chunkInts(wantedIds, sqlInChunk) { var rows []model.ClientInbound if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil { - return nil, err + return nil, nil, err } current = append(current, rows...) } @@ -397,7 +411,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID for _, batch := range chunkStrings(detachEmails, sqlInChunk) { var ids []int if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil { - return nil, err + return nil, nil, err } for _, id := range ids { if _, keep := wantedFlow[id]; !keep { @@ -421,12 +435,12 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID // A restored, still-attached client must lose its legacy mark before it loses its link. if err := clearSyncOrphanMarks(tx, toDelete); err != nil { - return nil, err + return nil, nil, err } for _, batch := range chunkInts(toDelete, sqlInChunk) { if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Delete(&model.ClientInbound{}).Error; err != nil { - return nil, err + return nil, nil, err } } for flow, ids := range toUpdate { @@ -434,7 +448,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID if err := tx.Model(&model.ClientInbound{}). Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Update("flow_override", flow).Error; err != nil { - return nil, err + return nil, nil, err } } } @@ -445,7 +459,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}}, DoUpdates: clause.AssignmentColumns([]string{"flow_override"}), }).CreateInBatches(toInsert, 200).Error; err != nil { - return nil, err + return nil, nil, err } if nodeID != nil { reattached := make([]int, 0, len(toInsert)) @@ -456,20 +470,20 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID 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 + return nil, nil, err } } } } - relinked := append([]int(nil), toDelete...) + relinked = append([]int(nil), toDelete...) for _, ids := range toUpdate { relinked = append(relinked, ids...) } for _, link := range toInsert { relinked = append(relinked, link.ClientId) } - return relinked, nil + return relinked, toDelete, nil } // keepLinkOwnedFields undoes the merge of the record fields one inbound cannot decide diff --git a/internal/web/service/client_sync_orphan.go b/internal/web/service/client_sync_orphan.go index 5e73d8b42..809e25ad8 100644 --- a/internal/web/service/client_sync_orphan.go +++ b/internal/web/service/client_sync_orphan.go @@ -25,13 +25,19 @@ func clientRecordExists(tx *gorm.DB, email string) bool { return n > 0 } -func markSyncOrphan(tx *gorm.DB, email string, nodeID int, nowMs int64) error { - if email == "" { - return nil +func markDetachedSyncOrphans(tx *gorm.DB, ids []int, nodeID int, nowMs int64) (bool, error) { + marked := false + for _, batch := range chunkInts(ids, sqlInChunk) { + result := tx.Model(&model.ClientRecord{}). + Where("id IN ? AND email <> '' AND sync_orphaned_at = 0", batch). + Where("NOT EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)"). + Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}) + if result.Error != nil { + return false, result.Error + } + marked = marked || result.RowsAffected > 0 } - return tx.Model(&model.ClientRecord{}). - Where("email = ? AND sync_orphaned_at = 0", email). - Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}).Error + return marked, nil } // A client that is attached again is not orphaned, whatever an earlier merge diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index b80d7ea7b..269a2450e 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1455,11 +1455,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi syncFailedInbounds := map[int]struct{}{} if !skipStructure || structuralChange { - type oldSet struct { - inboundID int - emails map[string]struct{} - } - var perInboundOld []oldSet + detached := make(map[int]struct{}) for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1471,20 +1467,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if dirty { continue } - var oldEmailsRows []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", c.Id). - Pluck("email", &oldEmailsRows).Error; err == nil { - oldEmails := make(map[string]struct{}, len(oldEmailsRows)) - for _, e := range oldEmailsRows { - if e != "" { - oldEmails[e] = struct{}{} - } - } - perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails}) - } - clients, gcErr := s.GetClients(snapIb) if gcErr != nil { logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr) @@ -1512,37 +1494,10 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A degraded node (reset/restart/removal) reports zero clients for an inbound the // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734). if _, degraded := degradedInbounds[c.Id]; degraded { - logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub has %d attached — keeping them and re-pushing", nodeID, snapIb.Tag, len(oldEmailsRows)) + logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub still has attached clients — keeping them and re-pushing", nodeID, snapIb.Tag) syncFailedInbounds[c.Id] = struct{}{} continue } - localEmails := make([]string, 0, len(filtered)) - for i := range filtered { - if filtered[i].Email != "" { - localEmails = append(localEmails, filtered[i].Email) - } - } - commentByEmail := make(map[string]string, len(localEmails)) - for _, batch := range chunkStrings(localEmails, sqlInChunk) { - var localMeta []struct { - Email string - Comment string `gorm:"column:comment"` - } - if err := tx.Table("clients"). - Select("email, comment"). - Where("email IN ?", batch). - Find(&localMeta).Error; err != nil { - continue - } - for _, m := range localMeta { - commentByEmail[m.Email] = m.Comment - } - } - for i := range filtered { - if cmt, ok := commentByEmail[filtered[i].Email]; ok { - filtered[i].Comment = cmt - } - } p, adopt := pendingAdopts[c.Id] _, isNew := newInboundIDs[c.Id] adoptedSettings := p.wireSettings @@ -1561,13 +1516,14 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } updates["settings"] = adoptedSettings } + var linkResult nodeInboundSyncResult rejected, err := withClientSyncSavepoint(tx, func() error { if len(updates) > 0 { if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil { return err } } - return s.clientService.SyncInbound(tx, c.Id, filtered) + return s.clientService.syncInboundClients(tx, c.Id, filtered, nil, true, &linkResult) }) if err != nil { return false, err @@ -1584,6 +1540,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if len(updates) > 0 { structuralChange = true } + for _, id := range linkResult.detached { + detached[id] = struct{}{} + } adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged lifecycleLifted = lifecycleLifted || liftChanged // Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts. @@ -1592,46 +1551,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - for _, old := range perInboundOld { - // The sweep's premise is that links were just rebuilt from the snapshot, - // which is exactly what a failed SyncInbound violates. - if _, failed := syncFailedInbounds[old.inboundID]; failed { - continue - } - var stillAttached []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", old.inboundID). - Pluck("email", &stillAttached).Error; err != nil { - continue - } - stillSet := make(map[string]struct{}, len(stillAttached)) - for _, e := range stillAttached { - stillSet[e] = struct{}{} - } - for email := range old.emails { - if _, kept := stillSet[email]; kept { - continue - } - var attachmentCount int64 - if err := tx.Table("client_inbounds"). - Joins("JOIN clients ON clients.id = client_inbounds.client_id"). - Where("clients.email = ?", email). - Count(&attachmentCount).Error; err != nil { - continue - } - if attachmentCount > 0 { - continue - } - // "Ended the merge unattached" is true for a real remote deletion and - // equally true for a bad merge, so record a strike instead of deleting. - if err := markSyncOrphan(tx, email, nodeID, now); err != nil { - logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err) - continue - } - structuralChange = true - } + // A client detached here may have been attached to another inbound by the same snapshot. + marked, err := markDetachedSyncOrphans(tx, slices.Sorted(maps.Keys(detached)), nodeID, now) + if err != nil { + return false, fmt.Errorf("mark node %d sync orphans: %w", nodeID, err) } + structuralChange = structuralChange || marked } if err := upsertNodeBaselines(tx, baselineChanges); err != nil { diff --git a/internal/web/service/node_full_reconciliation_test.go b/internal/web/service/node_full_reconciliation_test.go new file mode 100644 index 000000000..7ae3cce0d --- /dev/null +++ b/internal/web/service/node_full_reconciliation_test.go @@ -0,0 +1,336 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "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" +) + +func TestNodeFullReconciliationReusesLinkDiff(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + createNodeInbound(t, db, nodeID, "remote-first", 41001) + createNodeInbound(t, db, nodeID, "remote-second", 41002) + var inbounds []model.Inbound + if err := db.Where("node_id = ?", nodeID).Order("id").Find(&inbounds).Error; err != nil { + t.Fatal(err) + } + keep := model.Client{Email: "keep@example.test", Enable: true, Comment: "remote comment"} + move := model.Client{Email: "move@example.test", Enable: true} + local := model.Client{Email: "still-local@example.test", Enable: true} + other := model.Client{Email: "still-on-other-node@example.test", Enable: true} + before := []model.Client{keep, move, local, other} + const dropped = sqlInChunk + 3 + for i := range dropped { + before = append(before, model.Client{Email: fmt.Sprintf("drop-%04d@example.test", i), Enable: true}) + } + clientSvc := &ClientService{} + localInbound := model.Inbound{UserId: 1, Tag: "local-inbound", Port: 41003, Protocol: model.VLESS, Enable: true} + if err := db.Create(&localInbound).Error; err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, localInbound.Id, []model.Client{local}); err != nil { + t.Fatal(err) + } + const otherNodeID = 2 + seedNodeRow(t, db, &model.Node{Id: otherNodeID, Name: "other", Address: "192.0.2.2", Port: 2053, Enable: true}) + createNodeInboundWithClient(t, db, otherNodeID, "other-node-inbound", 41004, other.Email) + if err := clientSvc.SyncInbound(db, inbounds[0].Id, before); err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, inbounds[1].Id, []model.Client{keep}); err != nil { + t.Fatal(err) + } + if err := db.Model(&model.ClientRecord{}).Where("email = ?", keep.Email). + UpdateColumn("comment", "operator note").Error; err != nil { + t.Fatal(err) + } + keep.LimitIP = 3 + last := model.Client{Email: "new@example.test", Enable: true, Comment: "imported note"} + wire := func(tag string, clients ...model.Client) *model.Inbound { + t.Helper() + raw, err := json.Marshal(map[string]any{"clients": clients}) + if err != nil { + t.Fatal(err) + } + return &model.Inbound{Tag: tag, Protocol: model.VLESS, Settings: string(raw)} + } + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + wire(inbounds[0].Tag, keep), wire(inbounds[1].Tag, keep, move, last), + }} + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Enable: true}} + queries := recordExecutedSQL(t, db) + const updateCallback = "test:record-node-reconciliation-updates" + if err := db.Callback().Update().After("gorm:update").Register(updateCallback, func(tx *gorm.DB) { + *queries = append(*queries, tx.Statement.SQL.String()) + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(updateCallback) }) + svc := &InboundService{} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + markWrites := 0 + for _, sql := range *queries { + stmt := strings.ToLower(sql) + if strings.HasPrefix(stmt, "select email, comment ") || + (strings.Contains(stmt, "count(*)") && strings.Contains(stmt, "clients.email =")) { + t.Fatalf("reconciliation repeated a per-inbound comment or per-client attachment read: %s", sql) + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "sync_orphaned_by") && + strings.Contains(stmt, "not exists") { + markWrites++ + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "comment") { + t.Fatalf("remote reconciliation unnecessarily wrote the operator's comment: %s", sql) + } + } + if markWrites != 2 { + t.Fatalf("marked a %d-client drop in %d writes, want 2", dropped, markWrites) + } + var marked []model.ClientRecord + if err := db.Where("sync_orphaned_at > 0").Find(&marked).Error; err != nil { + t.Fatal(err) + } + if len(marked) != dropped { + t.Fatalf("marked %d removed clients, want %d", len(marked), dropped) + } + for _, row := range marked { + if row.SyncOrphanedBy != nodeID || !strings.HasPrefix(row.Email, "drop-") { + t.Fatalf("unexpected orphan: %q, node %d", row.Email, row.SyncOrphanedBy) + } + } + for email, want := range map[string]string{keep.Email: "operator note", last.Email: "imported note"} { + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil || row.Comment != want { + t.Fatalf("comment for %q = %q, want %q (%v)", email, row.Comment, want, err) + } + } + var movedLinks []int + if err := db.Table("client_inbounds").Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Where("clients.email = ?", move.Email).Pluck("inbound_id", &movedLinks).Error; err != nil { + t.Fatal(err) + } + if len(movedLinks) != 1 || movedLinks[0] != inbounds[1].Id { + t.Fatalf("move lost its destination: %v", movedLinks) + } + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Up: 100, Down: 50, Enable: true}} + for range 2 { + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + } + baseline := model.NodeClientTraffic{} + if err := db.Where("node_id = ? AND email = ?", nodeID, keep.Email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, keep.Email) + if baseline.Up != 100 || baseline.Down != 50 || traffic.Up != 100 || traffic.Down != 50 { + t.Fatalf("reapplied snapshot duplicated traffic or lost the baseline: traffic=%+v baseline=%+v", traffic, baseline) + } + if got := readOrphanMark(t, db, marked[0].Email); got != marked[0].SyncOrphanedAt { + t.Fatalf("replayed snapshot changed the orphan grace timestamp to %d", got) + } +} + +func TestNodeFullReconciliationRollsBackOrphanWriteFailure(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + const tag = "remote-inbound" + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + svc := &InboundService{} + const keepEmail = "keep@example.test" + const oldSettings = `{"clients":[{"email":"keep@example.test","enable":true},{"email":"detached@example.test","enable":true}]}` + syncNodeWithSettings(t, svc, nodeID, tag, oldSettings, xray.ClientTraffic{Email: keepEmail, Enable: true, Up: 100}) + var oldInbound model.Inbound + if err := db.Where("tag = ?", tag).Take(&oldInbound).Error; err != nil { + t.Fatal(err) + } + + writeErr := errors.New("injected orphan write failure") + const callbackName = "test:fail-node-orphan-write" + if err := db.Callback().Update().Before("gorm:update").Register(callbackName, func(tx *gorm.DB) { + updates, ok := tx.Statement.Dest.(map[string]any) + if ok && tx.Statement.Table == "clients" && updates["sync_orphaned_by"] == nodeID { + _ = tx.AddError(writeErr) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callbackName) }) + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Settings: `{"clients":[{"email":"keep@example.test","enable":true}]}`, + ClientStats: []xray.ClientTraffic{{Email: keepEmail, Enable: true, Up: 160}}, + }}} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); !errors.Is(err, writeErr) { + t.Fatalf("merge error = %v, want %v", err, writeErr) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("rollback left %d links, want 2 (%v)", links, err) + } + if mark := readOrphanMark(t, db, "detached@example.test"); mark != 0 { + t.Fatalf("rollback left orphan mark %d", mark) + } + var inbound model.Inbound + if err := db.First(&inbound, oldInbound.Id).Error; err != nil { + t.Fatal(err) + } + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", nodeID, keepEmail).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + if inbound.Settings != oldInbound.Settings || baseline.Up != 100 || readTraffic(t, db, keepEmail).Up != 100 { + t.Fatalf("rollback leaked snapshot settings, counters or baseline: settings=%s baseline=%+v", inbound.Settings, baseline) + } +} + +func isolateNodeReconciliationDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("node_reconciliation") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +} + +func TestNodeFullReconciliationKeepsConcurrentCommentPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires concurrent PostgreSQL writes") + } + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "comment-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + const email = "comment@example.test" + const tag = "remote-comment" + svc := &InboundService{} + syncNodeWithSettings(t, svc, node.Id, tag, clientsSettings(t, []model.Client{{Email: email, Enable: true, Comment: "old note"}})) + + read, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + var gate sync.Once + var wg sync.WaitGroup + const hook = "test:comment-after-reconcile-read" + if err := db.Callback().Update().Before("gorm:update").Register(hook, func(tx *gorm.DB) { + row, ok := tx.Statement.Dest.(*model.ClientRecord) + if ok && row.Email == email && row.LimitIP == 3 { + gate.Do(func() { close(read); <-release }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + unblock() + wg.Wait() + _ = db.Callback().Update().Remove(hook) + }) + + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Protocol: model.VLESS, + Settings: clientsSettings(t, []model.Client{{Email: email, Enable: true, LimitIP: 3, Comment: "remote note"}}), + }}} + done := make(chan error, 1) + wg.Go(func() { + _, err := svc.SetRemoteTraffic(node.Id, snap, false, false) + done <- err + }) + select { + case <-read: + case err := <-done: + t.Fatalf("reconciliation never reached the client write barrier: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("blocked before reaching the client write barrier") + } + + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + if err := db.WithContext(ctx).Model(&model.ClientRecord{}).Where("email = ?", email). + UpdateColumn("comment", "concurrent master note").Error; err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil { + t.Fatal(err) + } + if row.Comment != "concurrent master note" || row.LimitIP != 3 { + t.Fatalf("reconciliation lost the note or did not apply the remote edit: comment=%q limitIP=%d", row.Comment, row.LimitIP) + } +} + +func TestNodeFullReconciliationExcludesRolledBackDetaches(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "savepoint-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + svc := &InboundService{} + const rejectedTag = "rejected-inbound" + const acceptedTag = "accepted-inbound" + const rejectedEmail = "rejected@example.test" + const removedEmail = "removed@example.test" + keep := model.Client{Email: "keep@example.test", Enable: true} + initial := func(tag, email string, port int) *model.Inbound { + return &model.Inbound{ + Tag: tag, Port: port, Protocol: model.VLESS, Enable: true, + Settings: clientsSettings(t, []model.Client{keep, {Email: email, Enable: true}}), + } + } + original := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + initial(rejectedTag, rejectedEmail, 41010), initial(acceptedTag, removedEmail, 41011), + }} + if _, err := svc.SetRemoteTraffic(node.Id, original, false, false); err != nil { + t.Fatal(err) + } + var rejected model.Inbound + if err := db.Where("tag = ?", rejectedTag).Take(&rejected).Error; err != nil { + t.Fatal(err) + } + const hook = "test:reject-detach-after-delete" + rejectedDelete := false + if err := db.Callback().Delete().After("gorm:delete").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "client_inbounds" && len(tx.Statement.Vars) > 0 && + tx.Statement.Vars[0] == rejected.Id && tx.RowsAffected == 1 { + rejectedDelete = true + _ = tx.AddError(errors.New("injected failure after link deletion")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Delete().Remove(hook) }) + snapshot := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + {Tag: rejectedTag, Port: 41010, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + {Tag: acceptedTag, Port: 41011, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + }} + if _, err := svc.SetRemoteTraffic(node.Id, snapshot, false, false); err != nil { + t.Fatal(err) + } + if !rejectedDelete || readOrphanMark(t, db, rejectedEmail) != 0 || readOrphanMark(t, db, removedEmail) == 0 { + t.Fatalf("savepoint did not isolate orphan candidates: injected=%v", rejectedDelete) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", rejected.Id).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("failed reconciliation did not restore its two memberships: %d (%v)", links, err) + } +}