From e80af331ebbdfab45c03aa1791d1e6744ef3e21a Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Mon, 30 Nov 2026 22:08:47 +0330 Subject: [PATCH] fix(nodes): order client pushes outside inbound mutation locks Reserve node apply turns in database commit order and release the inbound mutation lock before waiting or calling the remote runtime. Keep lifecycle updates and full reconciliation in the same sequence, preserve dirty generations across overlapping writes, and invalidate fingerprints after uncertain or superseded remote state. --- .github/workflows/ci.yml | 10 + internal/web/node_contract_test.go | 17 +- internal/web/runtime/remote.go | 7 + internal/web/service/client_bulk.go | 117 ++-- internal/web/service/client_inbound_apply.go | 183 +++---- internal/web/service/client_node_dispatch.go | 144 +++++ .../web/service/client_node_order_test.go | 515 ++++++++++++++++++ internal/web/service/inbound_node.go | 10 + internal/web/service/inbound_traffic.go | 13 +- internal/web/service/inbound_traffic_apply.go | 41 +- internal/web/service/node.go | 3 +- .../service/node_reset_undelivered_test.go | 2 +- internal/web/service/traffic_writer.go | 8 + 13 files changed, 891 insertions(+), 179 deletions(-) create mode 100644 internal/web/service/client_node_dispatch.go create mode 100644 internal/web/service/client_node_order_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..49bd5ed71 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,16 @@ jobs: exit 1 fi + - name: PostgreSQL node client push ordering + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL node client ordering tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index 44c4e9870..b67951d5c 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -417,14 +417,15 @@ func TestMasterNodeContract(t *testing.T) { // Remote methods that never reach the node, or that this table must not run. var remoteMethodsOutsideContract = map[string]string{ - "Name": "local label", - "RecordAdoptedInbound": "local fingerprint bookkeeping", - "AdoptInboundAlias": "local alias bookkeeping", - "AdoptedInboundAliases": "local alias bookkeeping", - "AdvancePushedInbound": "local fingerprint bookkeeping", - "ForgetPushedInbound": "local fingerprint bookkeeping", - "ForgetInbound": "local bookkeeping for an inbound the node no longer has", - "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", + "Name": "local label", + "RecordAdoptedInbound": "local fingerprint bookkeeping", + "AdoptInboundAlias": "local alias bookkeeping", + "AdoptedInboundAliases": "local alias bookkeeping", + "AdvancePushedInbound": "local fingerprint bookkeeping", + "ForgetAllPushedInbounds": "local fingerprint bookkeeping", + "ForgetPushedInbound": "local fingerprint bookkeeping", + "ForgetInbound": "local bookkeeping for an inbound the node no longer has", + "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", } // A Remote method with no cell is how activeInbounds and bulkResetTraffic diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index ada3d9d75..f2c976763 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -690,6 +690,13 @@ func (r *Remote) ForgetPushedInbound(tag string) { r.mu.Unlock() } +// ForgetAllPushedInbounds forces a fresh configuration push without discarding tag aliases. +func (r *Remote) ForgetAllPushedInbounds() { + r.mu.Lock() + defer r.mu.Unlock() + clear(r.pushedFP) +} + // ForgetInbound drops everything kept under an inbound the node no longer has, in either // tag form: a node rotating tags would otherwise grow these maps without bound. func (r *Remote) ForgetInbound(tag string) { diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index ea249ba19..25053d42f 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -681,7 +681,8 @@ func (s *ClientService) bulkAdjustInboundClients( adTagIneligible: map[string]bool{}, } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -816,7 +817,7 @@ func (s *ClientService) bulkAdjustInboundClients( // Serialize against the traffic poll to avoid the cross-transaction // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -827,9 +828,6 @@ func (s *ClientService) bulkAdjustInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -847,28 +845,30 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - for email := range foundEmails { - entry := plan[email] - updated := *entry.record.ToClient() - if entry.applyExpiry { - updated.ExpiryTime = entry.newExpiry + mutation.push(rt, oldInbound, func() bool { + for email := range foundEmails { + entry := plan[email] + updated := *entry.record.ToClient() + if entry.applyExpiry { + updated.ExpiryTime = entry.newExpiry + } + if entry.applyTotal { + updated.TotalGB = entry.newTotal + } + if adTag != "" && oldInbound.Protocol == model.MTProto { + updated.AdTag = wantAdTag + } + updated.UpdatedAt = nowMs + ctx, cancel := nodePushContext() + err := rt.UpdateUser(ctx, oldInbound, email, updated) + cancel() + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - if entry.applyTotal { - updated.TotalGB = entry.newTotal - } - if adTag != "" && oldInbound.Protocol == model.MTProto { - updated.AdTag = wantAdTag - } - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - // First failure ends the batch push; the reconcile converges the rest. - break - } - } + return true + }) } } } @@ -1057,7 +1057,8 @@ func (s *ClientService) bulkDelInboundClients( res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}} defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1192,7 +1193,7 @@ func (s *ClientService) bulkDelInboundClients( // Serialize against the traffic poll to avoid the cross-transaction // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -1203,9 +1204,6 @@ func (s *ClientService) bulkDelInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -1251,17 +1249,18 @@ func (s *ClientService) bulkDelInboundClients( if perr != nil { logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr) } else if push { - for _, email := range dispatchEmails { - ctx, cancel := nodePushContext() - err1 := rt.DeleteClient(ctx, email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - // The node is already dirty, so one reconcile converges the rest of - // the batch instead of paying another deadline per client. - break + mutation.push(rt, oldInbound, func() bool { + for _, email := range dispatchEmails { + ctx, cancel := nodePushContext() + err := rt.DeleteClient(ctx, email) + cancel() + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } } - } + return true + }) } } @@ -1714,7 +1713,8 @@ func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult { res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}} - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1813,7 +1813,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, push = false } - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } @@ -1824,9 +1824,6 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { @@ -1862,23 +1859,21 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - pushFailed := false - for _, ch := range changed { - updated := ch.client - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - pushFailed = true - // First failure ends the batch push; the reconcile converges the rest. - break + mutation.push(rt, oldInbound, func() bool { + for _, ch := range changed { + updated := ch.client + updated.UpdatedAt = nowMs + ctx, cancel := nodePushContext() + err := rt.UpdateUser(ctx, oldInbound, ch.email, updated) + cancel() + if err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } } - } - if !pushFailed { advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } return res diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 6a1c4842c..7ae7b67ab 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -140,7 +140,8 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if len(recs) == 0 { return false, nil } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -248,7 +249,7 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId // Persist the batch deletion atomically, serialized against the traffic poll // to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { for _, t := range targets { if t.emailShared || keepTraffic { continue @@ -276,63 +277,52 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return needRestart, txErr } - // Resolve the node push plan once for the whole batch instead of per email. - var nodeRt runtime.Runtime - nodePush := false if oldInbound.NodeID != nil { rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { return needRestart, perr } - nodeRt, nodePush = rt, push - // Large batches collapse into one reconcile push rather than M deletes. - if nodePush && len(targets) > nodeBulkPushThreshold { - nodePush = false + if push && len(targets) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func() bool { + for _, target := range targets { + if target.email == "" { + continue + } + ctx, cancel := nodePushContext() + err := rt.DeleteUser(ctx, oldInbound, target.email) + cancel() + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } + } + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + return true + }) } + return needRestart, nil } - // Apply runtime deletes after commit — outside the serialized writer so a - // slow node call can't stall traffic accounting. - nodePushFailed := false for _, t := range targets { - if len(t.email) == 0 { + if t.email == "" || !t.needApiDel || !t.notDepleted { continue } - if oldInbound.NodeID == nil { - if t.needApiDel && t.notDepleted { - rt, rterr := inboundSvc.runtimeFor(oldInbound) - if rterr != nil { - needRestart = true - } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil { - if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) { - needRestart = true - } - } else if endDroppedClientSessions(oldInbound) { - needRestart = true - } - } - } else if nodePush && !nodePushFailed { - // First failure ends the batch push; the reconcile converges the rest. - ctx, cancel := nodePushContext() - err1 := nodeRt.DeleteUser(ctx, oldInbound, t.email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1) - nodePushFailed = true + rt, rterr := inboundSvc.runtimeFor(oldInbound) + if rterr != nil { + needRestart = true + } else if err := rt.RemoveUser(context.Background(), oldInbound, t.email); err != nil { + if !strings.Contains(err.Error(), fmt.Sprintf("User %s not found.", t.email)) { + needRestart = true } + } else if endDroppedClientSessions(oldInbound) { + needRestart = true } } - if nodePush && !nodePushFailed { - advancePushedInbound(nodeRt, prevSettings, string(newSettings), oldInbound) - } return needRestart, nil } @@ -406,8 +396,8 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { defer InvalidateSubData() - lock := lockInbound(data.Id) - defer lock.Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -611,7 +601,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } needRestart := false - nextOrphanOffset := lock.orphanOffset + nextOrphanOffset := mutation.lock.orphanOffset prunedOrphans := false rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) @@ -621,7 +611,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // lockInbound is per-inbound, so the pre-tx cross-inbound checks race // concurrent writers on other inbounds — re-run them in here (#6225). if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG { @@ -651,7 +641,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } // Confirm absence in the writer so an earlier committed re-add survives. - compacted, next, err := compactAddOrphans(tx, oldClients, lock.orphanOffset) + compacted, next, err := compactAddOrphans(tx, oldClients, mutation.lock.orphanOffset) if err != nil { return err } @@ -679,14 +669,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr } - lock.orphanOffset = nextOrphanOffset + mutation.lock.orphanOffset = nextOrphanOffset // Apply to the running runtime after commit — outside the serialized writer // so a slow node call can't stall traffic accounting. @@ -721,34 +708,27 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } - } else { - // Large batches would be M sequential per-client RPCs; the inbound's saved - // settings already hold the final set, so mark dirty and let one reconcile - // push converge the node instead. - if push && len(clients) > nodeBulkPushThreshold { - push = false - } - for _, client := range clients { - // /clients/add on the node historically coerced enable=true; skip live - // push for disabled clients and leave dirty so reconcile converges. - if !client.Enable { - push = false - continue - } - if push { + } else if push && len(clients) <= nodeBulkPushThreshold { + mutation.push(rt, oldInbound, func() bool { + for _, client := range clients { + // Older nodes coerce enable=true. Reconcile the rest of this batch. + if !client.Enable { + return false + } ctx, cancel := nodePushContext() err1 := rt.AddClient(ctx, oldInbound, client) cancel() if err1 != nil { logger.Warning("Error in adding client on", rt.Name(), ":", err1) - push = false + return false } } - } - // AddClient only pushed the new clients. Reconcile any orphan removals. - if push && !prunedOrphans { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + // AddClient only pushed the new clients. Reconcile any orphan removals. + if !prunedOrphans { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + return !prunedOrphans + }) } return needRestart, nil @@ -756,7 +736,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) { defer InvalidateSubData() - defer lockInbound(data.Id).Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -1058,7 +1039,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // Same re-check-inside-the-writer rule as AddInboundClient (#6225): // the pre-tx pass can race a concurrent writer on another inbound. if oldInbound.Protocol == model.WireGuard { @@ -1164,9 +1145,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr @@ -1216,14 +1194,16 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - } else { + mutation.push(rt, oldInbound, func() bool { + ctx, cancel := nodePushContext() + defer cancel() + if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil { + logger.Warning("Error in updating client on", rt.Name(), ":", err) + return false + } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } } else { logger.Debug("Client old email not found") @@ -1235,7 +1215,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) { defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1320,7 +1301,11 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // Persist the deletion atomically, serialized against the traffic poll to // avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + work := nodeClientDelta + if fullDelete { + work = nodeFullClientDelete + } + if txErr := mutation.commit(oldInbound, work, func(tx *gorm.DB) error { if !emailShared && !keepTraffic { if e := inboundSvc.DelClientIPs(tx, email); e != nil { logger.Error("Error in delete client IPs") @@ -1339,9 +1324,6 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr @@ -1386,19 +1368,22 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // must remove the node's client record too, not just detach it from // this inbound (#5797). if push { - ctx, cancel := nodePushContext() - var err1 error - if fullDelete { - err1 = rt.DeleteClient(ctx, email) - } else { - err1 = rt.DeleteUser(ctx, oldInbound, email) - } - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - } else { + mutation.push(rt, oldInbound, func() bool { + ctx, cancel := nodePushContext() + defer cancel() + var err error + if fullDelete { + err = rt.DeleteClient(ctx, email) + } else { + err = rt.DeleteUser(ctx, oldInbound, email) + } + if err != nil { + logger.Warning("Error in deleting client on", rt.Name(), ":", err) + return false + } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) } } } diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go new file mode 100644 index 000000000..bb5fff7bb --- /dev/null +++ b/internal/web/service/client_node_dispatch.go @@ -0,0 +1,144 @@ +package service + +import ( + "container/list" + "sync" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +var ( + nodeConfigDispatchMu sync.Mutex + nodeConfigDispatch = map[int]*nodeConfigQueue{} +) + +type nodeConfigQueue struct { + turns list.List + reconciles int +} + +type nodeConfigTurn struct { + nodeID int + queue *nodeConfigQueue + position *list.Element + ready chan struct{} + work nodeConfigWork + behindReconcile bool +} + +type nodeConfigWork uint8 + +const ( + nodeClientDelta nodeConfigWork = iota + nodeFullClientDelete + nodeFullReconcile +) + +// Per-node ordering also covers full client deletes, which can affect sibling inbounds. +func reserveNodeConfigTurn(nodeID int, work nodeConfigWork) *nodeConfigTurn { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q := nodeConfigDispatch[nodeID] + if q == nil { + q = &nodeConfigQueue{} + nodeConfigDispatch[nodeID] = q + } + // A reconcile can see newer commits than its position in the queue. Let it + // converge overlapping deltas, retaining node-wide deletes it cannot replay. + if q.reconciles > 0 && work == nodeClientDelta { + return nil + } + turn := &nodeConfigTurn{ + nodeID: nodeID, queue: q, ready: make(chan struct{}), work: work, behindReconcile: q.reconciles > 0, + } + turn.position = q.turns.PushBack(turn) + if work == nodeFullReconcile { + q.reconciles++ + } + if q.turns.Front() == turn.position { + close(turn.ready) + } + return turn +} + +func (t *nodeConfigTurn) release() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if t.position == nil { + return + } + q := t.queue + wasFirst := t.position == q.turns.Front() + q.turns.Remove(t.position) + t.position = nil + if t.work == nodeFullReconcile { + q.reconciles-- + } + if next := q.turns.Front(); next == nil { + delete(nodeConfigDispatch, t.nodeID) + } else if wasFirst { + close(next.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 + return runSerializedTxThen(func(tx *gorm.DB) error { + if err := write(tx); err != nil { + return err + } + return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID) + }, func() { + m.turn = reserveNodeConfigTurn(nodeID, work) + }) +} + +func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func() bool) { + m.unlock() + if m.turn == nil { + return + } + <-m.turn.ready + complete := false + defer func() { + if remote, ok := rt.(*runtime.Remote); ok { + // A node-wide delete may invalidate newer settings sent by an overlapping + // reconcile, including sibling inbounds that this turn did not edit. + if m.turn.work == nodeFullClientDelete && (!complete || m.turn.behindReconcile) { + remote.ForgetAllPushedInbounds() + } else if !complete { + remote.ForgetPushedInbound(inbound.Tag) + } + } + }() + complete = apply() +} diff --git a/internal/web/service/client_node_order_test.go b/internal/web/service/client_node_order_test.go new file mode 100644 index 000000000..d32b0fe59 --- /dev/null +++ b/internal/web/service/client_node_order_test.go @@ -0,0 +1,515 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type blockedClientPushRuntime struct { + fakeNodeRuntime + calls chan string + release <-chan struct{} + blockedEmail string + waitForTimeout bool + expired atomic.Bool +} + +func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) error { + r.calls <- "add " + client.Email + if client.Email != r.blockedEmail { + return nil + } + if r.waitForTimeout { + select { + case <-ctx.Done(): + r.expired.Store(errors.Is(ctx.Err(), context.DeadlineExceeded)) + return ctx.Err() + case <-time.After(nodeClientPushTimeout + 2*time.Second): + return errors.New("push timeout was not enforced") + } + } + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error { + r.calls <- "update " + email + " " + client.Comment + return nil +} + +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error { + r.calls <- "detach " + email + return nil +} + +func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { + r.calls <- "lifecycle " + inbound.Tag + return nil +} + +func setupClientNodeOrderDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("client_node_order") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + startSerializedWriter(t) +} + +func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) { + for _, tc := range []struct { + name string + timeout bool + }{ + {name: "successful push"}, + {name: "ambiguous timeout", timeout: true}, + } { + t.Run(tc.name, func(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "ordered@example.test" + blocked := &blockedClientPushRuntime{ + calls: make(chan string, 8), release: release, blockedEmail: email, waitForTimeout: tc.timeout, + } + mgr := runtime.GetManager() + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46001, nil) + siblingInbound := nodeInbound(t, nodeID, 46003, nil) + controlNode := model.Node{Name: "control", Address: "127.0.0.1", Port: 2097, ApiToken: "token", Enable: true, Status: "online"} + if err := database.GetDB().Create(&controlNode).Error; err != nil { + t.Fatal(err) + } + control := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(controlNode.Id, control) + other := nodeInbound(t, controlNode.Id, 46002, nil) + clientSvc, inboundSvc := &ClientService{}, &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true} + changed := client + changed.Comment = "committed update" + sibling := model.Client{Email: "control@example.test", ID: uuid.NewString(), Enable: true} + sameNode := model.Client{Email: "same-node@example.test", ID: uuid.NewString(), Enable: true} + data := func(inbound *model.Inbound, client model.Client) *model.Inbound { + return &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client})} + } + addData, updateData, controlData := data(ib, client), data(ib, changed), data(other, sibling) + siblingData := data(siblingInbound, sameNode) + + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + async := func(operation func() (bool, error)) <-chan error { + done := make(chan error, 1) + wg.Go(func() { + restart, err := operation() + if restart { + err = errors.Join(err, errors.New("requested a local restart for a remote mutation")) + } + done <- err + }) + return done + } + expectCall := func(want string) { + t.Helper() + select { + case got := <-blocked.calls: + if got != want { + t.Fatalf("node operation = %q, want %q", got, want) + } + case <-time.After(nodeClientPushTimeout + time.Second): + t.Fatalf("node never received %q", want) + } + } + waitSettings := func(id int, contains string, present bool) { + t.Helper() + start := time.Now() + for { + current, err := inboundSvc.GetInbound(id) + if err == nil && strings.Contains(current.Settings, contains) == present { + t.Logf("local commit observed after %s while first RPC was blocked", time.Since(start)) + return + } + if time.Since(start) >= time.Second { + t.Fatalf("local settings did not reach %q present=%t while first RPC was blocked (last read err=%v)", contains, present, err) + } + time.Sleep(5 * time.Millisecond) + } + } + + add := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, addData) }) + expectCall("add " + client.Email) + start := time.Now() + locked := make(chan time.Duration, 1) + wg.Go(func() { + start := time.Now() + lockInbound(ib.Id).Unlock() + locked <- time.Since(start) + }) + select { + case took := <-locked: + t.Logf("inbound mutation lock acquired in %s while first RPC was blocked", took) + case <-time.After(time.Second): + t.Fatal("first RPC still holds the inbound mutation lock") + } + writerStart := time.Now() + if err := runSerializedTx(func(*gorm.DB) error { return nil }); err != nil { + t.Fatal(err) + } + t.Logf("independent writer turn took %s while first RPC was blocked", time.Since(writerStart)) + update := async(func() (bool, error) { return clientSvc.UpdateInboundClient(inboundSvc, updateData, client.Email) }) + waitSettings(ib.Id, changed.Comment, true) + detach := async(func() (bool, error) { + return clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, client.Email, true, false) + }) + waitSettings(ib.Id, client.Email, false) + sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) }) + waitSettings(siblingInbound.Id, sameNode.Email, true) + controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) }) + select { + case err := <-controlDone: + if err != nil || control.addClient.Load() != 1 { + t.Fatalf("control inbound did not complete independently: %v (pushes=%d)", err, control.addClient.Load()) + } + case <-time.After(time.Second): + t.Fatal("control inbound waited for unrelated node") + } + select { + case got := <-blocked.calls: + t.Fatalf("%q overtook the first RPC", got) + default: + } + unblock() + expectCall("update " + client.Email + " " + changed.Comment) + t.Logf("first RPC held its dispatch turn for %s", time.Since(start)) + if tc.timeout && !blocked.expired.Load() { + t.Fatal("the first push did not finish through its deadline") + } + expectCall("detach " + client.Email) + expectCall("add " + sameNode.Email) + for i, done := range []<-chan error{add, update, detach, sameNodeDone} { + select { + case err := <-done: + if err != nil { + t.Fatal(fmt.Errorf("operation %d reported %w after commit", i, err)) + } + case <-time.After(time.Second): + t.Fatalf("operation %d did not complete", i) + } + } + if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { + t.Fatalf("node dirty=%t error=%v after committed client batch", dirty, err) + } + }) + } +} + +func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + mgr := runtime.GetManager() + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "depleted-while-pushing@example.test" + blocked := &blockedClientPushRuntime{calls: make(chan string, 4), release: release, blockedEmail: email} + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46012, nil) + inboundSvc := &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true, TotalGB: 5} + add := &model.Inbound{Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client})} + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + addDone := make(chan error, 1) + wg.Go(func() { + _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) + addDone <- err + }) + select { + case got := <-blocked.calls: + if got != "add "+client.Email { + t.Fatalf("first node operation = %q", got) + } + case <-time.After(3 * time.Second): + t.Fatal("node did not receive the add") + } + depletionDone := make(chan error, 1) + wg.Go(func() { + _, disabled, err := inboundSvc.AddTraffic(nil, []*xray.ClientTraffic{{Email: client.Email, Up: 10}}) + if !disabled { + err = errors.Join(err, errors.New("traffic did not disable the depleted client")) + } + depletionDone <- err + }) + deadline := time.Now().Add(time.Second) + for readTraffic(t, database.GetDB(), client.Email).Enable { + if time.Now().After(deadline) { + t.Fatal("depletion did not commit while the add was blocked") + } + time.Sleep(5 * time.Millisecond) + } + select { + case got := <-blocked.calls: + t.Fatalf("node operation %q overtook the pending add", got) + case <-time.After(100 * time.Millisecond): + } + unblock() + select { + case got := <-blocked.calls: + if got != "lifecycle "+ib.Tag { + t.Fatalf("second node operation = %q, want the depletion update", got) + } + case <-time.After(time.Second): + t.Fatal("node did not receive the depletion update") + } + for _, done := range []<-chan error{addDone, depletionDone} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } +} + +func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const tag = "in-46011" + listStarted := make(chan struct{}) + releaseList := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseList) }) + var lists atomic.Int32 + pushedSettings := make(chan string, 4) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + if lists.Add(1) == 1 { + close(listStarted) + select { + case <-r.Context().Done(): + return + case <-releaseList: + } + } + obj = []map[string]any{{"id": 1, "tag": tag}} + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + pushedSettings <- r.Form.Get("settings") + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + t.Cleanup(release) + + node := reconcileTestNode(t, server, "reconcile-overlap", "all", nil) + remote := runtime.NewRemote(node, nil) + fast := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(node.Id, fast) + ib := nodeInbound(t, node.Id, 46011, nil) + clientSvc, inboundSvc, nodeSvc := &ClientService{}, &InboundService{}, &NodeService{} + // Exercise generation ordering even when the previous timestamp is ahead of the clock. + oldGeneration := time.Now().Add(time.Minute).UnixMilli() + if err := database.GetDB().Model(node).Updates(map[string]any{ + "config_dirty": true, "config_dirty_at": oldGeneration, + }).Error; err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + reconciled := make(chan error, 1) + go func() { reconciled <- inboundSvc.ReconcileNode(ctx, remote, node) }() + waitTrafficWriterSignal(t, listStarted, "reconcile never reached the remote list") + + client := model.Client{Email: "during-reconcile@example.test", ID: uuid.NewString(), Enable: true} + if needRestart, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); needRestart || err != nil { + t.Fatalf("add during reconcile: restart=%t err=%v", needRestart, err) + } + if got := fast.addClient.Load(); got != 0 { + t.Fatalf("%d incremental pushes overlapped a reconcile of older settings", got) + } + release() + if err := waitTrafficWriterErr(t, reconciled); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if strings.Contains(pushed, client.Email) { + t.Fatalf("first reconcile should still carry the pre-add settings, got %s", pushed) + } + default: + t.Fatal("first reconcile did not push the captured configuration") + } + + if err := nodeSvc.ClearNodeDirty(node.Id, oldGeneration); err != nil { + t.Fatal(err) + } + _, _, dirty, generation, err := nodeSvc.NodeSyncState(node.Id) + if err != nil || !dirty || generation <= oldGeneration { + t.Fatalf("new generation lost after stale reconcile: dirty=%t generation=%d previous=%d err=%v", dirty, generation, oldGeneration, err) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if !strings.Contains(pushed, client.Email) { + t.Fatalf("next reconcile did not deliver the committed client: %s", pushed) + } + default: + t.Fatal("next reconcile did not push the new configuration") + } +} + +func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const primaryTag, blockerTag = "in-46013", "in-46014" + const email = "recreated@example.test" + firstPush := make(chan struct{}) + releaseFirstPush := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseFirstPush) }) + var hasClient atomic.Bool + hasClient.Store(true) + var adds, deletes atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}} + case "/panel/api/clients/add": + if adds.Add(1) == 1 { + close(firstPush) + select { + case <-r.Context().Done(): + return + case <-releaseFirstPush: + } + } + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + hasClient.Store(strings.Contains(r.Form.Get("settings"), "recreated configuration")) + case "/panel/api/inbounds/update/2": + case "/panel/api/clients/del/" + email: + deletes.Add(1) + hasClient.Store(false) + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + var wg sync.WaitGroup + t.Cleanup(func() { + release() + wg.Wait() + }) + + node := reconcileTestNode(t, server, "reconcile-full-delete", "all", nil) + remote := runtime.NewRemote(node, nil) + mgr.SetRuntimeOverride(node.Id, remote) + client := model.Client{Email: email, ID: uuid.NewString(), SubID: "reconcile-recreated", Enable: true} + inbound := nodeInbound(t, node.Id, 46013, []model.Client{client}) + blocker := nodeInbound(t, node.Id, 46014, nil) + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + addPayload := &model.Inbound{Id: blocker.Id, Protocol: model.VLESS, Settings: clientsSettings(t, []model.Client{{ + Email: "first-push@example.test", ID: uuid.NewString(), Enable: true, + }})} + async := func(run func() error) <-chan error { + done := make(chan error, 1) + wg.Go(func() { done <- run() }) + return done + } + waitUntil := func(message string, ready func() bool) { + t.Helper() + deadline := time.Now().Add(time.Second) + for !ready() { + if time.Now().After(deadline) { + t.Fatal(message) + } + time.Sleep(5 * time.Millisecond) + } + } + + added := async(func() error { + _, err := clientSvc.AddInboundClient(inboundSvc, addPayload) + return err + }) + waitTrafficWriterSignal(t, firstPush, "first AddClient never reached the node") + ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second) + defer cancel() + reconciled := async(func() error { return inboundSvc.ReconcileNode(ctx, remote, node) }) + waitUntil("reconcile did not queue behind the first add", func() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + queue := nodeConfigDispatch[node.Id] + return queue != nil && queue.reconciles > 0 + }) + deleted := async(func() error { + _, err := clientSvc.DelInboundClientByEmail(inboundSvc, inbound.Id, email, true, true) + return err + }) + waitUntil("full delete did not commit behind the reconcile", func() bool { + current, err := inboundSvc.GetInbound(inbound.Id) + return err == nil && !strings.Contains(current.Settings, email) + }) + client.Comment = "recreated configuration" + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + release() + for _, done := range []<-chan error{added, reconciled, deleted} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + if adds.Load() != 1 || deletes.Load() != 1 || hasClient.Load() { + t.Fatalf("expected one add then reconcile and full delete, got adds=%d deletes=%d client=%t", adds.Load(), deletes.Load(), hasClient.Load()) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + if !hasClient.Load() { + t.Fatal("stale fingerprint caused reconcile to skip restoring the recreated client") + } +} diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6f855bda0..d197bc4fb 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -137,6 +137,16 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, return nil } nodeID := n.Id + turn := reserveNodeConfigTurn(nodeID, nodeFullReconcile) + defer turn.release() + select { + case <-turn.ready: + case <-ctx.Done(): + return ctx.Err() + } + if err := ctx.Err(); err != nil { + return err + } db := database.GetDB() var inbounds []*model.Inbound if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil { diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index ce6f56f45..2aee90d13 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -34,6 +34,7 @@ func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraff func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart bool, clientsDisabled bool, err error) { var disabledNodeIDs []int var remotePlans []trafficInboundUpdatePlan + var remoteTurns map[int]*nodeConfigTurn var renewed []string committed := false // The periodic poll takes the background lane: an operator's save or reset @@ -46,6 +47,9 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b committed = true var inner error needRestart, clientsDisabled, disabledNodeIDs, remotePlans, renewed, inner = s.maintainTrafficLocked() + if inner == nil { + remoteTurns = reserveTrafficRemoteTurns(remotePlans) + } return inner }) if err != nil { @@ -55,9 +59,16 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b } return } + defer func() { + for _, turn := range remoteTurns { + if turn != nil { + turn.release() + } + } + }() s.resetMtprotoClientQuotas(renewed) // Off the serial writer: a hanging node must not stall traffic accounting. - needRestart = s.applyTrafficRemotePlans(remotePlans) || needRestart + needRestart = s.applyTrafficRemotePlans(remotePlans, remoteTurns) || needRestart if len(disabledNodeIDs) > 0 { s.restartRemoteNodesOnDepletion(disabledNodeIDs) } diff --git a/internal/web/service/inbound_traffic_apply.go b/internal/web/service/inbound_traffic_apply.go index d2d65afd5..03c87fd0f 100644 --- a/internal/web/service/inbound_traffic_apply.go +++ b/internal/web/service/inbound_traffic_apply.go @@ -7,6 +7,7 @@ import ( "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" @@ -60,32 +61,56 @@ func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error { return nil } -// applyTrafficRemotePlans is bounded like every per-client node push: the nodes are -// already dirty, so an offline or slow one defers to the reconcile. -func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan) bool { +// Reserve on the writer after maintenance commits so a newer client edit cannot pass it. +func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) map[int]*nodeConfigTurn { + if len(plans) == 0 { + return nil + } + turns := make(map[int]*nodeConfigTurn) + for i := range plans { + if id := plans[i].newInbound.NodeID; id != nil { + if _, seen := turns[*id]; !seen { + turns[*id] = reserveNodeConfigTurn(*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 map[int]*nodeConfigTurn) bool { byNode := make(map[int][]int) var nodeIDs []int for i := range plans { - nodeID := 0 - if plans[i].newInbound.NodeID != nil { - nodeID = *plans[i].newInbound.NodeID + id := plans[i].newInbound.NodeID + if id == nil || turns[*id] == 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 { - // One budget per node, not per inbound: a node choosing how many inbounds it reports - // must not choose how long the sync job waits on it before serving other nodes. + turn := turns[nodeIDs[n]] + defer turn.release() ctx, cancel := nodePushContext() defer cancel() + select { + case <-turn.ready: + case <-ctx.Done(): + return false + } indexes := byNode[nodeIDs[n]] nodeFailed, nodePanics := fanoutInboundResults(indexes, inboundFanoutConcurrency, func(k int) bool { plan := &plans[indexes[k]] 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) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 25ed1f493..d038d9cc0 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -1076,11 +1076,12 @@ func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error { if tx == nil { return errors.New("nil db transaction") } + now := time.Now().UnixMilli() return tx.Model(model.Node{}). Where("id = ?", id). Updates(map[string]any{ "config_dirty": true, - "config_dirty_at": time.Now().UnixMilli(), + "config_dirty_at": gorm.Expr(database.GreatestExpr("COALESCE(config_dirty_at, 0) + 1", "?"), now), }).Error } diff --git a/internal/web/service/node_reset_undelivered_test.go b/internal/web/service/node_reset_undelivered_test.go index 278d1c2b0..00d300357 100644 --- a/internal/web/service/node_reset_undelivered_test.go +++ b/internal/web/service/node_reset_undelivered_test.go @@ -388,7 +388,7 @@ func TestTrafficRemotePlansWaitOneBudgetPerNode(t *testing.T) { plans[i] = trafficInboundUpdatePlan{oldInbound: ib, newInbound: ib} } start := time.Now() - (&InboundService{}).applyTrafficRemotePlans(plans) + (&InboundService{}).applyTrafficRemotePlans(plans, reserveTrafficRemoteTurns(plans)) if took := time.Since(start); took > nodeClientPushTimeout+2*time.Second { t.Fatalf("pushing %d inbounds to one hanging node took %v", len(plans), took) } diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index a40b17484..017fc8acf 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -167,6 +167,11 @@ func drainTrafficWriter(adminQueue, bgQueue chan *trafficWriteRequest) { // remote node call would stall all traffic accounting for up to the remote // timeout. Apply runtime changes after this returns. func runSerializedTx(fn func(tx *gorm.DB) error) error { + return runSerializedTxThen(fn, nil) +} + +// afterCommit runs on the writer in commit order and must not wait or perform I/O. +func runSerializedTxThen(fn func(tx *gorm.DB) error, afterCommit func()) error { return submitTrafficWrite(func() error { state := &serializedTx{} err := database.GetDB().Transaction(func(tx *gorm.DB) error { @@ -176,6 +181,9 @@ func runSerializedTx(fn func(tx *gorm.DB) error) error { if err == nil { // Still on the writer, so no node merge runs between the commit and the lift. withdrawClientTombstones(state.createdClientEmails...) + if afterCommit != nil { + afterCommit() + } } return err })