Files
mirror-3x-ui/internal/web/service/client_create_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

194 lines
5.5 KiB
Go

package service
import (
"context"
"encoding/json"
"fmt"
"runtime/debug"
"sync"
"time"
"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"
)
type queuedClientCreate struct {
turn *nodeConfigTurn
remote *runtime.Remote
tag string
client string
advance func()
queuedAt time.Time
}
func (q *queuedClientCreate) prepare(turn *nodeConfigTurn, remote *runtime.Remote, previous, inbound *model.Inbound, client string, prunedOrphans bool) {
q.turn, q.remote, q.tag, q.client = turn, remote, inbound.Tag, client
q.queuedAt = time.Now()
if !prunedOrphans {
q.advance = remote.PreparePushedInboundAdvance(previous, inbound)
}
}
func (s *ClientService) pushClientCreates(parent context.Context, pushes []queuedClientCreate) (bool, error) {
ctx, cancel := context.WithTimeout(parent, nodeClientPushTimeout)
defer cancel()
byNode := make(map[int][]*queuedClientCreate)
var nodeOrder []int
for i := range pushes {
push := &pushes[i]
if push.turn == nil {
continue
}
nodeID := push.turn.nodeID
if len(byNode[nodeID]) == 0 {
nodeOrder = append(nodeOrder, nodeID)
}
byNode[nodeID] = append(byNode[nodeID], push)
}
applies := make([]inboundApply, 0, len(byNode))
// Reserve one delivery slot per admitted node. Extra groups use spare capacity.
spare := make(chan struct{}, max(0, inboundFanoutConcurrency-len(byNode)))
for _, nodeID := range nodeOrder {
group := byNode[nodeID]
applies = append(applies, inboundApply{id: group[0].turn.inboundID, nodeID: &nodeID, run: func() (bool, error) {
s.pushClientCreatesOnNode(ctx, spare, group)
return false, nil
}})
}
return fanoutInboundApplies(applies)
}
func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) {
queue := pending[0].turn.queue
nodeID := pending[0].turn.nodeID
defer func() {
for _, push := range pending {
push.turn.release()
}
}()
var workers sync.WaitGroup
defer workers.Wait()
primary := make(chan struct{}, 1)
for len(pending) > 0 {
if err := ctx.Err(); err != nil {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
return
}
changed := queue.changes()
type batchKey struct {
remote *runtime.Remote
client string
}
var batches [][]*queuedClientCreate
positions := make(map[batchKey]int)
var waiting []*queuedClientCreate
for _, push := range pending {
select {
case <-push.turn.ready:
key := batchKey{remote: push.remote, client: push.client}
i, found := positions[key]
if !found {
i = len(batches)
positions[key] = i
batches = append(batches, nil)
}
batches[i] = append(batches[i], push)
default:
waiting = append(waiting, push)
}
}
if len(batches) == 0 {
select {
case <-changed:
case <-ctx.Done():
}
continue
}
// Release ready lanes before waiting for lanes behind a node-wide turn.
for _, batch := range batches {
slot := reserveClientCreateSlot(ctx, primary, spare)
if slot == nil {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, ctx.Err())
return
}
run := func() {
defer func() { <-slot }()
defer func() {
for _, push := range batch {
push.turn.release()
}
}()
s.applyClientCreateBatch(ctx, nodeID, queue, batch)
}
if len(batches) == 1 && len(waiting) == 0 {
run()
} else {
workers.Go(run)
}
}
pending = waiting
}
}
func reserveClientCreateSlot(ctx context.Context, primary, spare chan struct{}) chan struct{} {
select {
case primary <- struct{}{}:
return primary
default:
}
select {
case primary <- struct{}{}:
return primary
case spare <- struct{}{}:
return spare
case <-ctx.Done():
return nil
}
}
func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, queue *nodeConfigQueue, batch []*queuedClientCreate) {
if err := ctx.Err(); err != nil {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
return
}
if !queue.acquireLive() {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy)
return
}
defer queue.releaseLive()
defer func() {
if panicValue := recover(); panicValue != nil {
for _, push := range batch {
push.remote.ForgetPushedInbound(push.tag)
}
err := fmt.Errorf("panic applying grouped client create: %v", panicValue)
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
logger.Errorf("%v for node %d\n%s", err, nodeID, debug.Stack())
}
}()
tags := make([]string, len(batch))
for i, push := range batch {
tags[i] = push.tag
}
remote := batch[0].remote
started := time.Now()
result, acknowledged, err := remote.AddClientGroup(ctx, tags, json.RawMessage(batch[0].client))
if err != nil {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
logger.Warning("Error applying clients on", remote.Name(), ":", err)
}
for i, push := range batch {
if i >= len(acknowledged) || !acknowledged[i] || push.advance == nil {
remote.ForgetPushedInbound(push.tag)
s.recordClientNodePush(nodeID, i < len(acknowledged) && acknowledged[i] && result.DownstreamPending, result, nil)
continue
}
push.advance()
s.recordClientNodePush(nodeID, true, result, nil)
}
logger.Debugf("client create node apply: node_id=%d inbounds=%d queue_wait_ms=%d rpc_ms=%d",
nodeID, len(tags), started.Sub(batch[0].queuedAt).Milliseconds(), time.Since(started).Milliseconds())
}