Files
mirror-3x-ui/internal/web/service/client_sync_orphan.go
T
Hamed 32e4b8bcfe 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
2026-12-02 19:46:44 +03:30

116 lines
4.0 KiB
Go

package service
import (
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
"gorm.io/gorm"
)
// How long a client stays recoverable after a node merge concluded it is gone.
// Attaching it again inside this window, by a merge or an admin, clears the mark.
const syncOrphanReapGrace = 15 * time.Minute
// A traffic row with no clients row behind it is drift the orphan sweep will
// never mark, so it stays on the old delete-immediately path.
func clientRecordExists(tx *gorm.DB, email string) bool {
var n int64
if err := tx.Model(&model.ClientRecord{}).Where("email = ?", email).Count(&n).Error; err != nil {
return false
}
return n > 0
}
func markDetachedSyncOrphans(tx *gorm.DB, ids []int, nodeID int, nowMs int64) (bool, error) {
marked := false
for _, batch := range chunkInts(ids, sqlInChunk) {
result := tx.Model(&model.ClientRecord{}).
Where("id IN ? AND email <> '' AND sync_orphaned_at = 0", batch).
Where("NOT EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)").
Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID})
if result.Error != nil {
return false, result.Error
}
marked = marked || result.RowsAffected > 0
}
return marked, nil
}
// A client that is attached again is not orphaned, whatever an earlier merge
// concluded — this is what makes a bad merge recoverable instead of fatal.
func clearSyncOrphanMarks(tx *gorm.DB, ids []int) error {
for _, batch := range chunkInts(ids, sqlInChunk) {
scope := tx.Model(&model.ClientRecord{}).Where("id IN ?", batch)
if err := clearAttachedSyncOrphanMarks(scope); err != nil {
return err
}
}
return nil
}
func clearAttachedSyncOrphanMarks(scope *gorm.DB) error {
return scope.Where("sync_orphaned_at > 0 AND EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)").
Updates(map[string]any{"sync_orphaned_at": 0, "sync_orphaned_by": 0}).Error
}
func reapableSyncOrphans(tx *gorm.DB, cutoff int64) *gorm.DB {
return tx.Model(&model.ClientRecord{}).
Where("sync_orphaned_at > 0 AND sync_orphaned_at <= ?", cutoff).
Where("NOT EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)")
}
// ReapSyncOrphans deletes the clients the node-snapshot sweep marked and nothing
// attached again since. It is the only path that hard-deletes for that sweep.
func (s *ClientService) ReapSyncOrphans() (int, error) {
db := database.GetDB()
cutoff := time.Now().Add(-syncOrphanReapGrace).UnixMilli()
// The maintenance pass also repairs attached marks from legacy databases and imports.
var ids []int
if err := db.Model(&model.ClientRecord{}).Where("sync_orphaned_at > 0").Pluck("id", &ids).Error; err != nil {
return 0, err
}
reaped := 0
for _, listed := range chunkInts(ids, sqlInChunk) {
var batch []string
if err := runSerializedTx(func(tx *gorm.DB) error {
// The list was read outside the writer; an attach may have committed since.
if err := clearSyncOrphanMarks(tx, listed); err != nil {
return err
}
if err := reapableSyncOrphans(tx, cutoff).Where("id IN ?", listed).Pluck("email", &batch).Error; err != nil {
return err
}
if len(batch) == 0 {
return nil
}
if err := adjustGroupBaselinesForRemovedTraffic(tx, batch); err != nil {
return err
}
if err := tx.Where("email IN ?", batch).Delete(&model.ClientRecord{}).Error; err != nil {
return err
}
if err := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; err != nil {
return err
}
if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
return err
}
return (&InboundService{}).delClientIPsByEmails(tx, batch)
}); err != nil {
return reaped, err
}
if len(batch) == 0 {
continue
}
reaped += len(batch)
logger.Infof("reaped %d client(s) confirmed removed on their node", len(batch))
}
return reaped, nil
}