mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
fix(nodes): order client pushes outside inbound mutation locks (#7314)
Release inbound mutation locks after durable local commit and reserve conflicting remote dispatch turns in writer commit order. Allow independent inbounds to progress concurrently while reconciliation and full client deletes retain node-wide ordering. Bound queue waits and live batches separately, advance dirty revisions strictly, and invalidate only affected remote fingerprints.
Persist permanent-delete intents transactionally per node/email and replay bounded pages during reconciliation. Match acknowledgements to the queued generation and retain failed/ambiguous deliveries. Supersede pending deletes only when the client is desired on the target node, so recreation on another node does not leave an old orphan record. Preserve pending rows during database migration and accept legacy backups without the outbox table.
Validation: reproduced the cross-node orphan on the previous head; fixed regression passed locally on Lenovo with focused SQLite (9/9) and PostgreSQL 16 (7/7). All 12 CI jobs passed on 5459316fbd (run 46862646487), including race, PostgreSQL migration and durable-first, and node/Xray E2E. PostgreSQL logs confirm all seven ordering tests including cross-node recreation, lost acknowledgement and bulk recovery after database reopen. Branch is up to date with main. No measured production latency claim; requests still wait for their own bounded ordered remote apply. Coordinate overlapping #7308 before its integration.
Fixes #7304.
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
||||
)
|
||||
|
||||
func queueNodeClientDeletes(tx *gorm.DB, nodeID *int, emails []string) ([]model.NodePendingClientDelete, error) {
|
||||
if nodeID == nil || len(emails) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
ids := make(map[string]int, len(emails))
|
||||
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||
var records []model.ClientRecord
|
||||
if err := tx.Select("id", "email").Where("email IN ?", batch).Find(&records).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, record := range records {
|
||||
ids[record.Email] = record.Id
|
||||
}
|
||||
}
|
||||
generation := uuid.NewString()
|
||||
rows := make([]model.NodePendingClientDelete, 0, len(emails))
|
||||
for _, email := range emails {
|
||||
rows = append(rows, model.NodePendingClientDelete{
|
||||
NodeId: *nodeID, Email: email, ClientId: ids[email], Generation: generation,
|
||||
})
|
||||
}
|
||||
err := tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"client_id", "generation", "last_attempt_at"}),
|
||||
}).CreateInBatches(rows, 200).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm.DB {
|
||||
return db.Model(&model.NodePendingClientDelete{}).
|
||||
Where("node_pending_client_deletes.node_id = ? AND node_pending_client_deletes.email = ? AND node_pending_client_deletes.generation = ?",
|
||||
row.NodeId, row.Email, row.Generation)
|
||||
}
|
||||
|
||||
// applyNodeClientDelete runs under the node-wide turn. Later attached clients
|
||||
// push after this turn or are restored by the dirty generation on reconcile.
|
||||
func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) error {
|
||||
db := database.GetDB().WithContext(ctx)
|
||||
var target struct {
|
||||
Desired bool
|
||||
}
|
||||
result := sameNodeClientDelete(db, row).
|
||||
Select("EXISTS (" +
|
||||
"SELECT 1 FROM client_inbounds JOIN inbounds ON inbounds.id = client_inbounds.inbound_id " +
|
||||
"WHERE client_inbounds.client_id = clients.id AND inbounds.node_id = node_pending_client_deletes.node_id) AS desired").
|
||||
Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email").
|
||||
Limit(1).Scan(&target)
|
||||
if result.Error != nil || result.RowsAffected == 0 {
|
||||
return result.Error
|
||||
}
|
||||
// Only a desired attachment on this node supersedes its pending delete.
|
||||
// Recreating the email elsewhere must not leave the old node record behind.
|
||||
if !target.Desired {
|
||||
if err := rt.DeleteClient(ctx, row.Email); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error
|
||||
}
|
||||
|
||||
const nodeClientDeletePage = 200
|
||||
|
||||
// Reconciliation holds the exclusive node turn while delivering one bounded
|
||||
// page. A failed page keeps the node dirty so snapshots cannot readopt clients.
|
||||
func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtime) error {
|
||||
db := database.GetDB().WithContext(ctx)
|
||||
var rows []model.NodePendingClientDelete
|
||||
if err := db.Where("node_id = ?", nodeID).Order("last_attempt_at, email").
|
||||
Limit(nodeClientDeletePage).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
sendCtx, cancel := context.WithTimeout(ctx, nodeClientPushTimeout)
|
||||
defer cancel()
|
||||
var firstErr error
|
||||
for _, row := range rows {
|
||||
if err := applyNodeClientDelete(sendCtx, rt, row); err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
// Rotate a failing row behind entries that have not had a turn.
|
||||
if err := sameNodeClientDelete(db, row).Update("last_attempt_at", time.Now().UnixNano()).Error; err != nil {
|
||||
return errors.Join(firstErr, err)
|
||||
}
|
||||
if sendCtx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if firstErr != nil {
|
||||
return fmt.Errorf("deliver node client deletes: %w", firstErr)
|
||||
}
|
||||
if len(rows) == nodeClientDeletePage {
|
||||
var remaining int64
|
||||
if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ?", nodeID).
|
||||
Limit(1).Select("1").Scan(&remaining).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining != 0 {
|
||||
return errors.New("more node client deletes awaiting delivery")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user