Files
mirror-3x-ui/internal/web/service/client_sync_orphan_test.go
T
Hamed b1cec64b18 perf(nodes): target orphan recovery during client reconciliation (#7240)
Every node snapshot merge ran a clear-orphan-marks UPDATE over the whole clients table, marked rows or not. On a PostgreSQL master with thousands of clients that was a full scan every five seconds per node, inside the single serialized writer.

A merge now clears marks only for the clients it reconciled, and an unchanged snapshot issues no orphan statement at all. Marks left on still-attached clients by older builds, restores or imports are repaired by the existing five-minute reaper, in the same transaction that decides what to delete, and a client that loses its last link has its stale mark cleared first so the reaper cannot delete it without a grace period.

Verified on SQLite and PostgreSQL 18: the previous code repairs an unrelated mark on every merge and reaps a legacy-marked client right after it is detached.

Fixes #7231
2026-11-29 17:55:47 +03:30

339 lines
12 KiB
Go

package service
import (
"fmt"
"strings"
"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 readOrphanMark(t *testing.T, db *gorm.DB, email string) int64 {
t.Helper()
var row model.ClientRecord
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("read client %q: %v", email, err)
}
return row.SyncOrphanedAt
}
func backdateOrphanMark(t *testing.T, db *gorm.DB, email string) {
t.Helper()
past := time.Now().Add(-2 * syncOrphanReapGrace).UnixMilli()
if err := db.Model(&model.ClientRecord{}).
Where("email = ?", email).
Update("sync_orphaned_at", past).Error; err != nil {
t.Fatalf("backdate orphan mark: %v", err)
}
}
// A partial snapshot (node alive, still serving another client) authoritatively drops one;
// the merge soft-orphans, recoverable until the grace elapses and the reaper confirms it.
func TestSyncOrphanSurvivesMergeUntilGraceElapses(t *testing.T) {
db := initTrafficTestDB(t)
svc := &InboundService{}
clientSvc := &ClientService{}
seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
const email = "gone@x"
const keep = "keep@x"
createNodeInboundWithClient(t, db, 1, "n1-in", 41001, keep)
bothSettings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true},{"email":%q,"enable":true}]}`, keep, email)
syncNodeWithSettings(t, svc, 1, "n1-in", bothSettings,
xray.ClientTraffic{Email: keep, Enable: true},
xray.ClientTraffic{Email: email, Up: 5, Down: 5, Enable: true})
if rec, traf := countClientRows(t, db, email); rec != 1 || traf != 1 {
t.Fatalf("setup: clients=%d client_traffics=%d, want 1/1", rec, traf)
}
keepOnly := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, keep)
if _, err := svc.setRemoteTrafficLocked(1, snapshotWithClients(t, "n1-in", keepOnly,
xray.ClientTraffic{Email: keep, Enable: true}), false, false); err != nil {
t.Fatalf("orphaning merge: %v", err)
}
if rec, traf := countClientRows(t, db, email); rec != 1 || traf != 1 {
t.Fatalf("merge hard-deleted the client: clients=%d client_traffics=%d, want 1/1", rec, traf)
}
if readOrphanMark(t, db, email) <= 0 {
t.Fatal("merge did not stamp sync_orphaned_at")
}
reaped, err := clientSvc.ReapSyncOrphans()
if err != nil {
t.Fatalf("reap inside grace: %v", err)
}
if reaped != 0 {
t.Fatalf("reaped %d client(s) inside the grace period, want 0", reaped)
}
if rec, _ := countClientRows(t, db, email); rec != 1 {
t.Fatal("client removed before the grace period elapsed")
}
backdateOrphanMark(t, db, email)
reaped, err = clientSvc.ReapSyncOrphans()
if err != nil {
t.Fatalf("reap after grace: %v", err)
}
if reaped != 1 {
t.Fatalf("reaped %d client(s) after the grace period, want 1", reaped)
}
rec, traf := countClientRows(t, db, email)
if rec != 0 || traf != 0 {
t.Fatalf("after reap: clients=%d client_traffics=%d, want 0/0", rec, traf)
}
}
// A client the node reports again (partial snapshot) was never gone: clearing the mark
// turns a bad merge into a recoverable blip instead of a delayed deletion.
func TestSyncOrphanMarkClearedOnReattach(t *testing.T) {
db := initTrafficTestDB(t)
svc := &InboundService{}
clientSvc := &ClientService{}
seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
const email = "flaky@x"
const keep = "keep@x"
createNodeInboundWithClient(t, db, 1, "n1-in", 41001, keep)
bothSettings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true},{"email":%q,"enable":true}]}`, keep, email)
syncNodeWithSettings(t, svc, 1, "n1-in", bothSettings,
xray.ClientTraffic{Email: keep, Enable: true},
xray.ClientTraffic{Email: email, Up: 5, Down: 5, Enable: true})
keepOnly := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, keep)
if _, err := svc.setRemoteTrafficLocked(1, snapshotWithClients(t, "n1-in", keepOnly,
xray.ClientTraffic{Email: keep, Enable: true}), false, false); err != nil {
t.Fatalf("orphaning merge: %v", err)
}
if readOrphanMark(t, db, email) <= 0 {
t.Fatal("setup: expected the merge to mark the client")
}
syncNodeWithSettings(t, svc, 1, "n1-in", bothSettings,
xray.ClientTraffic{Email: keep, Enable: true},
xray.ClientTraffic{Email: email, Up: 6, Down: 6, Enable: true})
if orphanedAt := readOrphanMark(t, db, email); orphanedAt != 0 {
t.Fatalf("re-attached client kept its orphan mark: sync_orphaned_at=%d", orphanedAt)
}
backdateOrphanMark(t, db, email)
if reaped, err := clientSvc.ReapSyncOrphans(); err != nil || reaped != 0 {
t.Fatalf("reaped %d client(s) (err=%v) that the node still reports, want 0", reaped, err)
}
}
// The reaper is scoped to the node sweep. Orphans from any other cause carry no
// mark and keep their existing manual-cleanup semantics.
func TestReapSyncOrphansIgnoresUnmarkedOrphans(t *testing.T) {
db := initTrafficTestDB(t)
clientSvc := &ClientService{}
const email = "manual@x"
rec := &model.ClientRecord{Email: email, Enable: true, UUID: "44444444-4444-4444-4444-444444444444"}
if err := db.Create(rec).Error; err != nil {
t.Fatalf("create client: %v", err)
}
reaped, err := clientSvc.ReapSyncOrphans()
if err != nil {
t.Fatalf("reap: %v", err)
}
if reaped != 0 {
t.Fatalf("reaped %d unmarked orphan(s), want 0", reaped)
}
var surviving int64
if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).Count(&surviving).Error; err != nil {
t.Fatalf("count clients: %v", err)
}
if surviving != 1 {
t.Fatalf("unmarked orphan was reaped: %d rows survive, want 1", surviving)
}
}
// With its only node silent no merge runs, so an admin's attach has to clear the mark
// itself, or the client's next detach is reaped instead of kept for manual cleanup.
func TestAdminAttachClearsSyncOrphanMark(t *testing.T) {
db := initTrafficTestDB(t)
svc := &InboundService{}
clientSvc := &ClientService{}
seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true})
const email = "rescued@x"
const keep = "keep@x"
createNodeInboundWithClient(t, db, 1, "n1-in", 41001, keep)
bothSettings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true},{"email":%q,"enable":true}]}`, keep, email)
syncNodeWithSettings(t, svc, 1, "n1-in", bothSettings,
xray.ClientTraffic{Email: keep, Enable: true},
xray.ClientTraffic{Email: email, Enable: true})
syncNodeWithSettings(t, svc, 1, "n1-in", fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, keep),
xray.ClientTraffic{Email: keep, Enable: true})
if readOrphanMark(t, db, email) <= 0 {
t.Fatal("setup: expected the merge to mark the client")
}
backdateOrphanMark(t, db, email)
master := &model.Inbound{UserId: 1, Tag: "master-in", Enable: true, Port: 40001, Protocol: model.VLESS, Settings: `{"clients":[]}`}
if err := db.Create(master).Error; err != nil {
t.Fatalf("create master inbound: %v", err)
}
if err := clientSvc.ApplyInboundClientDelta(db, master.Id, []model.Client{{Email: email, Enable: true}}, nil); err != nil {
t.Fatalf("attach: %v", err)
}
if at := readOrphanMark(t, db, email); at != 0 {
t.Fatalf("attached client kept its orphan mark: sync_orphaned_at=%d", at)
}
if err := clientSvc.ApplyInboundClientDelta(db, master.Id, nil, []string{email}); err != nil {
t.Fatalf("detach: %v", err)
}
reaped, err := clientSvc.ReapSyncOrphans()
if err != nil {
t.Fatalf("reap: %v", err)
}
if rec, _ := countClientRows(t, db, email); reaped != 0 || rec != 1 {
t.Fatalf("admin-detached client was reaped: reaped=%d clients=%d, want 0/1", reaped, rec)
}
}
func TestSyncOrphanRecoveryScope(t *testing.T) {
testSyncOrphanRecoveryScope(t, initTrafficTestDB(t))
}
func TestSyncOrphanRecoveryScopePostgres(t *testing.T) {
testSyncOrphanRecoveryScope(t, durablePostgresDB(t))
}
func TestLegacySyncOrphanMarksAcrossLinkChanges(t *testing.T) {
testLegacySyncOrphanMarksAcrossLinkChanges(t, initTrafficTestDB(t))
}
func TestLegacySyncOrphanMarksAcrossLinkChangesPostgres(t *testing.T) {
cleanup, err := testpg.IsolatePackage("legacy_sync_orphan_marks")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
testLegacySyncOrphanMarksAcrossLinkChanges(t, durablePostgresDB(t))
}
func testLegacySyncOrphanMarksAcrossLinkChanges(t *testing.T, db *gorm.DB) {
t.Helper()
clientSvc, inboundSvc := &ClientService{}, &InboundService{}
for _, action := range []string{"detach client", "delete inbound", "reattach client"} {
t.Run(action, func(t *testing.T) {
client := model.Client{Email: fmt.Sprintf("legacy-mark-%d@x", time.Now().UnixNano())}
ib := durableTestInbound(nil, client.Email, 42534)
ib.Enable = false
if action != "reattach client" {
ib.Settings = clientsSettings(t, []model.Client{client})
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
if action == "reattach client" {
record := model.ClientRecord{Email: client.Email}
if err := db.Create(&record).Error; err != nil {
t.Fatal(err)
}
} else if err := clientSvc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
backdateOrphanMark(t, db, client.Email)
switch action {
case "detach client":
if _, err := clientSvc.DetachByEmail(inboundSvc, ib.Id, client.Email); err != nil {
t.Fatal(err)
}
case "delete inbound":
if _, err := inboundSvc.DelInbound(ib.Id); err != nil {
t.Fatal(err)
}
case "reattach client":
writes := 0
const callback = "test:reattach-mark-writes"
if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) {
sql := strings.NewReplacer("`", "", "\"", "").Replace(tx.Statement.SQL.String())
if strings.Contains(sql, "SET sync_orphaned_at=") {
writes++
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
if err := clientSvc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
if writes != 1 {
t.Errorf("reattachment issued %d mark clears, want 1", writes)
}
}
if reaped, err := clientSvc.ReapSyncOrphans(); err != nil || reaped != 0 {
t.Fatalf("legacy mark after %s: reaped=%d err=%v", action, reaped, err)
}
if got := readOrphanMark(t, db, client.Email); got != 0 {
t.Fatalf("legacy mark after %s was %d, want zero", action, got)
}
})
}
}
func testSyncOrphanRecoveryScope(t *testing.T, db *gorm.DB) {
t.Helper()
suffix := time.Now().UnixNano()
tag, unrelatedTag := fmt.Sprintf("scope-node-%d", suffix), fmt.Sprintf("scope-local-%d", suffix)
email, otherEmail := tag+"@x", unrelatedTag+"@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, 42531, email)
createNodeInboundWithClient(t, db, node.Id+10000, unrelatedTag, 42532, otherEmail)
backdateOrphanMark(t, db, email)
backdateOrphanMark(t, db, otherEmail)
writes := 0
const callback = "test:orphan-scope"
if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) {
if strings.Contains(tx.Statement.SQL.String(), "sync_orphaned_by") && strings.Contains(tx.Statement.SQL.String(), "EXISTS") {
writes++
if !strings.Contains(tx.Statement.SQL.String(), "id IN") {
t.Error("unbounded orphan recovery update")
}
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
service := &InboundService{}
settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true}]}`, email)
syncNodeWithSettings(t, service, node.Id, tag, settings, xray.ClientTraffic{Email: email, Enable: true})
if readOrphanMark(t, db, email) != 0 {
t.Fatal("touched client still marked")
}
if readOrphanMark(t, db, otherEmail) <= 0 {
t.Fatal("merge repaired an unrelated mark")
}
writes = 0
syncNodeWithSettings(t, service, node.Id, tag, settings, xray.ClientTraffic{Email: email, Up: 1, Enable: true})
if writes != 0 {
t.Fatalf("unchanged snapshot issued %d orphan updates", writes)
}
if _, err := (&ClientService{}).ReapSyncOrphans(); err != nil {
t.Fatal(err)
}
if readOrphanMark(t, db, otherEmail) != 0 {
t.Fatal("maintenance failed to repair attached legacy mark")
}
}