diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..f1792c213 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -204,6 +204,16 @@ jobs: exit 1 fi + - name: PostgreSQL node client reconciliation + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeFullReconciliation' -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 2 ]; then + echo "expected 2 passing node client reconciliation tests, got $passed" >&2 + exit 1 + fi + - 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 e457d830f..2ce9fd04c 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, wantedFlow, wantedIds, detachEmails, prune) + relinked, detached, err := s.reconcileInboundLinks(tx, inboundId, 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, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +// affected and detached client IDs. 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) (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, wanted 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, wanted // 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, wanted 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,18 +459,18 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted 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 } } - 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 6f855bda0..56d6ffa46 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1416,11 +1416,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 @@ -1432,20 +1428,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) @@ -1473,37 +1455,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 @@ -1522,13 +1477,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 @@ -1545,6 +1501,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. @@ -1553,46 +1512,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 } for _, emails := range chunkStrings(slices.Sorted(maps.Keys(activatedEmails)), sqlInChunk) { 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..d25bddba9 --- /dev/null +++ b/internal/web/service/node_full_reconciliation_test.go @@ -0,0 +1,157 @@ +package service + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + + "gorm.io/gorm" + + "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" +) + +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} + before := []model.Client{keep, move} + for i := range sqlInChunk + 3 { + before = append(before, model.Client{Email: fmt.Sprintf("drop-%04d@example.test", i), Enable: true}) + } + clientSvc := &ClientService{} + 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), + }} + 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) }) + if _, err := (&InboundService{}).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", len(before)-2, markWrites) + } + var marked []model.ClientRecord + if err := db.Where("sync_orphaned_at > 0").Find(&marked).Error; err != nil { + t.Fatal(err) + } + if len(marked) != len(before)-2 { + t.Fatalf("marked %d removed clients, want %d", len(marked), len(before)-2) + } + 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) + } +} + +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{} + syncNodeWithSettings(t, svc, nodeID, tag, `{"clients":[{"email":"keep@example.test","enable":true},{"email":"detached@example.test","enable":true}]}`) + + 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}]}`, + }}} + 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) + } +} + +func isolateNodeReconciliationDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("node_reconciliation") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +}