mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
7a5a25fae2
Reuse client records and successful link diffs during full node snapshot reconciliation. Preserve master-owned comments on existing records while importing new comments; omit comment writes so concurrent operator updates survive. Deduplicate detached IDs across successful inbound savepoints and mark only globally unattached clients in bounded 400-ID batches inside the existing transaction; roll back on orphan-mark write failure.
Integrate against current main while preserving #7314 target-node pending-delete cancellation and cross-node recreation guarantees, #7315 staged traffic and batched baseline writes, and #7308 serialized eligibility checks. Preserve orphan recovery, degraded-inbound safeguards and idempotent snapshot replay.
Validation: all 12 CI jobs passed on 51e627739e (run 46895213148). PostgreSQL logs confirm four new reconciliation tests, both contention/baseline regressions and eight ordering/durable-delete regressions. Author reports focused SQLite/PostgreSQL 18 race tests, make verify and all four mixed-version node E2E pairings.
Author-reported controlled 4096-client PostgreSQL 18 fixture: idle SQL statements 350 -> 270, changing-counter statements 552 -> 472, rows read 151832 -> 102680. Idle writer p50/p95 490/597 -> 430/466 ms; counter writer 489/521 -> 449/519 ms. Idle cycle p50/p95 1118/1277 -> 1015/1050 ms; counter cycle 1121/1172 -> 1046/1135 ms. Worst counter cycle effectively unchanged. These fixture results are not independent production measurements. Production tail latency, shared-client compact-cache reuse and migration coordination remain separate follow-ups.
Refs #7305
337 lines
13 KiB
Go
337 lines
13 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"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/testpg"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
)
|
|
|
|
func TestNodeFullReconciliationReusesLinkDiff(t *testing.T) {
|
|
isolateNodeReconciliationDB(t)
|
|
db := initTrafficTestDB(t)
|
|
const nodeID = 1
|
|
seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true})
|
|
createNodeInbound(t, db, nodeID, "remote-first", 41001)
|
|
createNodeInbound(t, db, nodeID, "remote-second", 41002)
|
|
var inbounds []model.Inbound
|
|
if err := db.Where("node_id = ?", nodeID).Order("id").Find(&inbounds).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
keep := model.Client{Email: "keep@example.test", Enable: true, Comment: "remote comment"}
|
|
move := model.Client{Email: "move@example.test", Enable: true}
|
|
local := model.Client{Email: "still-local@example.test", Enable: true}
|
|
other := model.Client{Email: "still-on-other-node@example.test", Enable: true}
|
|
before := []model.Client{keep, move, local, other}
|
|
const dropped = sqlInChunk + 3
|
|
for i := range dropped {
|
|
before = append(before, model.Client{Email: fmt.Sprintf("drop-%04d@example.test", i), Enable: true})
|
|
}
|
|
clientSvc := &ClientService{}
|
|
localInbound := model.Inbound{UserId: 1, Tag: "local-inbound", Port: 41003, Protocol: model.VLESS, Enable: true}
|
|
if err := db.Create(&localInbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := clientSvc.SyncInbound(db, localInbound.Id, []model.Client{local}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const otherNodeID = 2
|
|
seedNodeRow(t, db, &model.Node{Id: otherNodeID, Name: "other", Address: "192.0.2.2", Port: 2053, Enable: true})
|
|
createNodeInboundWithClient(t, db, otherNodeID, "other-node-inbound", 41004, other.Email)
|
|
if err := clientSvc.SyncInbound(db, inbounds[0].Id, before); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := clientSvc.SyncInbound(db, inbounds[1].Id, []model.Client{keep}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.Model(&model.ClientRecord{}).Where("email = ?", keep.Email).
|
|
UpdateColumn("comment", "operator note").Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
keep.LimitIP = 3
|
|
last := model.Client{Email: "new@example.test", Enable: true, Comment: "imported note"}
|
|
wire := func(tag string, clients ...model.Client) *model.Inbound {
|
|
t.Helper()
|
|
raw, err := json.Marshal(map[string]any{"clients": clients})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &model.Inbound{Tag: tag, Protocol: model.VLESS, Settings: string(raw)}
|
|
}
|
|
snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
|
|
wire(inbounds[0].Tag, keep), wire(inbounds[1].Tag, keep, move, last),
|
|
}}
|
|
snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Enable: true}}
|
|
queries := recordExecutedSQL(t, db)
|
|
const updateCallback = "test:record-node-reconciliation-updates"
|
|
if err := db.Callback().Update().After("gorm:update").Register(updateCallback, func(tx *gorm.DB) {
|
|
*queries = append(*queries, tx.Statement.SQL.String())
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Callback().Update().Remove(updateCallback) })
|
|
svc := &InboundService{}
|
|
if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
markWrites := 0
|
|
for _, sql := range *queries {
|
|
stmt := strings.ToLower(sql)
|
|
if strings.HasPrefix(stmt, "select email, comment ") ||
|
|
(strings.Contains(stmt, "count(*)") && strings.Contains(stmt, "clients.email =")) {
|
|
t.Fatalf("reconciliation repeated a per-inbound comment or per-client attachment read: %s", sql)
|
|
}
|
|
if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "sync_orphaned_by") &&
|
|
strings.Contains(stmt, "not exists") {
|
|
markWrites++
|
|
}
|
|
if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "comment") {
|
|
t.Fatalf("remote reconciliation unnecessarily wrote the operator's comment: %s", sql)
|
|
}
|
|
}
|
|
if markWrites != 2 {
|
|
t.Fatalf("marked a %d-client drop in %d writes, want 2", dropped, markWrites)
|
|
}
|
|
var marked []model.ClientRecord
|
|
if err := db.Where("sync_orphaned_at > 0").Find(&marked).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(marked) != dropped {
|
|
t.Fatalf("marked %d removed clients, want %d", len(marked), dropped)
|
|
}
|
|
for _, row := range marked {
|
|
if row.SyncOrphanedBy != nodeID || !strings.HasPrefix(row.Email, "drop-") {
|
|
t.Fatalf("unexpected orphan: %q, node %d", row.Email, row.SyncOrphanedBy)
|
|
}
|
|
}
|
|
for email, want := range map[string]string{keep.Email: "operator note", last.Email: "imported note"} {
|
|
var row model.ClientRecord
|
|
if err := db.Where("email = ?", email).Take(&row).Error; err != nil || row.Comment != want {
|
|
t.Fatalf("comment for %q = %q, want %q (%v)", email, row.Comment, want, err)
|
|
}
|
|
}
|
|
var movedLinks []int
|
|
if err := db.Table("client_inbounds").Joins("JOIN clients ON clients.id = client_inbounds.client_id").
|
|
Where("clients.email = ?", move.Email).Pluck("inbound_id", &movedLinks).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(movedLinks) != 1 || movedLinks[0] != inbounds[1].Id {
|
|
t.Fatalf("move lost its destination: %v", movedLinks)
|
|
}
|
|
snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Up: 100, Down: 50, Enable: true}}
|
|
for range 2 {
|
|
if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
baseline := model.NodeClientTraffic{}
|
|
if err := db.Where("node_id = ? AND email = ?", nodeID, keep.Email).Take(&baseline).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
traffic := readTraffic(t, db, keep.Email)
|
|
if baseline.Up != 100 || baseline.Down != 50 || traffic.Up != 100 || traffic.Down != 50 {
|
|
t.Fatalf("reapplied snapshot duplicated traffic or lost the baseline: traffic=%+v baseline=%+v", traffic, baseline)
|
|
}
|
|
if got := readOrphanMark(t, db, marked[0].Email); got != marked[0].SyncOrphanedAt {
|
|
t.Fatalf("replayed snapshot changed the orphan grace timestamp to %d", got)
|
|
}
|
|
}
|
|
|
|
func TestNodeFullReconciliationRollsBackOrphanWriteFailure(t *testing.T) {
|
|
isolateNodeReconciliationDB(t)
|
|
db := initTrafficTestDB(t)
|
|
const nodeID = 1
|
|
const tag = "remote-inbound"
|
|
seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true})
|
|
svc := &InboundService{}
|
|
const keepEmail = "keep@example.test"
|
|
const oldSettings = `{"clients":[{"email":"keep@example.test","enable":true},{"email":"detached@example.test","enable":true}]}`
|
|
syncNodeWithSettings(t, svc, nodeID, tag, oldSettings, xray.ClientTraffic{Email: keepEmail, Enable: true, Up: 100})
|
|
var oldInbound model.Inbound
|
|
if err := db.Where("tag = ?", tag).Take(&oldInbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
writeErr := errors.New("injected orphan write failure")
|
|
const callbackName = "test:fail-node-orphan-write"
|
|
if err := db.Callback().Update().Before("gorm:update").Register(callbackName, func(tx *gorm.DB) {
|
|
updates, ok := tx.Statement.Dest.(map[string]any)
|
|
if ok && tx.Statement.Table == "clients" && updates["sync_orphaned_by"] == nodeID {
|
|
_ = tx.AddError(writeErr)
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Callback().Update().Remove(callbackName) })
|
|
snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{
|
|
Tag: tag, Settings: `{"clients":[{"email":"keep@example.test","enable":true}]}`,
|
|
ClientStats: []xray.ClientTraffic{{Email: keepEmail, Enable: true, Up: 160}},
|
|
}}}
|
|
if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); !errors.Is(err, writeErr) {
|
|
t.Fatalf("merge error = %v, want %v", err, writeErr)
|
|
}
|
|
var links int64
|
|
if err := db.Model(&model.ClientInbound{}).Count(&links).Error; err != nil || links != 2 {
|
|
t.Fatalf("rollback left %d links, want 2 (%v)", links, err)
|
|
}
|
|
if mark := readOrphanMark(t, db, "detached@example.test"); mark != 0 {
|
|
t.Fatalf("rollback left orphan mark %d", mark)
|
|
}
|
|
var inbound model.Inbound
|
|
if err := db.First(&inbound, oldInbound.Id).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var baseline model.NodeClientTraffic
|
|
if err := db.Where("node_id = ? AND email = ?", nodeID, keepEmail).Take(&baseline).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if inbound.Settings != oldInbound.Settings || baseline.Up != 100 || readTraffic(t, db, keepEmail).Up != 100 {
|
|
t.Fatalf("rollback leaked snapshot settings, counters or baseline: settings=%s baseline=%+v", inbound.Settings, baseline)
|
|
}
|
|
}
|
|
|
|
func isolateNodeReconciliationDB(t *testing.T) {
|
|
t.Helper()
|
|
cleanup, err := testpg.IsolatePackage("node_reconciliation")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
}
|
|
|
|
func TestNodeFullReconciliationKeepsConcurrentCommentPostgres(t *testing.T) {
|
|
if config.GetDBKind() != database.DialectPostgres {
|
|
t.Skip("requires concurrent PostgreSQL writes")
|
|
}
|
|
isolateNodeReconciliationDB(t)
|
|
db := initTrafficTestDB(t)
|
|
node := &model.Node{Enable: true, Name: "comment-test", Address: "192.0.2.1", Port: 2053}
|
|
seedNodeRow(t, db, node)
|
|
const email = "comment@example.test"
|
|
const tag = "remote-comment"
|
|
svc := &InboundService{}
|
|
syncNodeWithSettings(t, svc, node.Id, tag, clientsSettings(t, []model.Client{{Email: email, Enable: true, Comment: "old note"}}))
|
|
|
|
read, release := make(chan struct{}), make(chan struct{})
|
|
unblock := sync.OnceFunc(func() { close(release) })
|
|
var gate sync.Once
|
|
var wg sync.WaitGroup
|
|
const hook = "test:comment-after-reconcile-read"
|
|
if err := db.Callback().Update().Before("gorm:update").Register(hook, func(tx *gorm.DB) {
|
|
row, ok := tx.Statement.Dest.(*model.ClientRecord)
|
|
if ok && row.Email == email && row.LimitIP == 3 {
|
|
gate.Do(func() { close(read); <-release })
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
unblock()
|
|
wg.Wait()
|
|
_ = db.Callback().Update().Remove(hook)
|
|
})
|
|
|
|
snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{
|
|
Tag: tag, Protocol: model.VLESS,
|
|
Settings: clientsSettings(t, []model.Client{{Email: email, Enable: true, LimitIP: 3, Comment: "remote note"}}),
|
|
}}}
|
|
done := make(chan error, 1)
|
|
wg.Go(func() {
|
|
_, err := svc.SetRemoteTraffic(node.Id, snap, false, false)
|
|
done <- err
|
|
})
|
|
select {
|
|
case <-read:
|
|
case err := <-done:
|
|
t.Fatalf("reconciliation never reached the client write barrier: %v", err)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("blocked before reaching the client write barrier")
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
|
defer cancel()
|
|
if err := db.WithContext(ctx).Model(&model.ClientRecord{}).Where("email = ?", email).
|
|
UpdateColumn("comment", "concurrent master note").Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
unblock()
|
|
if err := <-done; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var row model.ClientRecord
|
|
if err := db.Where("email = ?", email).Take(&row).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if row.Comment != "concurrent master note" || row.LimitIP != 3 {
|
|
t.Fatalf("reconciliation lost the note or did not apply the remote edit: comment=%q limitIP=%d", row.Comment, row.LimitIP)
|
|
}
|
|
}
|
|
|
|
func TestNodeFullReconciliationExcludesRolledBackDetaches(t *testing.T) {
|
|
isolateNodeReconciliationDB(t)
|
|
db := initTrafficTestDB(t)
|
|
node := &model.Node{Enable: true, Name: "savepoint-test", Address: "192.0.2.1", Port: 2053}
|
|
seedNodeRow(t, db, node)
|
|
svc := &InboundService{}
|
|
const rejectedTag = "rejected-inbound"
|
|
const acceptedTag = "accepted-inbound"
|
|
const rejectedEmail = "rejected@example.test"
|
|
const removedEmail = "removed@example.test"
|
|
keep := model.Client{Email: "keep@example.test", Enable: true}
|
|
initial := func(tag, email string, port int) *model.Inbound {
|
|
return &model.Inbound{
|
|
Tag: tag, Port: port, Protocol: model.VLESS, Enable: true,
|
|
Settings: clientsSettings(t, []model.Client{keep, {Email: email, Enable: true}}),
|
|
}
|
|
}
|
|
original := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
|
|
initial(rejectedTag, rejectedEmail, 41010), initial(acceptedTag, removedEmail, 41011),
|
|
}}
|
|
if _, err := svc.SetRemoteTraffic(node.Id, original, false, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var rejected model.Inbound
|
|
if err := db.Where("tag = ?", rejectedTag).Take(&rejected).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const hook = "test:reject-detach-after-delete"
|
|
rejectedDelete := false
|
|
if err := db.Callback().Delete().After("gorm:delete").Register(hook, func(tx *gorm.DB) {
|
|
if tx.Statement.Table == "client_inbounds" && len(tx.Statement.Vars) > 0 &&
|
|
tx.Statement.Vars[0] == rejected.Id && tx.RowsAffected == 1 {
|
|
rejectedDelete = true
|
|
_ = tx.AddError(errors.New("injected failure after link deletion"))
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Callback().Delete().Remove(hook) })
|
|
snapshot := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
|
|
{Tag: rejectedTag, Port: 41010, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})},
|
|
{Tag: acceptedTag, Port: 41011, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})},
|
|
}}
|
|
if _, err := svc.SetRemoteTraffic(node.Id, snapshot, false, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !rejectedDelete || readOrphanMark(t, db, rejectedEmail) != 0 || readOrphanMark(t, db, removedEmail) == 0 {
|
|
t.Fatalf("savepoint did not isolate orphan candidates: injected=%v", rejectedDelete)
|
|
}
|
|
var links int64
|
|
if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", rejected.Id).Count(&links).Error; err != nil || links != 2 {
|
|
t.Fatalf("failed reconciliation did not restore its two memberships: %d (%v)", links, err)
|
|
}
|
|
}
|