perf(ip-sync): batch node client IP attribution writes (#7347)

Batch changed node_client_ips rows in bounded deterministic 190-row statements with snapshot CAS, affected-row/replacement-ID checks, whole-GUID rollback and retry, insert-only RETURNING id and guarded pruning. Preserve exact timestamps, canonical no-op skipping, GUID scoping and flat IP-limit behavior.

Integrate independent node polling with transactional reporter eligibility and identity fences. Avoid the reproduced PostgreSQL flat-IP/node ABBA cycle by ordering flat IP DML before reporter validation at commit; retain node-before-attribution ordering for GUID writes and node deletion. Prelock rename and bulk cleanup targets in byte order and reject stale email CAS attempts. Preserve SQLite immediate write transactions, ordered dispatch, durable deletion and existing traffic reconciliation. No network I/O under the new DB locks or global IP-sync serialization.

Validation: all 12 CI jobs passed on c2831ca52f (run 46915194728). PostgreSQL logs confirm delete/rename/bulk lock order, independent reporter progress, lifecycle rollback on disable/delete/endpoint/GUID changes, guarded prune, scanner enforcement and existing durable-delete/reconciliation regressions. Author reports RED SQLSTATE 40P01 on af77a55d, focused SQLite/PostgreSQL race tests, make verify and all four node E2E version pairings.

Author-reported PostgreSQL 16 fixture: 552 -> 4 UPSERTs/round, unchanged 70,656 affected rows, merge p95 387.8–391.1 -> 72.3–81.4 ms, handler p95 16.9–19.5 -> 8.9–11.7 ms. Contention: 2 -> 0 observed deadlocks; corrected 192/192 reports succeeded. Loaded-host tails increased; idle-host repeats did not show a consistent material regression. WAL reduction and production latency improvement are not established. Monitor lock waits and CRUD tail latency separately.

Fixes #7298
This commit is contained in:
Hamed
2026-12-02 19:46:44 +03:30
committed by GitHub
parent 7a5a25fae2
commit 32e4b8bcfe
14 changed files with 1512 additions and 80 deletions
@@ -0,0 +1,410 @@
package service
import (
"errors"
"fmt"
"slices"
"sync"
"sync/atomic"
"testing"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestNodeClientIpRefreshBatchesWrites(t *testing.T) {
setupClientIpTestDB(t)
const clients = 552
const guid = "edge"
now := time.Now().Unix()
report := make(map[string][]model.ClientIpEntry, clients)
for i := range clients {
report[fmt.Sprintf("client-%04d", i)] = []model.ClientIpEntry{
{IP: "192.0.2.1", Timestamp: now - 10},
{IP: "2001:db8::1", Timestamp: now - 20},
}
}
svc := &InboundService{}
if err := svc.RecordLocalClientIps(guid, report); err != nil {
t.Fatal(err)
}
counts := countClientIpSQL(t, "node_client_ips")
for _, entries := range report {
entries[0], entries[1] = entries[1], entries[0]
}
if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil {
t.Fatal(err)
}
if got := counts.creates.Load(); got != 0 {
t.Fatalf("unchanged report executed %d upserts, want none", got)
}
for email, entries := range report {
if email != "client-0000" {
entries[1].Timestamp = now
}
}
report["new@x"] = slices.Clone(report["client-0001"])
if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil {
t.Fatal(err)
}
if got := counts.creates.Load(); got != 3 || counts.affected.Load() != clients {
t.Fatalf("refreshed report executed %d upserts for %d rows, want 3 upserts for %d", got, counts.affected.Load(), clients)
}
trees, err := svc.GetClientIpsByGuid()
if err != nil {
t.Fatal(err)
}
if got := len(trees[guid]); got != len(report) {
t.Fatalf("saved clients = %d, want %d", got, len(report))
}
for email, want := range report {
got := trees[guid][email]
if len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("saved IPs for %q = %v, want %v", email, got, want)
}
}
}
func TestNodeClientIpBatchRetriesConcurrentChange(t *testing.T) {
for _, change := range []string{"insert", "insert in batch", "update", "refresh before delete", "delete before refresh", "replace before refresh"} {
t.Run(change, func(t *testing.T) {
setupClientIpTestDB(t)
db := database.GetDB()
svc := &InboundService{}
now := time.Now().Unix()
first := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10}
winner := model.ClientIpEntry{IP: "198.51.100.1", Timestamp: now - 5}
incoming := model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now}
if change == "refresh before delete" {
first.Timestamp = now - clientIpStaleAfterSeconds - 20
incoming.Timestamp = first.Timestamp
}
inserting := change == "insert" || change == "insert in batch"
if !inserting {
row := model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, first)}
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
replacement := []model.ClientIpEntry{winner}
if change == "delete before refresh" {
replacement = nil
}
if change == "update" {
replacement = []model.ClientIpEntry{first, winner}
}
blob := rawClientIpBlob(t, replacement...)
const callback = "test:node_ip_competing_writer"
wrote := false
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
if wrote || tx.Statement.Table != "node_client_ips" {
return
}
wrote = true
if change == "delete before refresh" || change == "replace before refresh" {
_ = tx.AddError(db.Transaction(func(other *gorm.DB) error {
if err := other.Exec("DELETE FROM node_client_ips WHERE node_guid = ? AND email = ?", "edge", "a@x").Error; err != nil {
return err
}
if change == "replace before refresh" {
return other.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error
}
return nil
}))
return
}
if inserting {
tx.AddError(db.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error)
return
}
tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error)
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
report := map[string][]model.ClientIpEntry{"a@x": {incoming}}
if change == "insert in batch" {
report["z@x"] = []model.ClientIpEntry{incoming}
}
if err := svc.RecordLocalClientIps("edge", report); err != nil {
t.Fatal(err)
}
tree, err := svc.GetClientIpsByGuid()
if err != nil {
t.Fatal(err)
}
want := replacement
if change != "refresh before delete" {
want = append(want, incoming)
}
if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, want) {
t.Fatalf("saved after concurrent %s = %v, want %v (writer ran: %t)", change, got, want, wrote)
}
if change == "insert in batch" && !slices.Equal(tree["edge"]["z@x"], report["z@x"]) {
t.Fatalf("uncontested row = %v, want %v", tree["edge"]["z@x"], report["z@x"])
}
})
}
}
func TestNodeClientIpBatchRollsBackOnLaterFailure(t *testing.T) {
setupClientIpTestDB(t)
db := database.GetDB()
svc := &InboundService{}
now := time.Now().Unix()
report := make(map[string][]model.ClientIpEntry, 201)
for i := range 201 {
report[fmt.Sprintf("client-%03d", i)] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 10}}
}
if err := svc.RecordLocalClientIps("edge", report); err != nil {
t.Fatal(err)
}
const callback = "test:node_ip_second_batch_failure"
failure := errors.New("second attribution batch failed")
attempts := 0
if err := db.Callback().Create().Before("gorm:create").Register(callback, func(tx *gorm.DB) {
if tx.Statement.Table == "node_client_ips" {
attempts++
if attempts == 2 {
tx.AddError(failure)
}
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Create().Remove(callback) })
for _, entries := range report {
entries[0].Timestamp = now
}
if err := svc.RecordLocalClientIps("edge", report); !errors.Is(err, failure) {
t.Fatalf("write error = %v, want %v", err, failure)
}
tree, err := svc.GetClientIpsByGuid()
if err != nil {
t.Fatal(err)
}
if got := len(tree["edge"]); got != len(report) {
t.Fatalf("saved clients = %d, want %d", got, len(report))
}
for email, entries := range tree["edge"] {
if len(entries) != 1 || entries[0].Timestamp != now-10 {
t.Fatalf("failed merge changed %q to %v", email, entries)
}
}
}
func TestPruneNodeClientIpsPreservesConcurrentRefresh(t *testing.T) {
for _, withFreshEntry := range []bool{false, true} {
t.Run(fmt.Sprintf("partially-fresh=%t", withFreshEntry), func(t *testing.T) {
setupClientIpTestDB(t)
db := database.GetDB()
now := time.Now().Unix()
cutoff := now - clientIpStaleAfterSeconds
fresh := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now}
stale := model.ClientIpEntry{IP: fresh.IP, Timestamp: cutoff - 1}
entries := []model.ClientIpEntry{stale}
if withFreshEntry {
entries = append(entries, model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now - 5})
}
if err := db.Create(&model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, entries...)}).Error; err != nil {
t.Fatal(err)
}
const callback = "test:refresh_during_prune"
refresh := append(slices.Clone(entries[1:]), fresh)
blob := rawClientIpBlob(t, refresh...)
wrote := false
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
if !wrote && tx.Statement.Table == "node_client_ips" {
wrote = true
tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error)
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
if err := pruneStaleNodeClientIps(cutoff); err != nil {
t.Fatal(err)
}
tree, err := (&InboundService{}).GetClientIpsByGuid()
if err != nil {
t.Fatal(err)
}
if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, refresh) {
t.Fatalf("saved IPs after prune = %v, want %v (refresh ran: %t)", got, refresh, wrote)
}
})
}
}
func TestConcurrentPolledReportsMergeMixedRowsForSharedDescendant(t *testing.T) {
setupClientIpTestDB(t)
db := database.GetDB()
svc := &InboundService{}
const guid = "shared-descendant"
now := time.Now().Unix()
parents := []*model.Node{
{Name: "parent-a", Guid: "parent-a", Address: "192.0.2.1", Port: 443, Enable: true, Status: "online"},
{Name: "parent-b", Guid: "parent-b", Address: "192.0.2.2", Port: 443, Enable: true, Status: "online"},
}
clients := []model.Client{{Email: "a@example.test", Enable: true}, {Email: "z@example.test", Enable: true}}
for i, node := range parents {
if err := db.Create(node).Error; err != nil {
t.Fatal(err)
}
inbound := &model.Inbound{NodeID: &node.Id, OriginNodeGuid: guid, UserId: 1, Protocol: model.VLESS, Port: 25000 + i, Tag: node.Name}
if err := db.Create(inbound).Error; err != nil {
t.Fatal(err)
}
if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil {
t.Fatal(err)
}
}
if err := svc.RecordLocalClientIps(guid, map[string][]model.ClientIpEntry{
clients[0].Email: {{IP: "192.0.2.1", Timestamp: now - 20}},
}); err != nil {
t.Fatal(err)
}
read := make(chan struct{})
continueFirst := make(chan struct{})
unblock := sync.OnceFunc(func() { close(continueFirst) })
var reads atomic.Int32
var workers sync.WaitGroup
const hook = "test:shared-descendant-mixed-insert"
if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) {
if tx.Statement.Table == "node_client_ips" && reads.Add(1) == 1 {
close(read)
<-continueFirst
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
unblock()
workers.Wait()
_ = db.Callback().Query().Remove(hook)
})
report := func(node *model.Node, ip string, timestamp int64) error {
obs := []model.ClientIpEntry{{IP: ip, Timestamp: timestamp}}
return svc.MergePolledClientIpsByGuid(t.Context(), node, map[string]map[string][]model.ClientIpEntry{
guid: {clients[0].Email: obs, clients[1].Email: obs},
})
}
done := make(chan error, 1)
workers.Go(func() { done <- report(parents[0], "198.51.100.1", now-5) })
select {
case <-read:
case err := <-done:
t.Fatalf("first reporter did not plan an attribution transaction: %v", err)
case <-time.After(3 * time.Second):
t.Fatal("first reporter did not reach the attribution read")
}
if err := report(parents[1], "203.0.113.1", now); err != nil {
t.Fatal(err)
}
unblock()
if err := <-done; err != nil {
t.Fatal(err)
}
if reads.Load() != 3 {
t.Fatalf("read attempts = %d, want initial pair plus one whole-GUID retry", reads.Load())
}
trees, err := svc.GetClientIpsByGuid()
if err != nil {
t.Fatal(err)
}
created := []model.ClientIpEntry{{IP: "198.51.100.1", Timestamp: now - 5}, {IP: "203.0.113.1", Timestamp: now}}
if got := trees[guid][clients[1].Email]; !slices.Equal(got, created) {
t.Fatalf("competing insert lost an observation: got %+v, want %+v", got, created)
}
updated := append([]model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 20}}, created...)
if got := trees[guid][clients[0].Email]; !slices.Equal(got, updated) {
t.Fatalf("mixed update lost an observation: got %+v, want %+v", got, updated)
}
}
func TestNodeClientIpLaterBatchCASRollsBackBeforeRetry(t *testing.T) {
for _, exhaust := range []bool{false, true} {
t.Run(fmt.Sprintf("exhaust=%t", exhaust), func(t *testing.T) {
setupClientIpTestDB(t)
db := database.GetDB()
svc := &InboundService{}
const guid = "later-cas"
now := time.Now().Unix()
original := rawClientIpBlob(t, model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 30})
rows := make([]model.NodeClientIp, nodeClientIpWriteBatch+1)
report := make(map[string][]model.ClientIpEntry, len(rows))
for i := range rows {
email := fmt.Sprintf("client-%03d@x", i)
rows[i] = model.NodeClientIp{NodeGuid: guid, Email: email, Ips: original}
report[email] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now}}
}
if err := db.CreateInBatches(&rows, 100).Error; err != nil {
t.Fatal(err)
}
first, last := rows[0], rows[len(rows)-1]
attempts := 0
const hook = "test:conflict-in-last-attribution-batch"
if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) {
if tx.Statement.Table != "node_client_ips" {
return
}
attempts++
var got string
if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&got).Error; err != nil {
_ = tx.AddError(err)
return
}
if got != original {
_ = tx.AddError(fmt.Errorf("earlier batch committed before attempt %d: %s", attempts, got))
return
}
if exhaust || attempts == 1 {
blob := fmt.Sprintf(`[{"ip":"198.51.100.2","timestamp":%d}]`, now-int64(attempts))
_ = tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE id = ?", blob, last.Id).Error)
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) })
err := svc.RecordLocalClientIps(guid, report)
if exhaust {
if !errors.Is(err, errNodeClientIpConflict) || attempts != ClientIpCasRetries {
t.Fatalf("exhaustion = %v, attempts=%d", err, attempts)
}
} else if err != nil || attempts != 2 {
t.Fatalf("retry = %v, attempts=%d", err, attempts)
}
var stored string
if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&stored).Error; err != nil {
t.Fatal(err)
}
want := original
if !exhaust {
want = rawClientIpBlob(t, report[first.Email]...)
var late string
if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", last.Id).Scan(&late).Error; err != nil {
t.Fatal(err)
}
wantLate := rawClientIpBlob(t, model.ClientIpEntry{IP: "198.51.100.2", Timestamp: now - 1}, report[last.Email][0])
if late != wantLate {
t.Fatalf("retry failed to merge the winning observation: %s want %s", late, wantLate)
}
}
if stored != want {
t.Fatalf("first batch after attempt sequence = %s, want %s", stored, want)
}
})
}
}