From 4b36cc1635fb62154756a99b3f0bbd1a7ec22484 Mon Sep 17 00:00:00 2001 From: Hamed Date: Tue, 24 Nov 2026 14:52:53 +0330 Subject: [PATCH] perf(traffic): find globally depleted clients with one set query (#7021) On a node that a master pushes cross-panel usage to, the 5-second traffic job looked up client_global_traffics once per enabled client to decide who to disable, and its freshness probe counted every fresh row (#7008). The scan of all enabled clients now builds the over-quota ids once and matches them with IN, and the probe is an EXISTS that stops at the first fresh row. Who gets disabled is unchanged: same 24-hour window, one master must reach the quota, masters are never summed. The email-scoped callers keep the correlated predicate. The Postgres job runs the four semantic tests. --- .github/workflows/ci.yml | 10 + internal/web/service/client_paging.go | 6 +- internal/web/service/depletion_query_test.go | 208 ++++++++++++++++++ internal/web/service/inbound_disable.go | 33 +-- .../web/service/inbound_traffic_global.go | 14 +- 5 files changed, 249 insertions(+), 22 deletions(-) create mode 100644 internal/web/service/depletion_query_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e17f1eb25..c856c11ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,6 +114,16 @@ jobs: exit 1 fi + - name: PostgreSQL depletion query regressions + run: | + set -o pipefail + go test ./internal/web/service -run '^TestDepletionQuery(Semantics|FreshnessAndReset|ConcurrentCommit|Renewals)$' -count=1 -v | tee /tmp/postgres-depletion-query.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-depletion-query.log || true) + if [ "$passed" -ne 4 ]; then + echo "expected 4 passing PostgreSQL depletion tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL deferred-commit test run: | set -o pipefail diff --git a/internal/web/service/client_paging.go b/internal/web/service/client_paging.go index e4a28333a..8c3c0e55f 100644 --- a/internal/web/service/client_paging.go +++ b/internal/web/service/client_paging.go @@ -186,11 +186,7 @@ func newClientQuery(db *gorm.DB, nowMs, expireDiffMs, trafficDiffBytes int64) cl usedExpr: "(COALESCE(ct.up, 0) + COALESCE(ct.down, 0))", } freshSince := globalTrafficFreshSince(db.NowFunc()) - var probe int64 - err := db.Model(&model.ClientGlobalTraffic{}). - Where("updated_at >= ?", freshSince). - Limit(1).Count(&probe).Error - if err != nil || probe == 0 { + if !hasFreshGlobalTraffic(db, freshSince) { return q } // A master still pushes cross-panel usage here, so the predicates have to diff --git a/internal/web/service/depletion_query_test.go b/internal/web/service/depletion_query_test.go new file mode 100644 index 000000000..04f4d2647 --- /dev/null +++ b/internal/web/service/depletion_query_test.go @@ -0,0 +1,208 @@ +package service + +import ( + "fmt" + "slices" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/xray" + + "gorm.io/gorm" +) + +func depletedEmailsForTest(t *testing.T, db *gorm.DB, enabled bool) []string { + t.Helper() + cond, args := depletedCondWithGlobal(db, depletedClientsScanCond) + var emails []string + if err := db.Model(&xray.ClientTraffic{}).Where(cond, args...).Where("enable = ?", enabled).Order("email").Pluck("email", &emails).Error; err != nil { + t.Fatal(err) + } + return emails +} + +// The same tests run on SQLite by default and on PostgreSQL with XUI_DB_TYPE +// and XUI_DB_DSN. The existing helper gives PostgreSQL a disposable schema. +func TestDepletionQuerySemantics(t *testing.T) { + db := initGlobalHeartbeatDB(t) + clock := globalTrafficClock(t, db, false) + now := clock.Load() + fresh := now - globalTrafficFreshWindow.Milliseconds() + type usage struct{ up, down, at int64 } + cases := []struct { + name string + up, down, total, ends int64 + globals []usage + depleted bool + }{ + {"local equality", 40, 60, 100, 0, nil, true}, + {"local below", 40, 59, 100, 0, nil, false}, + {"expiry equality", 0, 0, 0, now, nil, true}, + {"expiry future", 0, 0, 0, now + 1, nil, false}, + {"delayed start", 0, 0, 0, -100, nil, false}, + {"unlimited", 1000, 1000, 0, 0, []usage{{1000, 1000, now}}, false}, + {"negative quota", 1000, 1000, -1, 0, []usage{{1000, 1000, now}}, false}, + {"global equality", 1, 2, 100, 0, []usage{{40, 60, now}}, true}, + {"fresh boundary", 1, 2, 100, 0, []usage{{40, 60, fresh}}, true}, + {"stale boundary", 1, 2, 100, 0, []usage{{400, 600, fresh - 1}}, false}, + {"stale high live low", 1, 2, 100, 0, []usage{{400, 600, fresh - 1}, {4, 6, now}}, false}, + {"one master exhausts", 1, 2, 100, 0, []usage{{40, 60, now}, {4, 6, now}}, true}, + {"duplicate candidates", 1, 2, 100, 0, []usage{{40, 60, now}, {60, 40, now}}, true}, + {"do not sum masters", 1, 2, 100, 0, []usage{{40, 20, now}, {20, 40, now}}, false}, + {"do not combine directions", 1, 2, 100, 0, []usage{{70, 1, now}, {1, 70, now}}, false}, + {"expiry and quota", 100, 0, 100, now, []usage{{100, 0, now}}, true}, + {"expiry with stale globals", 0, 0, 100, now, []usage{{100, 0, fresh - 1}}, true}, + } + var expectedEnabled, expectedDisabled []string + for i, tc := range cases { + for _, enabled := range []bool{true, false} { + email := fmt.Sprintf("case-%02d-enabled-%v", i, enabled) + if err := db.Create(&xray.ClientTraffic{Email: email, Enable: enabled, Up: tc.up, Down: tc.down, Total: tc.total, ExpiryTime: tc.ends}).Error; err != nil { + t.Fatal(err) + } + for j, g := range tc.globals { + if err := db.Create(&model.ClientGlobalTraffic{MasterGuid: fmt.Sprint(j), Email: email, Up: g.up, Down: g.down, UpdatedAt: g.at}).Error; err != nil { + t.Fatal(err) + } + } + if tc.depleted { + if enabled { + expectedEnabled = append(expectedEnabled, email) + } else { + expectedDisabled = append(expectedDisabled, email) + } + } + t.Logf("%s: %s depleted=%v", email, tc.name, tc.depleted) + } + } + for _, enabled := range []bool{true, false} { + want := expectedEnabled + if !enabled { + want = expectedDisabled + } + if got := depletedEmailsForTest(t, db, enabled); !slices.Equal(got, want) { + t.Fatalf("enabled=%v got=%v want=%v", enabled, got, want) + } + } + // Exercise the real disable path and repeated empty-result polls. Existing + // disabled clients are excluded; duplicate masters must not duplicate writes. + for poll := range 5 { + var count int64 + if err := db.Transaction(func(tx *gorm.DB) error { + _, n, _, err := (&InboundService{}).disableInvalidClients(tx, newTrafficMutationBatch()) + count = n + return err + }); err != nil { + t.Fatal(err) + } + want := int64(0) + if poll == 0 { + want = int64(len(expectedEnabled)) + } + if count != want { + t.Fatalf("poll %d disabled %d want %d", poll, count, want) + } + } +} + +func TestDepletionQueryFreshnessAndReset(t *testing.T) { + db := initGlobalHeartbeatDB(t) + clock := globalTrafficClock(t, db, true) + seedClientRow(t, "quota", 1, 1, 2, 100) + assertDepleted := func(want bool) { + t.Helper() + got := depletedEmailsForTest(t, db, true) + if (len(got) == 1) != want { + t.Fatalf("depleted=%v want %v", got, want) + } + } + assertDepleted(false) // empty; no freshness decision is cached + for _, up := range []int64{99, 100, 1, 0, 100} { + pushGlobalTraffic(t, "master", &xray.ClientTraffic{Email: "quota", Up: up}) + assertDepleted(up >= 100) + } + clock.Add(globalTrafficFreshWindow.Milliseconds()) + assertDepleted(true) // inclusive 24h + clock.Add(1) + assertDepleted(false) + // Same counters, fresh idle heartbeat: the next poll must enforce again. + pushGlobalTraffic(t, "master", &xray.ClientTraffic{Email: "quota", Up: 100}) + assertDepleted(true) + if _, count, _, err := (&InboundService{}).disableInvalidClients(db, newTrafficMutationBatch()); err != nil || count != 1 { + t.Fatalf("disable count=%d err=%v", count, err) + } + pushGlobalTraffic(t, "master", &xray.ClientTraffic{Email: "quota"}) + if got := readTraffic(t, db, "quota"); got.Enable || got.Up != 1 || got.Down != 2 { + t.Fatalf("reset must not re-enable a disabled client or overwrite local counters: %+v", got) + } +} + +func TestDepletionQueryConcurrentCommit(t *testing.T) { + db := initGlobalHeartbeatDB(t) + clock := globalTrafficClock(t, db, false) + seedClientRow(t, "concurrent", 1, 1, 2, 100) + pushGlobalTraffic(t, "master", &xray.ClientTraffic{Email: "concurrent", Up: 1}) + for _, tc := range []struct { + up int64 + before, after bool + }{{100, false, true}, {0, true, false}} { + written, release := make(chan struct{}), make(chan struct{}) + result := make(chan error, 1) + go func() { + result <- db.Transaction(func(tx *gorm.DB) error { + if err := tx.Model(&model.ClientGlobalTraffic{}).Where("email = ?", "concurrent").Updates(map[string]any{"up": tc.up, "updated_at": clock.Load()}).Error; err != nil { + return err + } + close(written) + <-release + return nil + }) + }() + select { + case <-written: + case err := <-result: + t.Fatalf("writer before query: %v", err) + case <-time.After(10 * time.Second): + close(release) + t.Fatal("writer did not reach commit barrier") + } + // Release the writer even if a reader assertion fails. + func() { + defer close(release) + if got := len(depletedEmailsForTest(t, db, true)) == 1; got != tc.before { + t.Errorf("uncommitted global visible: depleted=%v want %v", got, tc.before) + } + }() + if err := <-result; err != nil { + t.Fatal(err) + } + if got := len(depletedEmailsForTest(t, db, true)) == 1; got != tc.after { + t.Fatalf("committed change not visible on next poll: depleted=%v want %v", got, tc.after) + } + } +} + +// Reuse the lifecycle regression fixtures on both backends. In particular a +// capped catch-up must retain global usage, while a real renewal must clear it. +func TestDepletionQueryRenewals(t *testing.T) { + for _, tc := range []struct { + name string + run func(*testing.T) + }{ + {"automatic renewal", TestAutoRenewClients_RenewedClientLosesCrossPanelTraffic}, + {"capped renewal", TestAutoRenewClients_TruncatedCatchUpKeepsCrossPanelTraffic}, + {"manual quota extension", TestBulkAdjust_ReenablesOverQuota_WhenAddBytesClearsQuota}, + {"manually disabled", TestBulkAdjust_DoesNotReenable_ManuallyDisabledNotDepleted}, + } { + t.Run(tc.name, func(t *testing.T) { + cleanup, err := testpg.IsolatePackage("depletion_renewal") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + tc.run(t) + }) + } +} diff --git a/internal/web/service/inbound_disable.go b/internal/web/service/inbound_disable.go index 32ad298dd..cf99faa0a 100644 --- a/internal/web/service/inbound_disable.go +++ b/internal/web/service/inbound_disable.go @@ -79,32 +79,39 @@ const depletedClientsCond = `((total > 0 AND up + down >= total) AND g.up + g.down >= client_traffics.total )))` -// depletedClientsCondLocal is depletedClientsCond without the cross-panel -// client_global_traffics check. The EXISTS branch is a correlated subquery that -// turns every traffic poll into a full client_traffics scan; on a panel no -// master pushes to (the common case) client_global_traffics is empty, so the -// branch can never match and is pure CPU cost (#5392). Placeholders: now. +// depletedClientsScanCond is depletedClientsCond for the scan of every enabled client: +// one set of over-quota ids, not a lookup per row; masters are never summed (#7008). +const depletedClientsScanCond = `((total > 0 AND up + down >= total) + OR (expiry_time > 0 AND expiry_time <= ?) + OR id IN ( + SELECT c.id FROM client_traffics c + JOIN client_global_traffics g ON g.email = c.email + WHERE c.total > 0 AND g.updated_at >= ? AND g.up + g.down >= c.total + ))` + +// depletedClientsCondLocal drops the client_global_traffics check, which cannot match +// on a panel no master pushes to (the common case, #5392). Placeholders: now. const depletedClientsCondLocal = `((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?))` // depletedCond includes cross-panel quota usage only while a master's row is fresh. -// Without fresh global rows, the local-only predicate avoids a correlated EXISTS scan. +// Without fresh global rows, the local-only predicate skips global lookups. func depletedCond(tx *gorm.DB) (string, []any) { + return depletedCondWithGlobal(tx, depletedClientsCond) +} + +func depletedCondWithGlobal(tx *gorm.DB, globalCond string) (string, []any) { now := tx.NowFunc() freshSince := globalTrafficFreshSince(now) - var probe int64 - err := tx.Model(&model.ClientGlobalTraffic{}). - Where("updated_at >= ?", freshSince). - Limit(1).Count(&probe).Error - if err == nil && probe > 0 { - return depletedClientsCond, []any{now.UnixMilli(), freshSince} + if hasFreshGlobalTraffic(tx, freshSince) { + return globalCond, []any{now.UnixMilli(), freshSince} } return depletedClientsCondLocal, []any{now.UnixMilli()} } func (s *InboundService) disableInvalidClients(tx *gorm.DB, mutationBatch *trafficMutationBatch) (bool, int64, []int, error) { now := time.Now().UnixMilli() - cond, condArgs := depletedCond(tx) + cond, condArgs := depletedCondWithGlobal(tx, depletedClientsScanCond) var depletedRows []xray.ClientTraffic err := tx.Model(xray.ClientTraffic{}). diff --git a/internal/web/service/inbound_traffic_global.go b/internal/web/service/inbound_traffic_global.go index 55fd08ffd..d3e8261cd 100644 --- a/internal/web/service/inbound_traffic_global.go +++ b/internal/web/service/inbound_traffic_global.go @@ -15,6 +15,15 @@ import ( const globalTrafficHeartbeatInterval = time.Hour +// hasFreshGlobalTraffic stops at the first fresh row; COUNT with LIMIT still counted them all. +// It probes on every call so a new push or a stale master takes effect at once. +func hasFreshGlobalTraffic(db *gorm.DB, freshSince int64) bool { + var fresh bool + err := db.Raw("SELECT EXISTS (SELECT 1 FROM client_global_traffics WHERE updated_at >= ?)", freshSince). + Scan(&fresh).Error + return err == nil && fresh +} + // AcceptGlobalTraffic overwrites hosted clients' per-master usage, including lower resets. // Identical usage refreshes hourly; client_traffics remains local-only for delta accounting. func (s *InboundService) AcceptGlobalTraffic(masterGuid string, traffics []*xray.ClientTraffic) error { @@ -114,10 +123,7 @@ func overlayGlobalTraffic(db *gorm.DB, rows []*xray.ClientTraffic) { } freshSince := globalTrafficFreshSince(db.NowFunc()) // Cheap short-circuit for the common case (a panel no master pushes to). - var probe int64 - if err := db.Model(&model.ClientGlobalTraffic{}). - Where("updated_at >= ?", freshSince). - Limit(1).Count(&probe).Error; err != nil || probe == 0 { + if !hasFreshGlobalTraffic(db, freshSince) { return }