diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..2e83d681e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,6 +214,16 @@ jobs: exit 1 fi + - name: PostgreSQL node merge contention + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeMerge(LetsSubscriptionTouchDuringClientReconciliationPostgres|BatchesBaselinesForActiveClients)$' -count=1 -v | tee /tmp/postgres-node-merge-contention.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-merge-contention.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL node merge contention tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6f855bda0..5ca1f4bc8 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -248,19 +248,48 @@ type nodeTrafficCounter struct { Down int64 } -func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, counter nodeTrafficCounter, dippedWhileFrozen bool) error { +func upsertNodeBaselines(tx *gorm.DB, changes map[string]model.NodeClientTraffic) error { + if len(changes) == 0 { + return nil + } + rows := make([]model.NodeClientTraffic, 0, len(changes)) + for _, email := range slices.Sorted(maps.Keys(changes)) { + rows = append(rows, changes[email]) + } return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, DoUpdates: clause.AssignmentColumns([]string{"up", "down", "dipped_while_frozen"}), - }).Create(&model.NodeClientTraffic{ - NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dippedWhileFrozen, - }).Error + }).CreateInBatches(rows, sqliteMaxVars/6).Error } -// mergeNodeClientTraffic folds one node-reported client into its central row. -// While frozen (a push pending or just landed) only the counters may move. -func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraffic, canon nodeTrafficCounter, frozen bool, deltaUp, deltaDown, now int64) error { - if frozen { +type nodeClientTrafficWrite struct { + stats xray.ClientTraffic + canon nodeTrafficCounter + deltaUp, deltaDown int64 + frozen, renewed bool +} + +// apply folds a planned change into the existing counter row without touching last_sub_fetch. +func (write nodeClientTrafficWrite) apply(tx *gorm.DB, now int64) error { + cs, canon := write.stats, write.canon + if write.renewed { + if err := tx.Exec( + fmt.Sprintf( + `UPDATE client_traffics + SET up = ?, down = ?, enable = ?, total = ?, + expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s + WHERE email = ?`, + database.GreatestExpr("last_online", "?"), + ), + canon.Up, canon.Down, cs.Enable, cs.Total, + cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, + cs.LastOnline, cs.Email, + ).Error; err != nil { + return err + } + return clearGlobalTraffic(tx, cs.Email) + } + if write.frozen { return tx.Exec( fmt.Sprintf( `UPDATE client_traffics @@ -270,7 +299,7 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClampedAddExpr("down"), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, cs.LastOnline, cs.Email, + write.deltaUp, write.deltaDown, cs.LastOnline, cs.Email, ).Error } return tx.Exec( @@ -286,8 +315,8 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClientTrafficExpiryMergeExpr(), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, - cs.Enable, now, deltaUp, deltaDown, canon.Up, canon.Down, + write.deltaUp, write.deltaDown, + cs.Enable, now, write.deltaUp, write.deltaDown, canon.Up, canon.Down, cs.Total, cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.LastOnline, cs.Email, @@ -433,11 +462,15 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { var structuralChange bool + queuedAt := time.Now() // Node merges take the background lane: a per-client mutation the operator // is waiting on must not queue behind the next batch of 5s snapshots. err := submitTrafficWriteBackground(func() error { + started := time.Now() var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) + logger.Debugf("node traffic writer: node_id=%d queue_wait_ms=%d writer_ms=%d success=%t", + nodeID, started.Sub(queuedAt).Milliseconds(), time.Since(started).Milliseconds(), inner == nil) return inner }) if err != nil { @@ -793,18 +826,27 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + var claimInputs nodeClaimInputs + if !skipStructure { + claimInputs = readNodeClaimInputs(snap) + } + txStarted := time.Now() tx := db.Begin() + if tx.Error != nil { + return false, tx.Error + } committed := false defer func() { if !committed { tx.Rollback() + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=false", nodeID, time.Since(txStarted).Milliseconds()) } }() claims := &nodeClientClaims{} rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds)) if !skipStructure { - claims, err = loadNodeClientClaims(tx, nodeID, snap) + claims, err = loadNodeClientClaims(tx, nodeID, claimInputs) if err != nil { return false, err } @@ -1167,6 +1209,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + baselineChanges := make(map[string]model.NodeClientTraffic) + var trafficWrites []nodeClientTrafficWrite + stageBaseline := func(email string, counter nodeTrafficCounter, dipped bool) { + baselineChanges[email] = model.NodeClientTraffic{ + NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dipped, + } + nodeBaselines[email] = counter + if dipped { + dippedWhileFrozen[email] = true + } else { + delete(dippedWhileFrozen, email) + } + } for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1260,11 +1315,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi activatedEmails[row.Email] = struct{}{} } structuralChange = true - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - delete(dippedWhileFrozen, cs.Email) + stageBaseline(cs.Email, canon, false) continue } @@ -1295,23 +1346,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if renewed { // A renewal starts a fresh quota window: adopt the node's counters // and enable state, drop stale pushes (mirrors autoRenewClients). - if err := tx.Exec( - fmt.Sprintf( - `UPDATE client_traffics - SET up = ?, down = ?, enable = ?, total = ?, - expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s - WHERE email = ?`, - database.GreatestExpr("last_online", "?"), - ), - canon.Up, canon.Down, cs.Enable, cs.Total, - cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, - cs.LastOnline, cs.Email, - ).Error; err != nil { - return false, err - } - if err := clearGlobalTraffic(tx, cs.Email); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{stats: cs, canon: canon, renewed: true}) existing.Up = canon.Up existing.Down = canon.Down existing.Enable = cs.Enable @@ -1343,9 +1378,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A multi-attached client is reported once per inbound and an idle one // every tick: rewriting an unchanged row only holds its lock longer. if next != *row { - if err := s.mergeNodeClientTraffic(tx, cs, canon, clientFrozen, deltaUp, deltaDown, now); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{ + stats: cs, canon: canon, frozen: clientFrozen, deltaUp: deltaUp, deltaDown: deltaDown, + }) if row.ExpiryTime <= 0 && next.ExpiryTime > 0 { activatedEmails[cs.Email] = struct{}{} } @@ -1358,15 +1393,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if seen && base == canon && stillOwed == dippedWhileFrozen[cs.Email] { continue } - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, stillOwed); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - if stillOwed { - dippedWhileFrozen[cs.Email] = true - } else { - delete(dippedWhileFrozen, cs.Email) - } + stageBaseline(cs.Email, canon, stillOwed) } if skipStructure { @@ -1509,7 +1536,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi adoptedSettings := p.wireSettings liftChanged := false if adopt && !isNew { - // Use the traffic deltas just applied to this transaction (#6228). + // Use the staged traffic values before flushing their SQL updates (#6228). if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { adoptedSettings, liftChanged = lifted, true } @@ -1595,6 +1622,16 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + if err := upsertNodeBaselines(tx, baselineChanges); err != nil { + return false, err + } + // Client reconciliation used the planned traffic values in memory. Lock + // the existing traffic rows only now, in snapshot order, before commit. + for _, write := range trafficWrites { + if err := write.apply(tx, now); err != nil { + return false, err + } + } for _, emails := range chunkStrings(slices.Sorted(maps.Keys(activatedEmails)), sqlInChunk) { if err := liftActivatedClientRecordExpiries(tx.Model(&model.ClientRecord{}).Where("email IN ?", emails)); err != nil { return false, err @@ -1605,6 +1642,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi return false, err } committed = true + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=true", nodeID, time.Since(txStarted).Milliseconds()) if adoptedSettingsChanged { InvalidateSubData() } diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 1e655a591..248a587c9 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -39,17 +39,20 @@ var nodeKeptSharedKeys = []string{"flow", "privateKey", "publicKey", "allowedIPs type clientLinkScope struct{ here, elsewhere bool } -func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot) (*nodeClientClaims, error) { - claims := &nodeClientClaims{ - refused: map[string]string{}, - shared: map[string]*model.ClientRecord{}, - storedSubID: map[string]string{}, - usageOnly: map[string]struct{}{}, +type nodeClaimInputs struct { + subIDByEmail map[string]string + refused map[string]string + sharesSubID map[string]struct{} +} + +func readNodeClaimInputs(snap *runtime.TrafficSnapshot) nodeClaimInputs { + inputs := nodeClaimInputs{ + subIDByEmail: map[string]string{}, + refused: map[string]string{}, + sharesSubID: map[string]struct{}{}, } - subIDByEmail := map[string]string{} // A subId selects a whole subscription, so within one snapshot it may name one client only. firstEmailBySub := map[string]string{} - sharesSubID := map[string]struct{}{} for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -64,28 +67,38 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot continue } if c.Email != strings.TrimSpace(c.Email) { - claims.refused[c.Email] = "its email carries surrounding white space" + inputs.refused[c.Email] = "its email carries surrounding white space" continue } - if _, seen := subIDByEmail[c.Email]; !seen { + if _, seen := inputs.subIDByEmail[c.Email]; !seen { var subID string _ = json.Unmarshal(c.SubID, &subID) - subIDByEmail[c.Email] = subID + inputs.subIDByEmail[c.Email] = subID if first, taken := firstEmailBySub[subID]; subID != "" && taken && !strings.EqualFold(first, c.Email) { - sharesSubID[c.Email] = struct{}{} + inputs.sharesSubID[c.Email] = struct{}{} } else if subID != "" && !taken { firstEmailBySub[subID] = c.Email } } } } - if len(subIDByEmail) == 0 { + return inputs +} + +func loadNodeClientClaims(tx *gorm.DB, nodeID int, inputs nodeClaimInputs) (*nodeClientClaims, error) { + claims := &nodeClientClaims{ + refused: inputs.refused, + shared: map[string]*model.ClientRecord{}, + storedSubID: map[string]string{}, + usageOnly: map[string]struct{}{}, + } + if len(inputs.subIDByEmail) == 0 { logRefusedClaims(nodeID, claims.refused) return claims, nil } - reported := make([]string, 0, len(subIDByEmail)) - for email := range subIDByEmail { + reported := make([]string, 0, len(inputs.subIDByEmail)) + for email := range inputs.subIDByEmail { reported = append(reported, email) } // SQLite's LOWER folds ASCII only, so a non-ASCII capital is matched by its spellings too. @@ -104,8 +117,8 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot byLower[strings.ToLower(records[i].Email)] = records[i].Email } - subIDs := make([]string, 0, len(subIDByEmail)) - for _, subID := range subIDByEmail { + subIDs := make([]string, 0, len(inputs.subIDByEmail)) + for _, subID := range inputs.subIDByEmail { if subID != "" { subIDs = append(subIDs, subID) } @@ -132,7 +145,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot holdersBySub[h.SubID] = append(holdersBySub[h.SubID], h) } subIDTaken := func(email, subID string) bool { - if _, shared := sharesSubID[email]; shared { + if _, shared := inputs.sharesSubID[email]; shared { return true } for _, h := range holdersBySub[subID] { @@ -143,7 +156,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot return false } - for email, subID := range subIDByEmail { + for email, subID := range inputs.subIDByEmail { rec, exact := byEmail[email] if !exact { if _, variant := byLower[strings.ToLower(email)]; variant { diff --git a/internal/web/service/node_merge_contention_test.go b/internal/web/service/node_merge_contention_test.go new file mode 100644 index 000000000..b5721132b --- /dev/null +++ b/internal/web/service/node_merge_contention_test.go @@ -0,0 +1,172 @@ +package service + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "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/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "contention.db")) + node := &model.Node{Name: "merge-lock-window", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "subscription-touch@example.test" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"subId":"touch-sub","enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "contention", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + before := readTraffic(t, db, email) + + const touchedAt = 1730000000123 + probed := false + var probeErr error + if err := db.Callback().Update().Before("gorm:update").Register("test:touch_during_reconcile", func(tx *gorm.DB) { + if tx.Statement.Table != "clients" || probed { + return + } + probed = true + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + probeErr = db.WithContext(ctx).Transaction(func(other *gorm.DB) error { + if err := other.Exec("SET LOCAL lock_timeout = '150ms'").Error; err != nil { + return err + } + return other.Model(&xray.ClientTraffic{}). + Where("email IN (SELECT email FROM clients WHERE sub_id = ?)", "touch-sub"). + Update("last_sub_fetch", touchedAt).Error + }) + }); err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + if !probed || probeErr != nil { + t.Fatalf("subscription update during client reconciliation: probed=%t err=%v", probed, probeErr) + } + if after := readTraffic(t, db, email); after.Up != before.Up+30 || after.Total != 2000 || after.LastSubFetch != touchedAt { + t.Fatalf("merge or subscription touch lost data: before=%+v after=%+v", before, after) + } +} + +func TestNodeMergeBatchesBaselinesForActiveClients(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "batch.db")) + node := &model.Node{Name: "batch-baselines", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const clients = 24 + snapshot := func(up int64) *runtime.TrafficSnapshot { + rows := make([]xray.ClientTraffic, 0, clients) + entries := make([]model.Client, 0, clients) + for i := range clients { + email := fmt.Sprintf("batch-%d@x", i) + rows = append(rows, xray.ClientTraffic{Email: email, Enable: true, Up: up}) + entries = append(entries, model.Client{Email: email, Enable: true}) + } + return snapshotWithClients(t, "batch-baselines", clientsSettings(t, entries), rows...) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100), false, false); err != nil { + t.Fatal(err) + } + trace := &snapshotReadLog{Interface: logger.Discard} + previous := db.Logger + db.Logger = trace + t.Cleanup(func() { db.Logger = previous }) + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + writes := 0 + for _, sql := range trace.statements { + if strings.HasPrefix(strings.ToUpper(sql), "INSERT INTO") && strings.Contains(sql, "node_client_traffics") { + writes++ + } + } + if writes != 1 { + t.Errorf("baseline upserts=%d for %d changed clients, want one", writes, clients) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + var rows []model.NodeClientTraffic + if err := db.Where("node_id = ?", node.Id).Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != clients { + t.Fatalf("stored %d baselines, want %d", len(rows), clients) + } + for _, row := range rows { + if row.Up != 107 { + t.Errorf("%s baseline up=%d, want 107", row.Email, row.Up) + } + if traffic := readTraffic(t, db, row.Email); traffic.Up != 107 { + t.Errorf("%s stored up=%d, want one 7-byte delta on top of adoption", row.Email, traffic.Up) + } + } +} + +func TestNodeMergeRollsBackConfigTrafficAndBaselineOnLateWriteFailure(t *testing.T) { + if config.GetDBKind() == database.DialectPostgres { + t.Skip("uses a SQLite trigger to fail the final traffic update") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "rollback.db")) + node := &model.Node{Name: "late-traffic-rollback", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "late-traffic@x" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "late-write", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + if err := db.Exec(`CREATE TRIGGER fail_late_traffic BEFORE UPDATE OF up ON client_traffics + WHEN NEW.email = 'late-traffic@x' AND NEW.up > OLD.up + BEGIN SELECT RAISE(ABORT, 'injected late traffic failure'); END`).Error; err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err == nil || !strings.Contains(err.Error(), "injected late traffic failure") { + t.Fatalf("merge failure=%v, want triggered write failure", err) + } + assertState := func(up, quota int64) { + t.Helper() + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", node.Id, email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, email) + record := lookupClientRecord(t, email) + if baseline.Up != up || traffic.Up != up || traffic.Total != quota || record.TotalGB != quota { + t.Fatalf("inconsistent merge: baseline=%d up=%d traffic quota=%d record quota=%d", baseline.Up, traffic.Up, traffic.Total, record.TotalGB) + } + } + assertState(100, 1000) + if err := db.Exec("DROP TRIGGER fail_late_traffic").Error; err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + } + assertState(130, 2000) +}