mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
2e0c751a80
Release inbound mutation locks after durable local commit and reserve conflicting remote dispatch turns in writer commit order. Allow independent inbounds to progress concurrently while reconciliation and full client deletes retain node-wide ordering. Bound queue waits and live batches separately, advance dirty revisions strictly, and invalidate only affected remote fingerprints.
Persist permanent-delete intents transactionally per node/email and replay bounded pages during reconciliation. Match acknowledgements to the queued generation and retain failed/ambiguous deliveries. Supersede pending deletes only when the client is desired on the target node, so recreation on another node does not leave an old orphan record. Preserve pending rows during database migration and accept legacy backups without the outbox table.
Validation: reproduced the cross-node orphan on the previous head; fixed regression passed locally on Lenovo with focused SQLite (9/9) and PostgreSQL 16 (7/7). All 12 CI jobs passed on 5459316fbd (run 46862646487), including race, PostgreSQL migration and durable-first, and node/Xray E2E. PostgreSQL logs confirm all seven ordering tests including cross-node recreation, lost acknowledgement and bulk recovery after database reopen. Branch is up to date with main. No measured production latency claim; requests still wait for their own bounded ordered remote apply. Coordinate overlapping #7308 before its integration.
Fixes #7304.
195 lines
5.3 KiB
Go
195 lines
5.3 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"slices"
|
|
"strings"
|
|
|
|
"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"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type trafficLocalApplyAction uint8
|
|
|
|
const (
|
|
trafficAddUser trafficLocalApplyAction = iota + 1
|
|
trafficRemoveUser
|
|
trafficDisableInbound
|
|
)
|
|
|
|
type trafficLocalApplyPlan struct {
|
|
action trafficLocalApplyAction
|
|
inbound model.Inbound
|
|
client map[string]any
|
|
email string
|
|
}
|
|
|
|
type trafficMutationBatch struct {
|
|
localPlans []trafficLocalApplyPlan
|
|
remotePlans []trafficInboundUpdatePlan
|
|
nodeIDs map[int]struct{}
|
|
// renewedEmails get their MTProto sidecar quota zeroed once the tick commits.
|
|
renewedEmails []string
|
|
}
|
|
|
|
type trafficInboundUpdatePlan struct{ oldInbound, newInbound model.Inbound }
|
|
|
|
func newTrafficMutationBatch() *trafficMutationBatch {
|
|
return &trafficMutationBatch{nodeIDs: make(map[int]struct{})}
|
|
}
|
|
|
|
func (b *trafficMutationBatch) addNode(nodeID int) {
|
|
if nodeID > 0 {
|
|
b.nodeIDs[nodeID] = struct{}{}
|
|
}
|
|
}
|
|
|
|
func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error {
|
|
if b == nil {
|
|
return nil
|
|
}
|
|
nodeSvc := NodeService{}
|
|
for nodeID := range b.nodeIDs {
|
|
if err := nodeSvc.MarkNodeDirtyTx(tx, nodeID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Reserve on the writer after maintenance commits so a newer client edit cannot pass it.
|
|
func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) []*nodeConfigTurn {
|
|
if len(plans) == 0 {
|
|
return nil
|
|
}
|
|
turns := make([]*nodeConfigTurn, len(plans))
|
|
for i := range plans {
|
|
ib := &plans[i].newInbound
|
|
if ib.NodeID != nil {
|
|
turns[i] = reserveNodeConfigTurn(*ib.NodeID, ib.Id, nodeClientDelta)
|
|
}
|
|
}
|
|
return turns
|
|
}
|
|
|
|
// The wait and pushes share one budget per node. Dirty state covers a skipped push.
|
|
func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan, turns []*nodeConfigTurn) bool {
|
|
byNode := make(map[int][]int)
|
|
var nodeIDs []int
|
|
for i := range plans {
|
|
id := plans[i].newInbound.NodeID
|
|
if id == nil || turns[i] == nil {
|
|
continue
|
|
}
|
|
nodeID := *id
|
|
if _, seen := byNode[nodeID]; !seen {
|
|
nodeIDs = append(nodeIDs, nodeID)
|
|
}
|
|
byNode[nodeID] = append(byNode[nodeID], i)
|
|
}
|
|
failed, panics := fanoutInboundResults(nodeIDs, nodeFanoutConcurrency, func(n int) bool {
|
|
ctx, cancel := nodePushContext()
|
|
defer cancel()
|
|
indexes := byNode[nodeIDs[n]]
|
|
nodeFailed, nodePanics := fanoutInboundResults(indexes, inboundFanoutConcurrency, func(k int) bool {
|
|
index := indexes[k]
|
|
turn := turns[index]
|
|
defer turn.release()
|
|
if !turn.wait(ctx) {
|
|
return false
|
|
}
|
|
plan := &plans[index]
|
|
rt, push, _, err := s.nodePushPlan(&plan.newInbound)
|
|
if err == nil && push {
|
|
err = rt.UpdateInbound(ctx, &plan.oldInbound, &plan.newInbound)
|
|
if remote, ok := rt.(*runtime.Remote); ok && err != nil {
|
|
remote.ForgetPushedInbound(plan.newInbound.Tag)
|
|
}
|
|
}
|
|
if err != nil {
|
|
logger.Debug("traffic post-commit remote apply failed:", err)
|
|
}
|
|
return err != nil
|
|
})
|
|
return slices.Contains(nodeFailed, true) || slices.ContainsFunc(nodePanics, func(p error) bool { return p != nil })
|
|
})
|
|
needRestart := false
|
|
for i := range failed {
|
|
needRestart = needRestart || failed[i] || panics[i] != nil
|
|
}
|
|
return needRestart
|
|
}
|
|
|
|
func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool {
|
|
if b == nil || len(b.localPlans) == 0 {
|
|
return false
|
|
}
|
|
needRestart := false
|
|
process := currentXrayProcess()
|
|
var original *xray.Config
|
|
if process != nil {
|
|
original = process.GetConfig()
|
|
}
|
|
var removed map[string]map[string]struct{}
|
|
for i := range b.localPlans {
|
|
plan := &b.localPlans[i]
|
|
if plan.inbound.Protocol == model.MTProto {
|
|
s.applyLocalMtproto(plan.inbound.Id)
|
|
continue
|
|
}
|
|
if plan.inbound.Protocol == model.AmneziaWG {
|
|
s.applyLocalAmneziaWG(plan.inbound.Id)
|
|
continue
|
|
}
|
|
if plan.inbound.Protocol == model.TUIC {
|
|
s.applyLocalTuic(plan.inbound.Id)
|
|
continue
|
|
}
|
|
rt, err := s.runtimeFor(&plan.inbound)
|
|
if err == nil {
|
|
switch plan.action {
|
|
case trafficAddUser:
|
|
err = rt.AddUser(context.Background(), &plan.inbound, plan.client)
|
|
case trafficRemoveUser:
|
|
err = rt.RemoveUser(context.Background(), &plan.inbound, plan.email)
|
|
if err != nil && strings.Contains(err.Error(), "not found") {
|
|
err = nil
|
|
}
|
|
if err == nil && original != nil && removalLeavesXraySessions(&plan.inbound) {
|
|
if removed == nil {
|
|
removed = make(map[string]map[string]struct{})
|
|
}
|
|
if removed[plan.inbound.Tag] == nil {
|
|
removed[plan.inbound.Tag] = make(map[string]struct{})
|
|
}
|
|
removed[plan.inbound.Tag][plan.email] = struct{}{}
|
|
}
|
|
case trafficDisableInbound:
|
|
err = rt.DelInbound(context.Background(), &plan.inbound)
|
|
if xray.IsMissingHandlerErr(err) {
|
|
err = nil
|
|
}
|
|
}
|
|
}
|
|
if err != nil {
|
|
logger.Debug("traffic post-commit runtime apply failed:", err)
|
|
needRestart = true
|
|
}
|
|
}
|
|
if len(removed) > 0 {
|
|
// A restart or reconcile may have replaced the snapshot while an API
|
|
// call was running. Only amend the snapshot we applied against.
|
|
lock.Lock()
|
|
if process == currentXrayProcess() && process.IsRunning() &&
|
|
process.GetConfig() == original && process.DropInboundUsers(removed) {
|
|
persistHotConfig(process)
|
|
}
|
|
lock.Unlock()
|
|
}
|
|
return needRestart
|
|
}
|