Skip to content

Commit 1cf1af4

Browse files
authored
fix(gateway): drain admitted node results before disconnect (#119246)
* fix(gateway): drain admitted node results on close * fix(gateway): keep idle node cleanup synchronous * fix(gateway): preserve node revocation during drain * refactor(gateway): keep websocket handler within line budget
1 parent 47bd1bb commit 1cf1af4

8 files changed

Lines changed: 382 additions & 15 deletions
Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
// Node result/close ordering tests keep admitted terminal frames authoritative.
2+
import { randomUUID } from "node:crypto";
3+
import { afterEach, expect, test, vi } from "vitest";
4+
import { writeConfigFile } from "../config/config.js";
5+
import { approveNodePairing, requestNodePairing } from "../infra/node-pairing.js";
6+
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
7+
import { pairDeviceIdentity } from "./device-authz.test-helpers.js";
8+
import { GatewayNodeLifecycleDispatchTracker } from "./server/ws-connection/node-lifecycle-dispatch.js";
9+
import { connectGatewayClient } from "./test-helpers.e2e.js";
10+
import { installGatewayTestHooks, startServer } from "./test-helpers.js";
11+
12+
const pairingRead = vi.hoisted(() => ({
13+
blocked: null as Promise<void> | null,
14+
onBlocked: null as (() => void) | null,
15+
release: null as (() => void) | null,
16+
}));
17+
18+
vi.mock("../infra/node-pairing-state.js", async (importOriginal) => {
19+
const actual = await importOriginal<typeof import("../infra/node-pairing-state.js")>();
20+
return {
21+
...actual,
22+
resolveCurrentNodePairingBinding: async (nodeId: string) => {
23+
const current = await actual.resolveCurrentNodePairingBinding(nodeId);
24+
if (pairingRead.blocked) {
25+
pairingRead.onBlocked?.();
26+
await pairingRead.blocked;
27+
}
28+
return current;
29+
},
30+
};
31+
});
32+
33+
installGatewayTestHooks({ scope: "suite" });
34+
35+
afterEach(() => {
36+
vi.restoreAllMocks();
37+
pairingRead.blocked = null;
38+
pairingRead.onBlocked = null;
39+
pairingRead.release = null;
40+
});
41+
42+
test.each([
43+
["a terminal node result admitted before close wins over disconnect cleanup", false],
44+
["pairing removal still fences a terminal node result while close drains", true],
45+
] as const)("%s", async (_name, removePairingDuringDrain) => {
46+
const pairedNode = await pairDeviceIdentity({
47+
name: "node-result-before-close",
48+
role: "node",
49+
scopes: [],
50+
clientId: GATEWAY_CLIENT_NAMES.NODE_HOST,
51+
clientMode: GATEWAY_CLIENT_MODES.NODE,
52+
});
53+
const pairing = await requestNodePairing({
54+
nodeId: pairedNode.identity.deviceId,
55+
platform: "linux",
56+
deviceFamily: "Linux",
57+
commands: ["camera.list"],
58+
});
59+
await approveNodePairing(pairing.request.requestId, {
60+
callerScopes: ["operator.pairing", "operator.write"],
61+
});
62+
await writeConfigFile({
63+
gateway: { nodes: { commands: { allow: ["camera.list"] } } },
64+
});
65+
66+
const { port, server } = await startServer("secret");
67+
const url = `ws://127.0.0.1:${port}`;
68+
let operator: Awaited<ReturnType<typeof connectGatewayClient>> | undefined;
69+
let node: Awaited<ReturnType<typeof connectGatewayClient>> | undefined;
70+
let resolveInvokeFrame:
71+
| ((frame: { id: string; nodeId: string; command: string }) => void)
72+
| undefined;
73+
const invokeFrame = new Promise<{ id: string; nodeId: string; command: string }>((resolve) => {
74+
resolveInvokeFrame = resolve;
75+
});
76+
77+
try {
78+
operator = await connectGatewayClient({
79+
url,
80+
token: "secret",
81+
role: "operator",
82+
clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
83+
clientDisplayName: "node result close operator",
84+
mode: GATEWAY_CLIENT_MODES.BACKEND,
85+
scopes: ["operator.admin", "operator.read", "operator.write"],
86+
});
87+
node = await connectGatewayClient({
88+
url,
89+
token: "secret",
90+
role: "node",
91+
clientName: GATEWAY_CLIENT_NAMES.NODE_HOST,
92+
clientDisplayName: "node result close host",
93+
mode: GATEWAY_CLIENT_MODES.NODE,
94+
platform: "linux",
95+
deviceFamily: "Linux",
96+
scopes: [],
97+
commands: ["camera.list"],
98+
deviceIdentity: pairedNode.identity,
99+
onEvent: (event) => {
100+
if (event.event !== "node.invoke.request" || !event.payload) {
101+
return;
102+
}
103+
resolveInvokeFrame?.(event.payload as { id: string; nodeId: string; command: string });
104+
},
105+
});
106+
await vi.waitFor(async () => {
107+
const listed = await operator?.request<{
108+
nodes?: Array<{ nodeId?: string; connected?: boolean; commands?: string[] }>;
109+
}>("node.list", {}, { timeoutMs: 10_000 });
110+
expect(listed?.nodes?.find((entry) => entry.nodeId === pairedNode.identity.deviceId)).toEqual(
111+
expect.objectContaining({
112+
connected: true,
113+
commands: ["camera.list"],
114+
}),
115+
);
116+
});
117+
118+
const invoked = operator.request<{
119+
ok: boolean;
120+
nodeId: string;
121+
command: string;
122+
payload: unknown;
123+
}>(
124+
"node.invoke",
125+
{
126+
nodeId: pairedNode.identity.deviceId,
127+
command: "camera.list",
128+
timeoutMs: 10_000,
129+
idempotencyKey: randomUUID(),
130+
},
131+
{ timeoutMs: 10_000 },
132+
);
133+
const frame = await Promise.race([
134+
invokeFrame,
135+
invoked.then(
136+
() => {
137+
throw new Error("node.invoke settled without sending a node request");
138+
},
139+
(error: unknown) => {
140+
throw error instanceof Error ? error : new Error(String(error));
141+
},
142+
),
143+
]);
144+
145+
pairingRead.blocked = new Promise<void>((resolve) => {
146+
pairingRead.release = resolve;
147+
});
148+
const pairingReadStarted = new Promise<void>((resolve) => {
149+
pairingRead.onBlocked = resolve;
150+
});
151+
const drainSpy = vi.spyOn(GatewayNodeLifecycleDispatchTracker.prototype, "drain");
152+
const resultAck = node
153+
.request(
154+
"node.invoke.result",
155+
{
156+
id: frame.id,
157+
nodeId: frame.nodeId,
158+
ok: true,
159+
payloadJSON: JSON.stringify({ completed: "before-close" }),
160+
},
161+
{ timeoutMs: 10_000 },
162+
)
163+
.catch((error: unknown) => error);
164+
await pairingReadStarted;
165+
const rawNodeSocket = Reflect.get(node, "ws") as { terminate?: () => void } | null;
166+
const stopped = node.stopAndWait({ timeoutMs: 1_000 });
167+
rawNodeSocket?.terminate?.();
168+
await stopped;
169+
node = undefined;
170+
await vi.waitFor(() => expect(drainSpy).toHaveBeenCalledOnce());
171+
if (removePairingDuringDrain) {
172+
await operator.request(
173+
"node.pair.remove",
174+
{ nodeId: pairedNode.identity.deviceId },
175+
{ timeoutMs: 10_000 },
176+
);
177+
}
178+
pairingRead.release?.();
179+
180+
if (removePairingDuringDrain) {
181+
await expect(invoked).rejects.toThrow("node pairing changed while invocation was active");
182+
} else {
183+
await expect(invoked).resolves.toMatchObject({
184+
ok: true,
185+
nodeId: pairedNode.identity.deviceId,
186+
command: "camera.list",
187+
payload: { completed: "before-close" },
188+
});
189+
}
190+
await resultAck;
191+
await vi.waitFor(async () => {
192+
const listed = await operator?.request<{
193+
nodes?: Array<{ nodeId?: string; connected?: boolean }>;
194+
}>("node.list", {}, { timeoutMs: 10_000 });
195+
const listedNode = listed?.nodes?.find(
196+
(entry) => entry.nodeId === pairedNode.identity.deviceId,
197+
);
198+
if (removePairingDuringDrain) {
199+
expect(listedNode).toBeUndefined();
200+
} else {
201+
expect(listedNode?.connected).toBe(false);
202+
}
203+
});
204+
} finally {
205+
releaseBlockedPairingRead();
206+
await Promise.allSettled([
207+
...(node ? [node.stopAndWait({ timeoutMs: 1_000 })] : []),
208+
...(operator ? [operator.stopAndWait({ timeoutMs: 1_000 })] : []),
209+
]);
210+
await server.close();
211+
}
212+
});
213+
214+
function releaseBlockedPairingRead(): void {
215+
pairingRead.release?.();
216+
pairingRead.onBlocked = null;
217+
pairingRead.blocked = null;
218+
pairingRead.release = null;
219+
}

‎src/gateway/server/ws-connection.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ import {
4040
shouldLimitMissingCredentialAuthLog,
4141
} from "./ws-connection/handshake-auth-log-limiter.js";
4242
import type { WsOriginCheckMetrics } from "./ws-connection/message-handler.js";
43+
import {
44+
GatewayNodeLifecycleDispatchTracker,
45+
NODE_LIFECYCLE_DISPATCH_DRAIN_TIMEOUT_MS,
46+
} from "./ws-connection/node-lifecycle-dispatch.js";
4347
import {
4448
attachWorkerWsMessageHandler,
4549
type WorkerConnectionService,
@@ -318,6 +322,7 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
318322
let lastFrameMethod: string | undefined;
319323
let lastFrameId: string | undefined;
320324
let hasReceivedPreauthFrame = false;
325+
const nodeLifecycleDispatch = new GatewayNodeLifecycleDispatchTracker();
321326

322327
socket.once("message", () => {
323328
hasReceivedPreauthFrame = true;
@@ -357,6 +362,7 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
357362
let pingTimer: ReturnType<typeof setInterval> | undefined;
358363
let cleanupWorkerConnection: (() => void) | undefined;
359364
let awaitingPong = false;
365+
let retainClientUntilNodeDrain = false;
360366
const handshakeTimeoutMs = resolvePreauthHandshakeTimeoutMs({
361367
configuredTimeoutMs: params.preauthHandshakeTimeoutMs,
362368
});
@@ -379,27 +385,29 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
379385
}
380386
}, handshakeTimeoutMs);
381387

382-
const close = (code = 1000, reason?: string) => {
388+
const retireTransport = (code = 1000, reason?: string) => {
383389
if (closed) {
384390
return;
385391
}
386392
closed = true;
387393
clearTimeout(handshakeTimer);
388-
if (pingTimer !== undefined) {
389-
clearInterval(pingTimer);
390-
}
394+
clearInterval(pingTimer);
391395
cleanupWorkerConnection?.();
392396
releasePreauthBudget();
393-
if (client) {
394-
clients.delete(client);
395-
}
396397
try {
397398
socket.close(code, reason);
398399
} catch {
399400
/* ignore */
400401
}
401402
};
402403

404+
const close = (code = 1000, reason?: string) => {
405+
retireTransport(code, reason);
406+
if (client && !retainClientUntilNodeDrain) {
407+
clients.delete(client);
408+
}
409+
};
410+
403411
const send = (obj: unknown) => {
404412
if (closed) {
405413
return;
@@ -476,7 +484,7 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
476484
normalizeLowercaseStringOrEmpty(requestUserAgent).startsWith("openclaw/") &&
477485
isLoopbackAddress(remoteAddr);
478486

479-
socket.once("close", (code, reason) => {
487+
const handleSocketClose = async (code: number, reason: Buffer) => {
480488
const durationMs = Date.now() - openedAt;
481489
const logForwardedFor = sanitizeLogValue(forwardedFor);
482490
const logOrigin = sanitizeLogValue(requestOrigin);
@@ -565,7 +573,23 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
565573
context.terminalSessions?.handleDisconnect(connId);
566574
let currentDisconnectedNodeId: string | null = null;
567575
if (client?.connect?.role === "node") {
568-
currentDisconnectedNodeId = context.nodeRegistry.unregister(connId);
576+
// Retire I/O immediately, but keep the client revocable until admitted
577+
// lifecycle work drains; pairing/token removal must still fence it.
578+
retainClientUntilNodeDrain = true;
579+
retireTransport();
580+
try {
581+
if (nodeLifecycleDispatch.hasActive()) {
582+
const drained = await nodeLifecycleDispatch.drain();
583+
if (!drained) {
584+
logGateway.warn(
585+
`node lifecycle dispatch drain timed out after ${NODE_LIFECYCLE_DISPATCH_DRAIN_TIMEOUT_MS}ms conn=${connId}`,
586+
);
587+
}
588+
}
589+
currentDisconnectedNodeId = context.nodeRegistry.unregister(connId);
590+
} finally {
591+
retainClientUntilNodeDrain = false;
592+
}
569593
}
570594
if (
571595
client?.presenceKey &&
@@ -597,6 +621,12 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
597621
endpoint,
598622
});
599623
close();
624+
};
625+
socket.once("close", (code, reason) => {
626+
void handleSocketClose(code, reason).catch((error: unknown) => {
627+
logGateway.error(`websocket close cleanup failed conn=${connId}: ${formatError(error)}`);
628+
close();
629+
});
600630
});
601631

602632
const setClient = (next: GatewayWsClient) => {
@@ -697,6 +727,7 @@ export function attachGatewayWsConnectionHandler(params: AttachGatewayWsConnecti
697727
extraHandlers,
698728
getMethodRegistry,
699729
buildRequestContext,
730+
nodeLifecycleDispatch,
700731
refreshHealthSnapshot,
701732
send,
702733
close,

‎src/gateway/server/ws-connection/authenticated-request-dispatch.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -187,12 +187,17 @@ export function createGatewayAuthenticatedRequestDispatcher(params: {
187187
}
188188
};
189189
const upstreamTrace = parseDiagnosticTraceparent(req.traceparent);
190-
const requestDispatch = upstreamTrace
191-
? runWithDiagnosticTraceContext(
192-
createChildDiagnosticTraceContext(upstreamTrace),
193-
executeRequest,
194-
)
195-
: executeRequest();
190+
const dispatchRequest = () =>
191+
upstreamTrace
192+
? runWithDiagnosticTraceContext(
193+
createChildDiagnosticTraceContext(upstreamTrace),
194+
executeRequest,
195+
)
196+
: executeRequest();
197+
const requestDispatch =
198+
client.connect.role === "node"
199+
? params.handler.nodeLifecycleDispatch.dispatch(req.method, dispatchRequest)
200+
: dispatchRequest();
196201
if (DEVICE_CREDENTIAL_INVALIDATING_METHODS.has(req.method)) {
197202
const barrier = requestDispatch.finally(() => {
198203
if (deviceCredentialMutationBarrier === barrier) {

‎src/gateway/server/ws-connection/message-handler-types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import type { GatewayRequestContext, GatewayRequestHandlers } from "../../server
2020
import type { GatewayWsClient, WsHandshakePhase } from "../ws-types.js";
2121
import type { resolveControlUiAuthPolicy } from "./connect-policy.js";
2222
import type { resolvePairingLocality } from "./handshake-auth-helpers.js";
23+
import type { GatewayNodeLifecycleDispatchTracker } from "./node-lifecycle-dispatch.js";
2324

2425
type SubsystemLogger = ReturnType<typeof createSubsystemLogger>;
2526
type ControlUiAuthPolicy = ReturnType<typeof resolveControlUiAuthPolicy>;
@@ -60,6 +61,7 @@ export type GatewayWsMessageHandlerParams = {
6061
extraHandlers: GatewayRequestHandlers;
6162
getMethodRegistry?: () => GatewayMethodRegistry;
6263
buildRequestContext: () => GatewayRequestContext;
64+
nodeLifecycleDispatch: GatewayNodeLifecycleDispatchTracker;
6365
refreshHealthSnapshot: GatewayRequestContext["refreshHealthSnapshot"];
6466
send: (obj: unknown) => void;
6567
close: (code?: number, reason?: string) => void;

‎src/gateway/server/ws-connection/message-handler.post-connect-health.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import type { HealthSummary } from "../../health/types.js";
2222
import { getOperatorApprovalRuntimeToken } from "../../operator-approval-runtime-token.js";
2323
import { handleGatewayRequest } from "../../server-methods.js";
2424
import type { GatewayRequestContext } from "../../server-methods/types.js";
25+
import { GatewayNodeLifecycleDispatchTracker } from "./node-lifecycle-dispatch.js";
2526

2627
const {
2728
buildGatewaySnapshotMock,
@@ -257,6 +258,7 @@ function attachGatewayHarness(options: {
257258
events: [],
258259
extraHandlers: {},
259260
buildRequestContext: () => ({}) as GatewayRequestContext,
261+
nodeLifecycleDispatch: new GatewayNodeLifecycleDispatchTracker(),
260262
refreshHealthSnapshot:
261263
options.refreshHealthSnapshot ?? vi.fn(async () => createHealthSummary()),
262264
send,

0 commit comments

Comments
 (0)