Files
mirror-3x-ui/internal/web/service/client_sync_orphan.go
T
Hamed Sanaei 596f807ed7 fix(ip-sync): prevent reporter lock inversion with client mutations
Take the PostgreSQL flat reporter fence after its IP writes. Match flat IP row order across bulk cleanup and rename, and discard observations whose row identity disappeared while the report was waiting. Exercise real CRUD and lifecycle overlap in the PostgreSQL CI gate.
2026-12-02 18:50:48 +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
}