Files
mirror-3x-ui/internal/web/service/client_sync_orphan.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

110 lines
3.8 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 markSyncOrphan(tx *gorm.DB, email string, nodeID int, nowMs int64) error {
if email == "" {
return nil
}
return tx.Model(&model.ClientRecord{}).
Where("email = ? AND sync_orphaned_at = 0", email).
Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}).Error
}
// 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 tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error
}); 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
}