diff --git a/docs/architecture.md b/docs/architecture.md index 22cf83c74..06e27193c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -418,7 +418,7 @@ All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` me | `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds | | `@every 10s` | `amneziawg_job` | Reconcile embedded AmneziaWG interfaces against enabled local inbounds | | `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs | -| `@every 5m` | `reap_sync_orphans_job` | Delete sync-orphaned clients, then the history of emails no client holds | +| `@every 5m` | `reap_sync_orphans_job` | Repair legacy activation expiries, then reap sync orphans and unowned history | | `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB | | `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets | | `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets | diff --git a/internal/web/job/reap_sync_orphans_job.go b/internal/web/job/reap_sync_orphans_job.go index 97f1809ed..45384ec78 100644 --- a/internal/web/job/reap_sync_orphans_job.go +++ b/internal/web/job/reap_sync_orphans_job.go @@ -5,10 +5,11 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/web/service" ) -// ReapSyncOrphansJob hard-deletes the clients the node-snapshot sweep only soft-orphaned, -// then the usage and change history of every email no client holds any more. +// ReapSyncOrphansJob repairs legacy activation expiry drift in bounded windows, then reaps +// sync-orphaned clients and the history of emails no client holds. type ReapSyncOrphansJob struct { - clientService service.ClientService + clientService service.ClientService + activationCursor int } func NewReapSyncOrphansJob() *ReapSyncOrphansJob { @@ -16,6 +17,11 @@ func NewReapSyncOrphansJob() *ReapSyncOrphansJob { } func (j *ReapSyncOrphansJob) Run() { + if next, err := j.clientService.RepairClientActivationExpiries(j.activationCursor); err != nil { + logger.Warning("repair client activation expiries failed:", err) + } else { + j.activationCursor = next + } if reaped, err := j.clientService.ReapSyncOrphans(); err != nil { logger.Warning("reap sync orphans failed:", err) } else if reaped > 0 { diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6a33e5429..4f3786386 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "slices" "sort" "strings" "sync" @@ -374,13 +375,23 @@ func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, coun // liftActivatedClientRecordExpiries copies a node-activated deadline from // client_traffics onto client records still holding the negative duration (#5714). -func liftActivatedClientRecordExpiries(tx *gorm.DB) error { - return tx.Exec( - `UPDATE clients - SET expiry_time = (SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1) - WHERE clients.expiry_time < 0 - AND EXISTS (SELECT 1 FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0)`, - ).Error +func liftActivatedClientRecordExpiries(scope *gorm.DB) error { + const deadline = "SELECT ct.expiry_time FROM client_traffics ct WHERE ct.email = clients.email AND ct.expiry_time > 0 LIMIT 1" + return scope.Where("clients.expiry_time < 0 AND EXISTS ("+deadline+")"). + UpdateColumn("expiry_time", gorm.Expr("("+deadline+")")).Error +} + +// RepairClientActivationExpiries visits a bounded primary-key window for legacy drift. +func (s *ClientService) RepairClientActivationExpiries(afterID int) (int, error) { + var upperID int + err := runSerializedTx(func(tx *gorm.DB) error { + window := tx.Model(&model.ClientRecord{}).Select("id").Where("id > ?", afterID).Order("id").Limit(4000) + if err := tx.Table("(?) AS window_ids", window).Select("COALESCE(MAX(id), 0)").Scan(&upperID).Error; err != nil || upperID == 0 { + return err + } + return liftActivatedClientRecordExpiries(tx.Model(&model.ClientRecord{}).Where("id > ? AND id <= ?", afterID, upperID)) + }) + return upperID, err } // SnapshotHasUnadoptedInbounds reports whether the snapshot carries a tag with @@ -761,6 +772,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } structuralChange := false + activatedEmails := make(map[string]struct{}) adoptedSettingsChanged := false lifecycleLifted := false var sweptTags []string @@ -1173,6 +1185,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi centralCS[csKey{c.Id, cs.Email}] = row centralCSByEmail[cs.Email] = row statByEmail[cs.Email] = row + if row.ExpiryTime > 0 { + activatedEmails[row.Email] = struct{}{} + } structuralChange = true if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { return false, err @@ -1231,6 +1246,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi existing.Enable = cs.Enable existing.Total = cs.Total existing.ExpiryTime = cs.ExpiryTime + activatedEmails[cs.Email] = struct{}{} existing.Reset = cs.Reset existing.ResetDay = cs.ResetDay existing.ResetWeekday = cs.ResetWeekday @@ -1259,6 +1275,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if err := s.mergeNodeClientTraffic(tx, cs, canon, clientFrozen, deltaUp, deltaDown, now); err != nil { return false, err } + if row.ExpiryTime <= 0 && next.ExpiryTime > 0 { + activatedEmails[cs.Email] = struct{}{} + } *row = next } } @@ -1500,8 +1519,10 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - if err := liftActivatedClientRecordExpiries(tx); err != nil { - logger.Warning("setRemoteTraffic: lift activated expiries failed:", 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 + } } if err := tx.Commit().Error; err != nil { diff --git a/internal/web/service/node_client_expiry_sync_test.go b/internal/web/service/node_client_expiry_sync_test.go index 1398a6537..f2b4c1d83 100644 --- a/internal/web/service/node_client_expiry_sync_test.go +++ b/internal/web/service/node_client_expiry_sync_test.go @@ -5,6 +5,8 @@ import ( "testing" "time" + "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/web/runtime" @@ -1056,3 +1058,135 @@ func TestNodeActivationLiftsClientRecordExpiry(t *testing.T) { t.Fatalf("client record kept stale duration (#5714): expiry = %d, want %d", got, activated) } } + +func TestActivationRepairIsScoped(t *testing.T) { + testActivationRepairIsScoped(t, initTrafficTestDB(t)) +} + +func TestActivationRepairIsScopedPostgres(t *testing.T) { + testActivationRepairIsScoped(t, durablePostgresDB(t)) +} + +func TestNodeActivationRepairsExpiryWithoutClientReconciliation(t *testing.T) { + testNodeActivationRepairsExpiryWithoutClientReconciliation(t, initTrafficTestDB(t)) +} + +func TestNodeActivationRepairsExpiryWithoutClientReconciliationPostgres(t *testing.T) { + testNodeActivationRepairsExpiryWithoutClientReconciliation(t, durablePostgresDB(t)) +} + +func testNodeActivationRepairsExpiryWithoutClientReconciliation(t *testing.T, db *gorm.DB) { + t.Helper() + const duration = -60_000 + deadline := time.Now().Add(24 * time.Hour).UnixMilli() + for _, tc := range []struct { + name string + storedExpiry int64 + renewal bool + }{ + {name: "first traffic row"}, + {name: "first use", storedExpiry: duration}, + {name: "renewal", storedExpiry: deadline - time.Hour.Milliseconds(), renewal: true}, + } { + t.Run(tc.name, func(t *testing.T) { + tag := fmt.Sprintf("expiry-without-reconcile-%d", time.Now().UnixNano()) + email := tag + "@x" + node := model.Node{Name: tag, Address: "127.0.0.1", Port: 2096, Enable: true} + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + createNodeInboundWithClient(t, db, node.Id, tag, 42533, email) + if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).UpdateColumn("expiry_time", duration).Error; err != nil { + t.Fatal(err) + } + + reported := xray.ClientTraffic{Email: email, ExpiryTime: deadline, Up: 1, Enable: true} + if tc.storedExpiry != 0 { + var inbound model.Inbound + if err := db.Where("tag = ?", tag).First(&inbound).Error; err != nil { + t.Fatal(err) + } + stored := xray.ClientTraffic{Email: email, InboundId: inbound.Id, ExpiryTime: tc.storedExpiry, Enable: true} + if tc.renewal { + stored.Reset, stored.ResetCount = 30, 1 + reported.Reset, reported.ResetCount = 30, 2 + if err := db.Create(&model.NodeClientTraffic{NodeId: node.Id, Email: email}).Error; err != nil { + t.Fatal(err) + } + } + if err := db.Create(&stored).Error; err != nil { + t.Fatal(err) + } + } + + // The traffic snapshot is usable, but this settings payload cannot rebuild client records. + snapshot := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Settings: `{"clients":{}}`, ClientStats: []xray.ClientTraffic{reported}, + }}} + if _, err := (&InboundService{}).setRemoteTrafficLocked(node.Id, snapshot, false, false); err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, email) + if traffic.ExpiryTime != deadline || traffic.ResetCount != reported.ResetCount { + t.Fatalf("central traffic expiry/count = %d/%d, want %d/%d", traffic.ExpiryTime, traffic.ResetCount, deadline, reported.ResetCount) + } + var record model.ClientRecord + if err := db.Where("email = ?", email).First(&record).Error; err != nil { + t.Fatal(err) + } + if record.ExpiryTime != deadline { + t.Fatalf("client record expiry = %d, want %d", record.ExpiryTime, deadline) + } + }) + } +} + +func testActivationRepairIsScoped(t *testing.T, db *gorm.DB) { + t.Helper() + tag := fmt.Sprintf("expiry-scope-%d", time.Now().UnixNano()) + email, other := tag+"@x", tag+"-other@x" + node := &model.Node{Name: tag, Address: "127.0.0.1", Port: 2096, Enable: true} + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + createNodeInboundWithClient(t, db, node.Id, tag, 42533, email) + deadline := time.Now().Add(24 * time.Hour).UnixMilli() + const duration = -60_000 + if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).UpdateColumn("expiry_time", duration).Error; err != nil { + t.Fatal(err) + } + unrelated := &model.ClientRecord{Email: other, ExpiryTime: duration} + if err := db.Create(unrelated).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&xray.ClientTraffic{Email: other, ExpiryTime: deadline, Enable: true}).Error; err != nil { + t.Fatal(err) + } + readExpiry := func(email string) int64 { + t.Helper() + var rec model.ClientRecord + if err := db.Where("email = ?", email).First(&rec).Error; err != nil { + t.Fatal(err) + } + return rec.ExpiryTime + } + svc := &InboundService{} + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"expiryTime":%d}]}`, email, duration) + syncNodeWithSettings(t, svc, node.Id, tag, settings, xray.ClientTraffic{Email: email, ExpiryTime: duration, Enable: true}) + syncNodeWithSettings(t, svc, node.Id, tag, settings, xray.ClientTraffic{Email: email, ExpiryTime: deadline, Up: 1, Enable: true}) + if got := readExpiry(email); got != deadline { + t.Fatalf("activated expiry = %d, want %d", got, deadline) + } + if got := readExpiry(other); got != duration { + t.Fatalf("merge changed unrelated expiry to %d", got) + } + + // Start at the preceding primary key so it is covered even on a large database. + next, err := (&ClientService{}).RepairClientActivationExpiries(unrelated.Id - 1) + if err != nil || next < unrelated.Id { + t.Fatalf("repair cursor = %d, err = %v", next, err) + } + if got := readExpiry(other); got != deadline { + t.Fatalf("repaired expiry = %d, want %d", got, deadline) + } +}