Files
mirror-3x-ui/internal/web/service/node_merge_contention_test.go
T
Hamed bdddb08249 fix(nodes): shorten the traffic merge lock window (#7315)
Stage existing client traffic updates in snapshot order and flush them after client reconciliation to shorten PostgreSQL row-lock lifetime. Keep configuration, traffic counters, renewals and baselines atomic in the same serialized transaction, preserve concurrent last_sub_fetch updates, and retain rollback and idempotent replay semantics.

Batch baseline upserts by (node_id, email) within SQLite parameter limits. Decode snapshot claims before opening the transaction while retaining transactional ownership checks. Add debug metrics for queue wait, writer execution and transaction duration.

Validation: all 12 GitHub CI jobs passed on reviewed head 6dc504b675, including race, PostgreSQL, node and Xray E2E. PostgreSQL CI logs explicitly confirm both contention and baseline batching regressions. The author reports PostgreSQL 16/18 validation, rollback/replay coverage and a reduction from 4,187 baseline upserts to 28 in a local fixture.

Scope: this resolves the reproduced subscription row-lock window, not the full serialized writer hold, shared-client cache restriction, historical 41-second SQL tail or cross-process migration/restore deadlock. These require follow-up. No independent production measurements or successful CI run on the exact latest combined revision were verified before merge.

Refs #7305
2026-12-02 13:02:15 +03:30

173 lines
6.4 KiB
Go

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)
}