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()) }