From efb6c6d5796c427cb547fecc4f2a607c36ae7009 Mon Sep 17 00:00:00 2001 From: Hamed Date: Wed, 25 Nov 2026 15:23:19 +0330 Subject: [PATCH] perf(traffic): skip unchanged client lifecycle writes (#7204) A full inbound save ran the lifecycle UPDATE on client_traffics for every client of the inbound, even when quota, expiry, renewal settings and the enable flag already matched. On PostgreSQL each of those is a new row version and WAL, on every stream-settings edit of a large inbound. Guard the same UPDATE with a NULL-safe IS DISTINCT FROM over the eight columns it assigns, so the database writes only a row that actually differs and still repairs one that drifted. The PostgreSQL CI job runs the lifecycle suite, including a row-lock check on a second connection. Closes #7202 --- .github/workflows/ci.yml | 9 + internal/web/service/bulk_clients_test.go | 2 +- .../client_traffic_lifecycle_bench_test.go | 196 +++++++++++++ .../service/client_traffic_lifecycle_test.go | 267 ++++++++++++++++++ internal/web/service/inbound_traffic.go | 11 +- 5 files changed, 480 insertions(+), 5 deletions(-) create mode 100644 internal/web/service/client_traffic_lifecycle_bench_test.go create mode 100644 internal/web/service/client_traffic_lifecycle_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08731d130..a80719556 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,15 @@ jobs: exit 1 fi + - name: PostgreSQL client traffic lifecycle edits + run: | + set -o pipefail + go test ./internal/web/service -run '^TestClientTrafficLifecyclePostgres$' -count=1 -v | tee /tmp/postgres-client-traffic-lifecycle.log + if ! grep -q -- '^--- PASS: TestClientTrafficLifecyclePostgres ' /tmp/postgres-client-traffic-lifecycle.log; then + echo "expected the PostgreSQL client traffic lifecycle suite to pass" >&2 + exit 1 + fi + - name: PostgreSQL batched stats identities run: | set -o pipefail diff --git a/internal/web/service/bulk_clients_test.go b/internal/web/service/bulk_clients_test.go index 34fba1942..085ec95f4 100644 --- a/internal/web/service/bulk_clients_test.go +++ b/internal/web/service/bulk_clients_test.go @@ -11,7 +11,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" ) -func setupBulkDB(t *testing.T) { +func setupBulkDB(t testing.TB) { t.Helper() dbDir := t.TempDir() t.Setenv("XUI_DB_FOLDER", dbDir) diff --git a/internal/web/service/client_traffic_lifecycle_bench_test.go b/internal/web/service/client_traffic_lifecycle_bench_test.go new file mode 100644 index 000000000..b33c3d7fd --- /dev/null +++ b/internal/web/service/client_traffic_lifecycle_bench_test.go @@ -0,0 +1,196 @@ +package service + +import ( + "context" + "database/sql" + "fmt" + "os" + "strings" + "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/testpg" +) + +type lifecycleBenchMetrics struct { + statements int64 + updates int64 + rows int64 + txTime time.Duration +} + +type lifecycleBenchPool struct { + *sql.DB + metrics *lifecycleBenchMetrics +} + +func (p *lifecycleBenchPool) GetDBConn() (*sql.DB, error) { return p.DB, nil } + +func (p *lifecycleBenchPool) BeginTx(ctx context.Context, opts *sql.TxOptions) (gorm.ConnPool, error) { + if p.metrics == nil { + return p.DB.BeginTx(ctx, opts) + } + start := time.Now() + tx, err := p.DB.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + return &lifecycleBenchTx{Tx: tx, start: start, metrics: p.metrics}, nil +} + +func (p *lifecycleBenchPool) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.QueryContext(ctx, query, args...) +} + +func (p *lifecycleBenchPool) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.QueryRowContext(ctx, query, args...) +} + +func (p *lifecycleBenchPool) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + if p.metrics != nil { + p.metrics.statements++ + } + return p.DB.ExecContext(ctx, query, args...) +} + +type lifecycleBenchTx struct { + *sql.Tx + start time.Time + metrics *lifecycleBenchMetrics +} + +func (t *lifecycleBenchTx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + t.metrics.statements++ + return t.Tx.QueryContext(ctx, query, args...) +} + +func (t *lifecycleBenchTx) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + t.metrics.statements++ + return t.Tx.QueryRowContext(ctx, query, args...) +} + +func (t *lifecycleBenchTx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { + t.metrics.statements++ + result, err := t.Tx.ExecContext(ctx, query, args...) + if err == nil && strings.HasPrefix(query, `UPDATE "client_traffics" SET "email"=`) { + n, err := result.RowsAffected() + if err != nil { + return result, err + } + t.metrics.updates++ + t.metrics.rows += n + } + return result, err +} + +func (t *lifecycleBenchTx) Commit() error { + err := t.Tx.Commit() + t.metrics.txTime += time.Since(t.start) + return err +} + +func BenchmarkInboundTrafficLifecycleEdit(b *testing.B) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + b.Skip("requires a dedicated disposable PostgreSQL server for WAL measurement") + } + for _, size := range []int{1000, 10000, 20000} { + b.Run(fmt.Sprint(size), func(b *testing.B) { + cleanup, err := testpg.IsolatePackage("inbound_lifecycle_bench") + if err != nil { + b.Fatal(err) + } + b.Cleanup(cleanup) + setupBulkDB(b) + db := database.GetDB() + sqlDB, err := db.DB() + if err != nil { + b.Fatal(err) + } + clients := make([]model.Client, size) + for i := range clients { + clients[i] = model.Client{ + Email: fmt.Sprintf("fixture-%05d@x", i), ID: fmt.Sprintf("00000000-0000-4000-8000-%012d", i+1), + Enable: true, TotalGB: 1 << 30, + } + } + svc := &InboundService{} + inbound := seedTrafficLifecycleInbound(b, svc, clients) + pool := &lifecycleBenchPool{DB: sqlDB} + original := db.Statement.ConnPool + db.Statement.ConnPool = pool + defer func() { db.Statement.ConnPool = original }() + for _, percent := range []int{0, 10, 100} { + b.Run(fmt.Sprintf("changed-%d", percent), func(b *testing.B) { + benchmarkTrafficLifecycleEdits(b, svc, inbound, pool, size, size*percent/100) + }) + } + }) + } +} + +func benchmarkTrafficLifecycleEdits(b *testing.B, svc *InboundService, inbound *model.Inbound, pool *lifecycleBenchPool, size, changed int) { + b.Helper() + prepare := func() { + b.Helper() + if err := database.GetDB().Exec("UPDATE client_traffics SET total = 0 WHERE id IN (SELECT id FROM client_traffics ORDER BY id LIMIT ?)", changed).Error; err != nil { + b.Fatal(err) + } + } + edit := func(remark string) { + b.Helper() + form := *inbound + form.Remark = remark + if _, _, err := svc.UpdateInbound(&form); err != nil { + b.Fatal(err) + } + } + // Warm the exact code path and then restore drift before each timed edit. + prepare() + edit("warm-up") + var totals lifecycleBenchMetrics + var walBytes int64 + iteration := 0 + b.ReportAllocs() + for b.Loop() { + b.StopTimer() + prepare() + var lsn string + if err := pool.DB.QueryRowContext(b.Context(), "SELECT pg_current_wal_insert_lsn()::text").Scan(&lsn); err != nil { + b.Fatal(err) + } + iteration++ + remark := fmt.Sprintf("edit-%d", iteration) + var metrics lifecycleBenchMetrics + pool.metrics = &metrics + b.StartTimer() + edit(remark) + b.StopTimer() + pool.metrics = nil + if metrics.txTime <= 0 || metrics.updates != int64(size) || (metrics.rows != int64(changed) && metrics.rows != int64(size)) { + b.Fatalf("inbound edit at %d/%d changed rows: %+v", changed, size, metrics) + } + var wal int64 + if err := pool.DB.QueryRowContext(b.Context(), "SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), $1::pg_lsn)::bigint", lsn).Scan(&wal); err != nil { + b.Fatal(err) + } + walBytes += wal + totals.statements += metrics.statements + totals.rows += metrics.rows + totals.txTime += metrics.txTime + b.StartTimer() + } + b.ReportMetric(float64(totals.statements)/float64(b.N), "sql/op") + b.ReportMetric(float64(totals.rows)/float64(b.N), "traffic-rows/op") + b.ReportMetric(float64(walBytes)/float64(b.N), "wal-B/op") + b.ReportMetric(float64(totals.txTime.Microseconds())/float64(b.N), "tx-us/op") +} diff --git a/internal/web/service/client_traffic_lifecycle_test.go b/internal/web/service/client_traffic_lifecycle_test.go new file mode 100644 index 000000000..f1509de16 --- /dev/null +++ b/internal/web/service/client_traffic_lifecycle_test.go @@ -0,0 +1,267 @@ +package service + +import ( + "errors" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/mattn/go-sqlite3" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "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" +) + +func TestClientTrafficLifecyclePostgres(t *testing.T) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + t.Skip("requires a disposable PostgreSQL database") + } + for _, test := range []struct { + name string + run func(*testing.T) + }{ + {"inbound save", TestInboundEditWritesOnlyDriftedTraffic}, + {"fields and errors", TestUpdateClientStatPreservesLifecycleAndCounters}, + {"row locks", checkUpdateClientStatRowLocks}, + {"one connection", TestUpdateClientTrafficsStaysOnOneConnection}, + {"rename onto existing stats", TestUpdateInboundClientRenameOntoExistingStatStaysOnOneConnection}, + {"master lifecycle", TestInboundUpdateFromMasterAppliesClientLifecycle}, + {"sibling lifecycle", TestNodeInboundPushDisablingASharedClientRemovesItFromEveryHandler}, + {"detached lifecycle", TestUpdate_NoInbound_SyncsEnforcementRow}, + {"reattachment", TestAddClientStat_MultiInboundReattachStaysIdempotent}, + } { + t.Run(test.name, func(t *testing.T) { + cleanup, err := testpg.IsolatePackage("client_traffic_lifecycle") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + test.run(t) + }) + } +} + +func execLifecycleTestSQL(t testing.TB, queries ...string) { + t.Helper() + for _, query := range queries { + if err := database.GetDB().Exec(query).Error; err != nil { + t.Fatal(err) + } + } +} + +func auditLifecycleWrites(t *testing.T) func() int64 { + t.Helper() + execLifecycleTestSQL(t, "CREATE TABLE lifecycle_write_audit (email text)") + db := database.GetDB() + if db.Name() == "postgres" { + execLifecycleTestSQL(t, `CREATE FUNCTION audit_lifecycle_write() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN INSERT INTO lifecycle_write_audit VALUES (NEW.email); RETURN NEW; END; + $$`, `CREATE TRIGGER audit_lifecycle_write AFTER UPDATE ON client_traffics + FOR EACH ROW EXECUTE FUNCTION audit_lifecycle_write()`) + } else { + execLifecycleTestSQL(t, `CREATE TRIGGER audit_lifecycle_write AFTER UPDATE ON client_traffics + BEGIN INSERT INTO lifecycle_write_audit VALUES (NEW.email); END`) + } + return func() int64 { + t.Helper() + var count int64 + if err := db.Table("lifecycle_write_audit").Count(&count).Error; err != nil { + t.Fatal(err) + } + return count + } +} + +func seedTrafficLifecycleInbound(t testing.TB, svc *InboundService, clients []model.Client) *model.Inbound { + t.Helper() + inbound, _, err := svc.AddInbound(&model.Inbound{ + UserId: 1, Tag: "lifecycle-edit", Remark: "before", Port: 43021, + Enable: true, Protocol: model.VLESS, Settings: clientsSettings(t, clients), + StreamSettings: `{"network":"tcp","security":"none"}`, + }) + if err != nil { + t.Fatal(err) + } + return inbound +} + +func TestInboundEditWritesOnlyDriftedTraffic(t *testing.T) { + setupBulkDB(t) + svc := &InboundService{} + ib := seedTrafficLifecycleInbound(t, svc, []model.Client{ + {Email: "stable@x", ID: "00000000-0000-4000-8000-000000000001", Enable: true, TotalGB: 1 << 30}, + {Email: "drifted@x", ID: "00000000-0000-4000-8000-000000000002", Enable: true, TotalGB: 2 << 30}, + }) + stable := readClientTraffic(t, "stable@x") + execLifecycleTestSQL(t, "UPDATE client_traffics SET total = 0, up = 73, down = 19, last_online = 100, reset_count = 2 WHERE email = 'drifted@x'") + drifted := readClientTraffic(t, "drifted@x") + drifted.Total = 2 << 30 + count := auditLifecycleWrites(t) + form := *ib + form.Remark = "edited" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + if got := count(); got != 1 { + t.Fatalf("row trigger fired %d times, want only the drift repair", got) + } + if got := readClientTraffic(t, stable.Email); got != stable { + t.Fatalf("identical row changed: %+v, want %+v", got, stable) + } + if got := readClientTraffic(t, drifted.Email); got != drifted { + t.Fatalf("drift repair = %+v, want %+v", got, drifted) + } + form.Remark = "edited again" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + if got := count(); got != 1 { + t.Fatalf("second edit fired additional row triggers: got %d total", got) + } + saved, err := svc.GetInbound(ib.Id) + if err != nil || saved.Remark != "edited again" { + t.Fatalf("inbound edit did not persist: %v, %v", saved, err) + } +} + +func TestUpdateClientStatPreservesLifecycleAndCounters(t *testing.T) { + setupBulkDB(t) + db := database.GetDB() + svc := &InboundService{} + count := auditLifecycleWrites(t) + for _, tc := range []struct { + name string + set func(*xray.ClientTraffic, *model.Client) + }{ + {"case-only rename", func(row *xray.ClientTraffic, c *model.Client) { c.Email = strings.ToUpper(row.Email) }}, + {"disable", func(_ *xray.ClientTraffic, c *model.Client) { c.Enable = false }}, + {"enable", func(row *xray.ClientTraffic, c *model.Client) { row.Enable, c.Enable = false, true }}, + {"clear total", func(_ *xray.ClientTraffic, c *model.Client) { c.TotalGB = 0 }}, + {"delayed expiry", func(_ *xray.ClientTraffic, c *model.Client) { c.ExpiryTime = -86400000 }}, + {"interval", func(_ *xray.ClientTraffic, c *model.Client) { c.Reset = 30 }}, + {"billing day", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetDay = 15 }}, + {"weekly day", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetWeekday = 7 }}, + {"max renewals", func(_ *xray.ClientTraffic, c *model.Client) { c.ResetMax = 4 }}, + {"repair nulls", func(_ *xray.ClientTraffic, _ *model.Client) {}}, + } { + t.Run(tc.name, func(t *testing.T) { + row := xray.ClientTraffic{ + Email: tc.name + "@x", Enable: true, Total: 1 << 30, + Up: 3, Down: 5, LastOnline: 7, LastSubFetch: 9, ResetCount: 11, InboundId: 13, + } + client := model.Client{Email: row.Email, Enable: row.Enable, TotalGB: row.Total} + tc.set(&row, &client) + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + if tc.name == "repair nulls" { + if err := db.Model(&row).Updates(map[string]any{ + "enable": nil, "total": nil, "expiry_time": nil, "reset": nil, + "reset_day": nil, "reset_weekday": nil, "reset_max": nil, + }).Error; err != nil { + t.Fatal(err) + } + } + before := count() + if err := db.Transaction(func(tx *gorm.DB) error { return svc.UpdateClientStat(tx, row.Email, &client) }); err != nil { + t.Fatal(err) + } + row.Email, row.Enable, row.Total, row.ExpiryTime = client.Email, client.Enable, client.TotalGB, client.ExpiryTime + row.Reset, row.ResetDay, row.ResetWeekday, row.ResetMax = client.Reset, client.ResetDay, client.ResetWeekday, client.ResetMax + if got := readClientTraffic(t, client.Email); got != row || count() != before+1 { + t.Fatalf("updated row = %+v, want %+v and exactly one write", got, row) + } + if tc.name == "repair nulls" { + var nulls int64 + if err := db.Model(xray.ClientTraffic{}).Where("id = ?", row.Id). + Where("(enable IS NULL OR total IS NULL OR expiry_time IS NULL OR reset IS NULL OR reset_day IS NULL OR reset_weekday IS NULL OR reset_max IS NULL)"). + Count(&nulls).Error; err != nil || nulls != 0 { + t.Fatalf("NULL repair = %d rows remain, error=%v", nulls, err) + } + } + }) + } + before := count() + if err := svc.UpdateClientStat(db, "missing@x", &model.Client{Email: "missing@x"}); err != nil || count() != before { + t.Fatalf("missing row: error=%v, writes=%d", err, count()-before) + } + invalid := xray.ClientTraffic{Email: "invalid@x", ResetWeekday: 8} + if err := db.Create(&invalid).Error; err != nil { + t.Fatal(err) + } + if err := svc.UpdateClientStat(db, invalid.Email, &model.Client{Email: invalid.Email, ResetWeekday: 8}); err == nil || + err.Error() != "client resetWeekday must be between 0 and 7, got: 8\n" || count() != before { + t.Fatalf("equal invalid row: error=%v, writes=%d", err, count()-before) + } + if err := svc.UpdateClientStat(db, "disable@x", &model.Client{Email: "enable@x"}); !lifecycleUniqueViolation(err) { + t.Fatalf("rename onto existing email: expected unique constraint error, got %v", err) + } + if got := readClientTraffic(t, "disable@x"); got.Total != 1<<30 || count() != before { + t.Fatalf("failed rename changed source: %+v", got) + } +} + +func lifecycleUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + var sqliteErr sqlite3.Error + return errors.As(err, &pgErr) && pgErr.Code == "23505" || + errors.As(err, &sqliteErr) && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique +} + +func checkUpdateClientStatRowLocks(t *testing.T) { + t.Helper() + setupBulkDB(t) + db := database.GetDB() + svc := &InboundService{} + for _, test := range []struct { + name string + total int64 + wantLocked bool + }{ + {"identical", 1000, false}, + {"changed", 2000, true}, + } { + t.Run(test.name, func(t *testing.T) { + row := xray.ClientTraffic{Email: test.name + "@x", Enable: true, Total: 1000} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + tx := db.Begin() + if tx.Error != nil { + t.Fatal(tx.Error) + } + defer func() { _ = tx.Rollback().Error }() + client := model.Client{Email: row.Email, Enable: true, TotalGB: test.total} + if err := svc.UpdateClientStat(tx, row.Email, &client); err != nil { + t.Fatal(err) + } + + // Probe on another connection while the UPDATE transaction is still open. + err := db.Transaction(func(other *gorm.DB) error { + var locked xray.ClientTraffic + return other.Clauses(clause.Locking{Strength: "UPDATE", Options: "NOWAIT"}). + Where("id = ?", row.Id).Take(&locked).Error + }) + if test.wantLocked { + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) || pgErr.Code != "55P03" { + t.Fatalf("changed update should hold a row lock (SQLSTATE 55P03), got %v", err) + } + } else if err != nil { + t.Fatalf("identical update should leave the row available, got %v", err) + } + if err := tx.Commit().Error; err != nil { + t.Fatal(err) + } + if got := readClientTraffic(t, row.Email).Total; got != test.total { + t.Fatalf("committed total = %d, want %d", got, test.total) + } + }) + } +} diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index bd3bba31a..e03458a31 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -662,8 +662,13 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod if err := validateClientRenewal(*client); err != nil { return err } - result := tx.Model(xray.ClientTraffic{}). + // Compare the persisted row atomically so an unchanged inbound can still repair drift. + return tx.Model(xray.ClientTraffic{}). Where("email = ?", email). + Where(`(email, enable, expiry_time, reset, reset_day, reset_max, reset_weekday, total) + IS DISTINCT FROM (?, ?, ?, ?, ?, ?, ?, ?)`, + client.Email, client.Enable, client.ExpiryTime, client.Reset, client.ResetDay, + client.ResetMax, client.ResetWeekday, client.TotalGB). Updates(map[string]any{ "enable": client.Enable, "email": client.Email, @@ -673,9 +678,7 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod "reset_day": client.ResetDay, "reset_weekday": client.ResetWeekday, "reset_max": client.ResetMax, - }) - err := result.Error - return err + }).Error } func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {