fix(nodes): bound ordered client dispatch and scope cache invalidation

Run independent inbounds in parallel while full reconciliation and permanent deletes retain node-wide ordering. Bound queue waits and live batches, and invalidate only cached payloads affected by a remote client deletion.
This commit is contained in:
Hamed Sanaei
2026-11-30 23:16:19 +03:30
parent e80af331eb
commit 4e0fb882bf
11 changed files with 266 additions and 114 deletions
+3 -3
View File
@@ -147,10 +147,10 @@ jobs:
- 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
go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeWideDeleteInvalidatesSettingsSentByQueuedReconcile|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
if [ "$passed" -ne 5 ]; then
echo "expected 5 passing PostgreSQL node client ordering tests, got $passed" >&2
exit 1
fi
+8 -9
View File
@@ -417,15 +417,14 @@ 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",
"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)",
"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)",
}
// A Remote method with no cell is how activeInbounds and bulkResetTraffic
@@ -65,6 +65,38 @@ func TestReconcileInbound_SkipsUnchanged(t *testing.T) {
}
}
func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) {
for _, response := range []struct {
name string
body string
failed bool
}{
{name: "acknowledged", body: `{"success":true}`},
{name: "uncertain", body: `{"success":false,"msg":"apply failed"}`, failed: true},
} {
t.Run(response.name, func(t *testing.T) {
srv, _ := newCountingNodeServer(t, response.body)
r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
affected := &model.Inbound{Tag: "in-1", Protocol: model.VLESS, Settings: `{"clients":[{"email":"delete@example.test"}]}`}
unaffected := &model.Inbound{Tag: "in-2", Protocol: model.VLESS, Settings: `{"clients":[{"email":"keep@example.test"}]}`}
r.AdoptInboundAlias(affected, RemoteInboundOption{Tag: "adopted-1", Id: 1})
r.AdoptInboundAlias(unaffected, RemoteInboundOption{Tag: "adopted-2", Id: 2})
if err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed {
t.Fatalf("unexpected delete result: %v", err)
}
if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed {
t.Fatalf("unaffected inbound: pushed=%v err=%v", pushed, err)
}
if pushed, err := r.ReconcileInbound(t.Context(), affected, true); err != nil || !pushed {
t.Fatalf("affected inbound: pushed=%v err=%v", pushed, err)
}
if id, err := r.resolveRemoteID(t.Context(), unaffected.Tag); err != nil || id != 2 {
t.Fatalf("unaffected alias: id=%d err=%v", id, err)
}
})
}
}
type nodeCallCounts struct {
adds atomic.Int32
inboundUpdates atomic.Int32
+47 -16
View File
@@ -97,7 +97,7 @@ type Remote struct {
// pushedFP holds the fingerprint of the last inbound wire payload successfully
// pushed, keyed by panel-side tag, so reconcile can skip re-sending an
// unchanged inbound. Guarded by mu; dropped with the Remote on node config change.
pushedFP map[string]string
pushedFP map[string]pushedInboundState
// supportsZstd is learned from the node's X-3x-Node-Caps response header; once
// seen, config pushes to this node are zstd-compressed. Old nodes never set
// it, so they keep receiving plain bodies (mixed-version safe).
@@ -137,7 +137,7 @@ func NewRemote(n *model.Node, r NodeEgressResolver) *Remote {
snapshotGate: make(chan struct{}, 1),
remoteIDByTag: make(map[string]int),
adoptedAliases: make(map[string]string),
pushedFP: make(map[string]string),
pushedFP: make(map[string]pushedInboundState),
egressResolver: r,
}
}
@@ -652,7 +652,7 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists
r.mu.RLock()
prev, ok := r.pushedFP[ib.Tag]
r.mu.RUnlock()
if ok && prev == fp {
if ok && prev.fingerprint == fp {
return false, nil
}
} else {
@@ -667,9 +667,9 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists
// recordPushedInbound stamps the fingerprint after a full-payload push — the
// only operation that proves the node holds the entire wire payload.
func (r *Remote) recordPushedInbound(ib *model.Inbound) {
fp := wireFingerprint(wireInbound(ib, r.node.Id))
state := stampPushedInbound(ib, r.node.Id)
r.mu.Lock()
r.pushedFP[ib.Tag] = fp
r.pushedFP[ib.Tag] = state
r.mu.Unlock()
}
@@ -690,13 +690,6 @@ 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) {
@@ -717,11 +710,12 @@ func (r *Remote) ForgetInbound(tag string) {
// AdoptInboundAlias records a deployed alias without mutating either panel.
// The runtime association is rediscovered after a master restart.
func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) {
state := stampPushedInbound(ib, r.node.Id)
r.mu.Lock()
r.remoteIDByTag[remote.Tag] = remote.Id
r.remoteIDByTag[ib.Tag] = remote.Id
r.adoptedAliases[ib.Tag] = remote.Tag
r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id))
r.pushedFP[ib.Tag] = state
r.mu.Unlock()
}
@@ -742,14 +736,50 @@ func (r *Remote) AdoptedInboundAliases() []string {
// the next reconcile re-sends the full inbound.
func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) {
prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id))
nextFP := wireFingerprint(wireInbound(ib, r.node.Id))
next := stampPushedInbound(ib, r.node.Id)
r.mu.Lock()
if r.pushedFP[ib.Tag] == prevFP {
r.pushedFP[ib.Tag] = nextFP
if r.pushedFP[ib.Tag].fingerprint == prevFP {
r.pushedFP[ib.Tag] = next
}
r.mu.Unlock()
}
type pushedInboundClient struct {
Email string `json:"email"`
}
type pushedInboundState struct {
fingerprint string
clients []pushedInboundClient
clientsKnown bool
}
func stampPushedInbound(ib *model.Inbound, nodeID int) pushedInboundState {
var settings struct {
Clients []pushedInboundClient `json:"clients"`
}
err := json.Unmarshal([]byte(ib.Settings), &settings)
return pushedInboundState{
fingerprint: wireFingerprint(wireInbound(ib, nodeID)),
clients: settings.Clients,
clientsKnown: err == nil,
}
}
// A node-wide delete can remove a client from several inbounds, even when its
// reply times out. Only those previously stamped with that client can change.
func (r *Remote) forgetPushedClient(email string) {
r.mu.Lock()
defer r.mu.Unlock()
for tag, state := range r.pushedFP {
if !state.clientsKnown || slices.ContainsFunc(state.clients, func(client pushedInboundClient) bool {
return client.Email == email
}) {
delete(r.pushedFP, tag)
}
}
}
// wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect.
func wireFingerprint(v url.Values) string {
sum := sha256.Sum256([]byte(v.Encode()))
@@ -809,6 +839,7 @@ func (r *Remote) DeleteClient(ctx context.Context, email string) error {
}
_, err := r.do(ctx, http.MethodPost,
"panel/api/clients/del/"+url.PathEscape(email), nil)
r.forgetPushedClient(email)
if err == nil {
return nil
}
+3 -9
View File
@@ -845,7 +845,7 @@ func (s *ClientService) bulkAdjustInboundClients(
if perr != nil {
logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr)
} else if push {
mutation.push(rt, oldInbound, func() bool {
mutation.push(rt, oldInbound, func(ctx context.Context) bool {
for email := range foundEmails {
entry := plan[email]
updated := *entry.record.ToClient()
@@ -859,9 +859,7 @@ func (s *ClientService) bulkAdjustInboundClients(
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
@@ -1249,11 +1247,9 @@ func (s *ClientService) bulkDelInboundClients(
if perr != nil {
logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr)
} else if push {
mutation.push(rt, oldInbound, func() bool {
mutation.push(rt, oldInbound, func(ctx context.Context) 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
@@ -1859,13 +1855,11 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
}
}
} else if push {
mutation.push(rt, oldInbound, func() bool {
mutation.push(rt, oldInbound, func(ctx context.Context) 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
+4 -12
View File
@@ -288,14 +288,12 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
return needRestart, perr
}
if push && len(targets) <= nodeBulkPushThreshold {
mutation.push(rt, oldInbound, func() bool {
mutation.push(rt, oldInbound, func(ctx context.Context) 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
@@ -709,15 +707,13 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
}
} else if push && len(clients) <= nodeBulkPushThreshold {
mutation.push(rt, oldInbound, func() bool {
mutation.push(rt, oldInbound, func(ctx context.Context) 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)
return false
@@ -1194,9 +1190,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
}
}
} else if push {
mutation.push(rt, oldInbound, func() bool {
ctx, cancel := nodePushContext()
defer cancel()
mutation.push(rt, oldInbound, func(ctx context.Context) bool {
if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil {
logger.Warning("Error in updating client on", rt.Name(), ":", err)
return false
@@ -1368,9 +1362,7 @@ 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 {
mutation.push(rt, oldInbound, func() bool {
ctx, cancel := nodePushContext()
defer cancel()
mutation.push(rt, oldInbound, func(ctx context.Context) bool {
var err error
if fullDelete {
err = rt.DeleteClient(ctx, email)
+83 -33
View File
@@ -2,6 +2,7 @@ package service
import (
"container/list"
"context"
"sync"
"gorm.io/gorm"
@@ -16,17 +17,26 @@ var (
)
type nodeConfigQueue struct {
turns list.List
groups list.List
reconciles int
}
// 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
queue *nodeConfigQueue
position *list.Element
ready chan struct{}
work nodeConfigWork
behindReconcile bool
nodeID int
inboundID int
queue *nodeConfigQueue
group *nodeConfigGroup
position *list.Element
ready chan struct{}
work nodeConfigWork
}
type nodeConfigWork uint8
@@ -37,8 +47,7 @@ const (
nodeFullReconcile
)
// Per-node ordering also covers full client deletes, which can affect sibling inbounds.
func reserveNodeConfigTurn(nodeID int, work nodeConfigWork) *nodeConfigTurn {
func reserveNodeConfigTurn(nodeID, inboundID int, work nodeConfigWork) *nodeConfigTurn {
nodeConfigDispatchMu.Lock()
defer nodeConfigDispatchMu.Unlock()
q := nodeConfigDispatch[nodeID]
@@ -46,41 +55,81 @@ func reserveNodeConfigTurn(nodeID int, work nodeConfigWork) *nodeConfigTurn {
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.
// 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
}
turn := &nodeConfigTurn{
nodeID: nodeID, queue: q, ready: make(chan struct{}), work: work, behindReconcile: q.reconciles > 0,
exclusive := work != nodeClientDelta
if exclusive {
inboundID = 0
}
turn.position = q.turns.PushBack(turn)
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.turns.Front() == turn.position {
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 := t.queue
wasFirst := t.position == q.turns.Front()
q.turns.Remove(t.position)
q, group := t.queue, t.group
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 next := q.turns.Front(); next == nil {
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 wasFirst {
close(next.Value.(*nodeConfigTurn).ready)
} else if wasReady {
for _, lane := range next.Value.(*nodeConfigGroup).inbounds {
close(lane.Front().Value.(*nodeConfigTurn).ready)
}
}
}
@@ -118,27 +167,28 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo
}
return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID)
}, func() {
m.turn = reserveNodeConfigTurn(nodeID, work)
m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work)
})
}
func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func() bool) {
func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context) bool) {
m.unlock()
if m.turn == nil {
return
}
<-m.turn.ready
waitCtx, stopWaiting := nodePushContext()
ready := m.turn.wait(waitCtx)
stopWaiting()
if !ready {
return
}
ctx, cancel := nodePushContext()
defer cancel()
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)
}
if remote, ok := rt.(*runtime.Remote); ok && !complete {
remote.ForgetPushedInbound(inbound.Tag)
}
}()
complete = apply()
complete = apply(ctx)
}
+69 -8
View File
@@ -191,6 +191,10 @@ func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) {
waitSettings(ib.Id, client.Email, false)
sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) })
waitSettings(siblingInbound.Id, sameNode.Email, true)
expectCall("add " + sameNode.Email)
if err := waitTrafficWriterErr(t, sameNodeDone); err != nil {
t.Fatal(err)
}
controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) })
select {
case err := <-controlDone:
@@ -212,8 +216,7 @@ func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) {
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} {
for i, done := range []<-chan error{add, update, detach} {
select {
case err := <-done:
if err != nil {
@@ -230,6 +233,57 @@ func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) {
}
}
func TestNodeClientQueueTimeoutDefersCommittedDelta(t *testing.T) {
setupClientNodeOrderDB(t)
nodeID, fake := setupNodeRuntime(t)
inbound := nodeInbound(t, nodeID, 46004, nil)
first := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta)
t.Cleanup(first.release)
email := "wait-deadline@example.test"
data := &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{{
Email: email, ID: uuid.NewString(), Enable: true,
}})}
inboundSvc, clientSvc := &InboundService{}, &ClientService{}
done := make(chan error, 1)
completed := make(chan struct{})
t.Cleanup(func() {
first.release()
<-completed
})
go func() {
defer close(completed)
_, err := clientSvc.AddInboundClient(inboundSvc, data)
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(nodeClientPushTimeout + 2*time.Second):
t.Fatal("client request waited for a dispatch turn past its deadline")
}
if fake.addClient.Load() != 0 {
t.Fatal("expired client push overtook the in-flight operation")
}
current, err := inboundSvc.GetInbound(inbound.Id)
if err != nil || !strings.Contains(current.Settings, email) {
t.Fatalf("expired queue wait lost the committed client: %v", err)
}
if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty {
t.Fatalf("expired queue wait did not leave the node dirty: dirty=%v err=%v", dirty, err)
}
first.release()
next := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta)
defer next.release()
select {
case <-next.ready:
default:
t.Fatal("expired dispatch turn blocked the next mutation")
}
}
func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) {
setupClientNodeOrderDB(t)
nodeID, _ := setupNodeRuntime(t)
@@ -398,19 +452,19 @@ func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) {
func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
setupClientNodeOrderDB(t)
mgr := useTestRuntimeManager(t)
const primaryTag, blockerTag = "in-46013", "in-46014"
const primaryTag, blockerTag, recreatedTag = "in-46013", "in-46014", "in-46015"
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
var adds, deletes, blockerUpdates, recreatedUpdates 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}}
obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}, {"id": 3, "tag": recreatedTag}}
case "/panel/api/clients/add":
if adds.Add(1) == 1 {
close(firstPush)
@@ -421,12 +475,15 @@ func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
}
}
case "/panel/api/inbounds/update/1":
case "/panel/api/inbounds/update/3":
recreatedUpdates.Add(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":
blockerUpdates.Add(1)
case "/panel/api/clients/del/" + email:
deletes.Add(1)
hasClient.Store(false)
@@ -449,6 +506,7 @@ func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
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)
recreated := nodeInbound(t, node.Id, 46015, 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,
@@ -493,7 +551,7 @@ func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
})
client.Comment = "recreated configuration"
if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{
Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}),
Id: recreated.Id, Protocol: recreated.Protocol, Settings: clientsSettings(t, []model.Client{client}),
}); err != nil {
t.Fatal(err)
}
@@ -509,7 +567,10 @@ func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
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")
if !hasClient.Load() || recreatedUpdates.Load() != 2 {
t.Fatalf("reconcile failed to restore recreated client on sibling inbound (pushes=%d)", recreatedUpdates.Load())
}
if blockerUpdates.Load() != 1 {
t.Fatalf("reconcile re-sent unrelated inbound (pushes=%d)", blockerUpdates.Load())
}
}
+2 -7
View File
@@ -137,16 +137,11 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote,
return nil
}
nodeID := n.Id
turn := reserveNodeConfigTurn(nodeID, nodeFullReconcile)
turn := reserveNodeConfigTurn(nodeID, 0, nodeFullReconcile)
defer turn.release()
select {
case <-turn.ready:
case <-ctx.Done():
if !turn.wait(ctx) {
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 {
+1 -1
View File
@@ -34,7 +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 remoteTurns []*nodeConfigTurn
var renewed []string
committed := false
// The periodic poll takes the background lane: an operator's save or reset
+14 -16
View File
@@ -62,28 +62,27 @@ func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error {
}
// Reserve on the writer after maintenance commits so a newer client edit cannot pass it.
func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) map[int]*nodeConfigTurn {
func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) []*nodeConfigTurn {
if len(plans) == 0 {
return nil
}
turns := make(map[int]*nodeConfigTurn)
turns := make([]*nodeConfigTurn, len(plans))
for i := range plans {
if id := plans[i].newInbound.NodeID; id != nil {
if _, seen := turns[*id]; !seen {
turns[*id] = reserveNodeConfigTurn(*id, nodeClientDelta)
}
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 map[int]*nodeConfigTurn) bool {
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[*id] == nil {
if id == nil || turns[i] == nil {
continue
}
nodeID := *id
@@ -93,18 +92,17 @@ func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePla
byNode[nodeID] = append(byNode[nodeID], i)
}
failed, panics := fanoutInboundResults(nodeIDs, nodeFanoutConcurrency, func(n int) bool {
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]]
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)