mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
0db9503228
Isolate traffic synchronization with bounded round-robin per-node workers, independent maintenance and publication, cancellation and ordered shutdown drain. Recheck online eligibility inside the serialized writer before merging snapshots and retain the latest valid speed sample per node, with expiry and explicit empty publication.
Report direct per-node applied/pending/failed outcomes without changing local-save success semantics. Propagate downstream pending separately from direct ACKs so acknowledged batch items do not abort subsequent work. Integrate live admission into the existing #7314 ordered dispatcher with separate four-second queue and batch budgets, retaining monotonic dirty generations, exclusive full-delete/reconcile turns, durable deletion outbox, generation-matched settlement, cross-node recreation safeguards and targeted fingerprint invalidation. Preserve legacy peer compatibility and update generated API documentation.
Validation: all 12 CI jobs and Docs CI passed on reviewed head d13850474f (runs 46871519847 and 46871519831). PostgreSQL logs confirm eight ordering regressions, including saturation, lost ACK, cross-node recreation and bulk recovery. Author reports make verify, focused SQLite/PostgreSQL race tests, four mixed-version node E2E pairings and Xray E2E. No independent production-scale latency measurement or universal HTTP timeout guarantee.
Residual follow-ups: possible conservative false-pending result when a final full delete settles an intermediate superseded intent on the same node; add per-logical-operation settlement regression. Verify shutdown drain under a blocked writer/maintenance worker. These static-review concerns remain open for follow-up, not demonstrated data loss or a new deadlock.
Refs #7293
127 lines
4.4 KiB
Go
127 lines
4.4 KiB
Go
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) (runtime.ClientApplyResult, bool, 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 runtime.ClientApplyResult{}, false, 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.
|
|
var applied runtime.ClientApplyResult
|
|
if !target.Desired {
|
|
var err error
|
|
applied, err = rt.DeleteClient(ctx, row.Email)
|
|
if err != nil {
|
|
return applied, false, err
|
|
}
|
|
}
|
|
return applied, !target.Desired, 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
|
|
}
|