Files
mirror-3x-ui/internal/web/service/client_node_dispatch.go
T
Hamed 91d5ff400d perf(clients): batch client creation by destination node (#7367)
Group compatible client creates by destination and effective payload via the existing clients/add API. Resolve node-local inbound IDs, preserve distinct flow/address/credential payloads, bound delivery concurrency and use a shared four-second remote delivery budget after local commits.

Advance reconciliation fingerprints only for acknowledged intended settings, retaining previous-fingerprint CAS rather than stamping unrelated rebased changes. Preserve FIFO turns, node-wide barriers, dirty generations, durable delete supersession, partial and uncertain delivery recovery and downstream outcomes. Protect later reattachments in final Delete cleanup and complete Create metadata before remote delivery.

Validation: all 12 CI jobs passed on 63e70cda38 (run 46935177853). PostgreSQL logs confirm 21 ordering/grouped-create tests and prior reporter-lock, reconciliation and traffic contention gates; node E2E confirms all four version pairings. Author reports SQLite/PostgreSQL race tests, make verify and isolated full make race.

Author-reported paired PostgreSQL 18 benchmark: 11 -> 1 RPC, fixed 200 ms peer delay 11-target p95 1552.0 -> 731.9 ms, timeout probe 12.41–12.42 -> 4.41–4.50 s. Size-dependent peer cost can instead cause pending delivery (1.74 -> 4.51 s with 0.74 s recovery); four stalled nodes can defer a fifth. Monitor production convergence and pending rate. No general production latency or allocation improvement claimed.

Refs #7299
2026-12-03 00:08:12 +03:30

267 lines
6.8 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
changed chan struct{}
}
// 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
if q.changed != nil {
close(q.changed)
q.changed = nil
}
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)
}
}
}
func (q *nodeConfigQueue) changes() <-chan struct{} {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
if q.changed == nil {
q.changed = make(chan struct{})
}
return q.changed
}
func (q *nodeConfigQueue) acquireLive() bool {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
if q.live >= inboundFanoutConcurrency {
return false
}
q.live++
return true
}
func (q *nodeConfigQueue) releaseLive() {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
q.live--
}
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.
if !m.turn.queue.acquireLive() {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy)
return
}
defer m.turn.queue.releaseLive()
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)
}