Skip to content

Commit 5c0a11d

Browse files
committed
refactor(gateway): extract bounded node invocation policies
1 parent 92e71e2 commit 5c0a11d

3 files changed

Lines changed: 95 additions & 96 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
2+
3+
export const NODE_INVOKE_DEADLINE_EXPIRED = Symbol("node invoke deadline expired");
4+
5+
/** Bounds node pairing, wake, policy, and transport preparation by one absolute deadline. */
6+
export async function awaitNodeInvokeWithinDeadline<T>(
7+
operation: () => Promise<T>,
8+
deadlineAtMs: number | undefined,
9+
): Promise<T | typeof NODE_INVOKE_DEADLINE_EXPIRED> {
10+
if (deadlineAtMs === undefined) {
11+
return await operation();
12+
}
13+
if (Math.max(0, deadlineAtMs - Date.now()) === 0) {
14+
return NODE_INVOKE_DEADLINE_EXPIRED;
15+
}
16+
17+
let timer: ReturnType<typeof setTimeout> | undefined;
18+
try {
19+
// Arm the timer before plugin or push code can synchronously consume the
20+
// budget; timer callbacks alone cannot establish an absolute deadline.
21+
const deadline = new Promise<typeof NODE_INVOKE_DEADLINE_EXPIRED>((resolve) => {
22+
// Node overflows long timer delays, so rearm against the real deadline.
23+
const waitForDeadline = () => {
24+
const remainingMs = Math.max(0, deadlineAtMs - Date.now());
25+
if (remainingMs === 0) {
26+
resolve(NODE_INVOKE_DEADLINE_EXPIRED);
27+
return;
28+
}
29+
timer = setTimeout(waitForDeadline, Math.min(remainingMs, MAX_TIMER_TIMEOUT_MS));
30+
};
31+
waitForDeadline();
32+
});
33+
return await Promise.race([
34+
deadline,
35+
operation().then((result) =>
36+
Date.now() >= deadlineAtMs ? NODE_INVOKE_DEADLINE_EXPIRED : result,
37+
),
38+
]);
39+
} finally {
40+
if (timer !== undefined) {
41+
clearTimeout(timer);
42+
}
43+
}
44+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import {
2+
normalizeLowercaseStringOrEmpty,
3+
normalizeOptionalString,
4+
} from "@openclaw/normalization-core/string-coerce";
5+
import { isForegroundRestrictedPluginNodeCommand } from "../node-command-policy.js";
6+
7+
/** Queues only commands that iOS explicitly rejected as requiring the foreground. */
8+
export function shouldQueueAsPendingForegroundAction(params: {
9+
platform?: string;
10+
command: string;
11+
error: unknown;
12+
}): boolean {
13+
const platform = normalizeLowercaseStringOrEmpty(params.platform);
14+
if (!platform.startsWith("ios") && !platform.startsWith("ipados")) {
15+
return false;
16+
}
17+
if (
18+
!isForegroundRestrictedPluginNodeCommand(params.command) &&
19+
!params.command.startsWith("camera.") &&
20+
!params.command.startsWith("screen.") &&
21+
!params.command.startsWith("talk.")
22+
) {
23+
return false;
24+
}
25+
const error =
26+
params.error && typeof params.error === "object"
27+
? (params.error as { code?: unknown; message?: unknown })
28+
: null;
29+
const code = normalizeOptionalString(error?.code)?.toUpperCase() ?? "";
30+
const message = normalizeOptionalString(error?.message)?.toUpperCase() ?? "";
31+
return code === "NODE_BACKGROUND_UNAVAILABLE" || message.includes("BACKGROUND_UNAVAILABLE");
32+
}

‎src/gateway/server-methods/nodes.invoke.ts‎

Lines changed: 19 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import { randomUUID } from "node:crypto";
2-
import { MAX_TIMER_TIMEOUT_MS } from "@openclaw/normalization-core/number-coercion";
3-
import {
4-
normalizeLowercaseStringOrEmpty,
5-
normalizeOptionalString,
6-
} from "@openclaw/normalization-core/string-coerce";
2+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
73
import {
84
ErrorCodes,
95
errorShape,
@@ -13,11 +9,7 @@ import {
139
import { isAdminOnlyNodeInvokeCommand } from "../../infra/node-commands.js";
1410
import { captureNodePairingGeneration } from "../../infra/node-pairing-state.js";
1511
import { isForbiddenBrowserProxyMutation } from "../node-browser-proxy-policy.js";
16-
import {
17-
isForegroundRestrictedPluginNodeCommand,
18-
isNodeCommandAllowed,
19-
resolveNodeCommandAllowlist,
20-
} from "../node-command-policy.js";
12+
import { isNodeCommandAllowed, resolveNodeCommandAllowlist } from "../node-command-policy.js";
2113
import { applyPluginNodeInvokePolicy } from "../node-invoke-plugin-policy.js";
2214
import { sanitizeNodeInvokeParamsForForwarding } from "../node-invoke-sanitize.js";
2315
import { enqueuePendingNodeAction, removePendingNodeAction } from "../node-runtime-state.js";
@@ -38,6 +30,11 @@ import {
3830
respondUnavailableOnThrow,
3931
safeParseJson,
4032
} from "./nodes.helpers.js";
33+
import {
34+
awaitNodeInvokeWithinDeadline,
35+
NODE_INVOKE_DEADLINE_EXPIRED,
36+
} from "./nodes.invoke-deadline.js";
37+
import { shouldQueueAsPendingForegroundAction } from "./nodes.invoke-foreground.js";
4138
import { toPendingParamsJSON } from "./nodes.pending.js";
4239
import {
4340
isNodePairingWorkCurrent,
@@ -58,82 +55,8 @@ const TALK_PTT_COMMANDS = new Set([
5855
"talk.ptt.cancel",
5956
"talk.ptt.once",
6057
]);
61-
const NODE_WAKE_INVOKE_DEADLINE_EXPIRED = Symbol("node wake invoke deadline expired");
6258
const talkPttEventSeqBySessionId = new Map<string, number>();
6359

64-
async function awaitNodeWakeWithinInvokeDeadline<T>(
65-
operation: () => Promise<T>,
66-
deadlineAtMs: number | undefined,
67-
): Promise<T | typeof NODE_WAKE_INVOKE_DEADLINE_EXPIRED> {
68-
if (deadlineAtMs === undefined) {
69-
return await operation();
70-
}
71-
const remainingMs = Math.max(0, deadlineAtMs - Date.now());
72-
if (remainingMs === 0) {
73-
return NODE_WAKE_INVOKE_DEADLINE_EXPIRED;
74-
}
75-
let timer: ReturnType<typeof setTimeout> | undefined;
76-
try {
77-
// Arm the timer before plugin or push code can synchronously consume the
78-
// budget; Node timer callbacks alone cannot establish absolute deadlines.
79-
const deadline = new Promise<typeof NODE_WAKE_INVOKE_DEADLINE_EXPIRED>((resolve) => {
80-
// Node silently overflows long timers; reschedule against the absolute
81-
// deadline so a valid long request never expires or disappears early.
82-
const waitForDeadline = () => {
83-
const remainingMs = Math.max(0, deadlineAtMs - Date.now());
84-
if (remainingMs === 0) {
85-
resolve(NODE_WAKE_INVOKE_DEADLINE_EXPIRED);
86-
return;
87-
}
88-
timer = setTimeout(waitForDeadline, Math.min(remainingMs, MAX_TIMER_TIMEOUT_MS));
89-
};
90-
waitForDeadline();
91-
});
92-
return await Promise.race([
93-
deadline,
94-
operation().then((result) =>
95-
Date.now() >= deadlineAtMs ? NODE_WAKE_INVOKE_DEADLINE_EXPIRED : result,
96-
),
97-
]);
98-
} finally {
99-
if (timer !== undefined) {
100-
clearTimeout(timer);
101-
}
102-
}
103-
}
104-
105-
function isForegroundRestrictedIosCommand(command: string): boolean {
106-
return (
107-
isForegroundRestrictedPluginNodeCommand(command) ||
108-
command.startsWith("camera.") ||
109-
command.startsWith("screen.") ||
110-
command.startsWith("talk.")
111-
);
112-
}
113-
114-
function shouldQueueAsPendingForegroundAction(params: {
115-
platform?: string;
116-
command: string;
117-
error: unknown;
118-
}): boolean {
119-
// iOS cannot run camera/screen/Talk commands in the background. Queue only
120-
// those foreground-only commands when the node explicitly reports that state.
121-
const platform = normalizeLowercaseStringOrEmpty(params.platform);
122-
if (!platform.startsWith("ios") && !platform.startsWith("ipados")) {
123-
return false;
124-
}
125-
if (!isForegroundRestrictedIosCommand(params.command)) {
126-
return false;
127-
}
128-
const error =
129-
params.error && typeof params.error === "object"
130-
? (params.error as { code?: unknown; message?: unknown })
131-
: null;
132-
const code = normalizeOptionalString(error?.code)?.toUpperCase() ?? "";
133-
const message = normalizeOptionalString(error?.message)?.toUpperCase() ?? "";
134-
return code === "NODE_BACKGROUND_UNAVAILABLE" || message.includes("BACKGROUND_UNAVAILABLE");
135-
}
136-
13760
function emitTalkPttNodeEvent(params: {
13861
context: Pick<GatewayRequestContext, "broadcast">;
13962
nodeId: string;
@@ -297,11 +220,11 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
297220
return true;
298221
};
299222
await respondUnavailableOnThrow(respond, async () => {
300-
const generation = await awaitNodeWakeWithinInvokeDeadline(
223+
const generation = await awaitNodeInvokeWithinDeadline(
301224
() => captureNodePairingGeneration(nodeId),
302225
invokeDeadlineAtMs,
303226
);
304-
if (generation === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
227+
if (generation === NODE_INVOKE_DEADLINE_EXPIRED) {
305228
respondIfInvokeExpired();
306229
return;
307230
}
@@ -312,11 +235,11 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
312235
const wakeLifecycle = captureNodeWakeLifecycle(nodeId, generation.key);
313236
try {
314237
const continuePairingWork = async (): Promise<boolean> => {
315-
const pairingCurrent = await awaitNodeWakeWithinInvokeDeadline(
238+
const pairingCurrent = await awaitNodeInvokeWithinDeadline(
316239
() => isNodePairingWorkCurrent({ nodeId, generation, lifecycle: wakeLifecycle }),
317240
invokeDeadlineAtMs,
318241
);
319-
if (pairingCurrent === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
242+
if (pairingCurrent === NODE_INVOKE_DEADLINE_EXPIRED) {
320243
respondIfInvokeExpired();
321244
return false;
322245
}
@@ -344,7 +267,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
344267

345268
// Wake attempts can be shared; expire this caller without aborting a
346269
// push that another live invocation still owns.
347-
const wake = await awaitNodeWakeWithinInvokeDeadline(
270+
const wake = await awaitNodeInvokeWithinDeadline(
348271
() =>
349272
maybeWakeNodeWithApns(nodeId, {
350273
cfg,
@@ -353,7 +276,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
353276
}),
354277
invokeDeadlineAtMs,
355278
);
356-
if (wake === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
279+
if (wake === NODE_INVOKE_DEADLINE_EXPIRED) {
357280
respondIfInvokeExpired();
358281
return;
359282
}
@@ -393,7 +316,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
393316
context.nodeRegistry.getForPairingGeneration(nodeId, generation.key),
394317
);
395318
if (!nodeSession && wake.available) {
396-
const retryWake = await awaitNodeWakeWithinInvokeDeadline(
319+
const retryWake = await awaitNodeInvokeWithinDeadline(
397320
() =>
398321
maybeWakeNodeWithApns(nodeId, {
399322
force: true,
@@ -403,7 +326,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
403326
}),
404327
invokeDeadlineAtMs,
405328
);
406-
if (retryWake === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
329+
if (retryWake === NODE_INVOKE_DEADLINE_EXPIRED) {
407330
respondIfInvokeExpired();
408331
return;
409332
}
@@ -448,7 +371,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
448371
return;
449372
}
450373
const totalDurationMs = Math.max(0, Date.now() - wakeFlowStartedAtMs);
451-
const nudge = await awaitNodeWakeWithinInvokeDeadline(
374+
const nudge = await awaitNodeInvokeWithinDeadline(
452375
() =>
453376
maybeSendNodeWakeNudge(nodeId, {
454377
cfg,
@@ -457,7 +380,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
457380
}),
458381
invokeDeadlineAtMs,
459382
);
460-
if (nudge === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
383+
if (nudge === NODE_INVOKE_DEADLINE_EXPIRED) {
461384
respondIfInvokeExpired();
462385
return;
463386
}
@@ -538,7 +461,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
538461
if (respondIfInvokeExpired()) {
539462
return;
540463
}
541-
const policyResult = await awaitNodeWakeWithinInvokeDeadline(
464+
const policyResult = await awaitNodeInvokeWithinDeadline(
542465
() =>
543466
applyPluginNodeInvokePolicy({
544467
context,
@@ -566,7 +489,7 @@ export const nodeInvokeHandlers: GatewayRequestHandlers = {
566489
}),
567490
invokeDeadlineAtMs,
568491
);
569-
if (policyResult === NODE_WAKE_INVOKE_DEADLINE_EXPIRED) {
492+
if (policyResult === NODE_INVOKE_DEADLINE_EXPIRED) {
570493
respondIfInvokeExpired(true);
571494
return;
572495
}

0 commit comments

Comments
 (0)