Files
mirror-3x-ui/internal/web/service/client_node_dispatch.go
T
Hamed 0db9503228 fix(nodes): isolate traffic sync and report client apply outcomes (#7308)
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
2026-12-02 16:47:26 +03:30

245 lines
6.4 KiB
Go

package service
import (
"container/list"
"context"
"sync"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
var (
nodeConfigDispatchMu sync.Mutex
nodeConfigDispatch = map[int]*nodeConfigQueue{}
)
type nodeConfigQueue struct {
groups list.List
reconciles int
live int
}
// Inbounds in the same group can push concurrently. A node-wide operation
// waits for the preceding group to drain before the next group can run.
type nodeConfigGroup struct {
position *list.Element
exclusive bool
inbounds map[int]*list.List
}
type nodeConfigTurn struct {
nodeID int
inboundID int
queue *nodeConfigQueue
group *nodeConfigGroup
position *list.Element
ready chan struct{}
work nodeConfigWork
}
type nodeConfigWork uint8
const (
nodeClientDelta nodeConfigWork = iota
nodeFullClientDelete
nodeFullReconcile
)
func reserveNodeConfigTurn(nodeID, inboundID int, work nodeConfigWork) *nodeConfigTurn {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
q := nodeConfigDispatch[nodeID]
if q == nil {
q = &nodeConfigQueue{}
nodeConfigDispatch[nodeID] = q
}
// A reconcile can see later commits. It converges overlapping deltas,
// while node-wide deletes still run because they also remove client records.
if q.reconciles > 0 && work == nodeClientDelta {
return nil
}
exclusive := work != nodeClientDelta
if exclusive {
inboundID = 0
}
var group *nodeConfigGroup
if last := q.groups.Back(); last != nil {
group = last.Value.(*nodeConfigGroup)
}
if group == nil || group.exclusive != exclusive {
group = &nodeConfigGroup{exclusive: exclusive, inbounds: make(map[int]*list.List)}
group.position = q.groups.PushBack(group)
}
lane := group.inbounds[inboundID]
if lane == nil {
lane = &list.List{}
group.inbounds[inboundID] = lane
}
turn := &nodeConfigTurn{
nodeID: nodeID, inboundID: inboundID, queue: q, group: group, ready: make(chan struct{}), work: work,
}
turn.position = lane.PushBack(turn)
if work == nodeFullReconcile {
q.reconciles++
}
if q.groups.Front() == group.position && lane.Front() == turn.position {
close(turn.ready)
}
return turn
}
func (t *nodeConfigTurn) wait(ctx context.Context) bool {
select {
case <-t.ready:
return ctx.Err() == nil
case <-ctx.Done():
return false
}
}
func (t *nodeConfigTurn) release() {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
if t.position == nil {
return
}
q, group := t.queue, t.group
lane := group.inbounds[t.inboundID]
wasReady := q.groups.Front() == group.position && lane.Front() == t.position
lane.Remove(t.position)
t.position = nil
if t.work == nodeFullReconcile {
q.reconciles--
}
if front := lane.Front(); front != nil {
if wasReady {
close(front.Value.(*nodeConfigTurn).ready)
}
return
}
delete(group.inbounds, t.inboundID)
if len(group.inbounds) > 0 {
return
}
q.groups.Remove(group.position)
if next := q.groups.Front(); next == nil {
delete(nodeConfigDispatch, t.nodeID)
} else if wasReady {
for _, lane := range next.Value.(*nodeConfigGroup).inbounds {
close(lane.Front().Value.(*nodeConfigTurn).ready)
}
}
}
type inboundClientMutation struct {
lock *inboundMutationLock
turn *nodeConfigTurn
}
func beginInboundClientMutation(inboundID int) *inboundClientMutation {
return &inboundClientMutation{lock: lockInbound(inboundID)}
}
func (m *inboundClientMutation) unlock() {
if m.lock != nil {
m.lock.Unlock()
m.lock = nil
}
}
func (m *inboundClientMutation) close() {
m.unlock()
if m.turn != nil {
m.turn.release()
}
}
func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error {
if inbound.NodeID == nil {
return runSerializedTx(write)
}
nodeID := *inbound.NodeID
queuedAt := time.Now()
var startedAt time.Time
err := runSerializedTxThen(func(tx *gorm.DB) error {
startedAt = time.Now()
if err := write(tx); err != nil {
return err
}
return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID)
}, func() {
m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work)
})
if !startedAt.IsZero() {
logger.Debugf("client node save: node_id=%d writer_wait_ms=%d tx_ms=%d success=%t", nodeID,
startedAt.Sub(queuedAt).Milliseconds(), time.Since(startedAt).Milliseconds(), err == nil)
}
return err
}
type nodeClientBatch struct {
result runtime.ClientApplyResult
err error
}
func (b *nodeClientBatch) acknowledge(result runtime.ClientApplyResult, err error) bool {
b.result.DownstreamPending = b.result.DownstreamPending || result.DownstreamPending
b.err = err
return err == nil
}
func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context, *nodeClientBatch) bool) {
m.unlock()
if m.turn == nil {
s.recordClientNodeDeferred(inbound.NodeID)
return
}
nodeID := m.turn.nodeID
queued := time.Now()
waitCtx, stopWaiting := nodePushContext()
ready := m.turn.wait(waitCtx)
waitErr := waitCtx.Err()
stopWaiting()
if !ready {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, waitErr)
logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d deferred=timeout", nodeID, time.Since(queued).Milliseconds())
return
}
// Conflicting turns wait without consuming a live slot.
nodeConfigDispatchMu.Lock()
if m.turn.queue.live >= inboundFanoutConcurrency {
nodeConfigDispatchMu.Unlock()
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy)
return
}
m.turn.queue.live++
nodeConfigDispatchMu.Unlock()
defer func() {
nodeConfigDispatchMu.Lock()
m.turn.queue.live--
nodeConfigDispatchMu.Unlock()
}()
ctx, cancel := nodePushContext()
defer cancel()
complete := false
defer func() {
if remote, ok := rt.(*runtime.Remote); ok && !complete && m.turn.work != nodeFullClientDelete {
remote.ForgetPushedInbound(inbound.Tag)
}
}()
started := time.Now()
var batch nodeClientBatch
complete = apply(ctx, &batch)
s.recordClientNodePush(nodeID, complete || batch.err != nil || batch.result.DownstreamPending, batch.result, batch.err)
if batch.err != nil {
logger.Warning("Error applying clients on", rt.Name(), ":", batch.err)
}
logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d rpc_ms=%d complete=%t downstream_pending=%t",
nodeID, started.Sub(queued).Milliseconds(), time.Since(started).Milliseconds(), complete, batch.result.DownstreamPending)
}