perf(nodes): scope expiry repair to activated clients (#7241)

Every node snapshot merge ran a table-wide UPDATE that copies a node-activated deadline onto client records still holding the start-after-first-use duration, whether or not that snapshot activated anyone.

A merge now repairs only the clients it activated or renewed in that tick, and a snapshot with no such transition issues no UPDATE. Older drift (legacy imports, a tick whose client reconciliation was skipped) is repaired by the five-minute maintenance job in windows of 4,000 client ids, which also covers standalone panels. A failed repair now fails the merge on SQLite as it always did on PostgreSQL, where the transaction was already aborted.

Verified on SQLite and PostgreSQL 18: the previous code rewrites an unrelated client's expiry on every merge, and without the scoped lift a record on a tick that cannot rebuild client records keeps its negative duration.

Fixes #7233
This commit is contained in:
Hamed
2026-11-29 18:12:13 +03:30
committed by GitHub
parent b1cec64b18
commit be2a2e9e71
4 changed files with 174 additions and 13 deletions
+1 -1
View File
@@ -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 |
+9 -3
View File
@@ -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 {
+30 -9
View File
@@ -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 {
@@ -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)
}
}