Skip to content

Commit 9e05172

Browse files
committed
fix(sms): align MMS retries with network timeouts
1 parent 6194cfd commit 9e05172

11 files changed

Lines changed: 342 additions & 166 deletions

‎extensions/sms/src/media.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,18 +656,51 @@ describe("SMS inbound MMS materialization", () => {
656656
}),
657657
retryable: true,
658658
},
659+
{
660+
name: "nested host unreachable",
661+
cause: new Error("fetch failed", {
662+
cause: Object.assign(new Error("host unreachable"), { code: "EHOSTUNREACH" }),
663+
}),
664+
retryable: true,
665+
},
666+
{
667+
name: "Undici DNS resolve failure",
668+
cause: Object.assign(new Error("DNS resolve failed"), {
669+
code: "UND_ERR_DNS_RESOLVE_FAILED",
670+
}),
671+
retryable: true,
672+
},
659673
{
660674
name: "media request deadline",
661675
cause: new DOMException("timed out", "TimeoutError"),
662676
retryable: true,
663677
},
678+
{
679+
name: "aggregate network failure",
680+
cause: new AggregateError(
681+
[Object.assign(new Error("timed out"), { code: "ETIMEDOUT" })],
682+
"all addresses failed",
683+
),
684+
retryable: true,
685+
},
664686
{
665687
name: "blocked SSRF with nested transient error",
666688
cause: Object.assign(new SsrFBlockedError("blocked private address"), {
667689
cause: Object.assign(new Error("reset"), { code: "ECONNRESET" }),
668690
}),
669691
retryable: false,
670692
},
693+
{
694+
name: "aggregate containing blocked SSRF and transient failure",
695+
cause: new AggregateError(
696+
[
697+
Object.assign(new Error("reset"), { code: "ECONNRESET" }),
698+
new SsrFBlockedError("blocked private address"),
699+
],
700+
"mixed failures",
701+
),
702+
retryable: false,
703+
},
671704
{
672705
name: "local storage permission",
673706
cause: Object.assign(new Error("permission denied"), { code: "EACCES" }),
@@ -680,6 +713,23 @@ describe("SMS inbound MMS materialization", () => {
680713
);
681714
});
682715

716+
it.each(["reason", "original", "error", "data"] as const)(
717+
"does not retry when .$field contains an SSRF denial",
718+
async (field) => {
719+
const cause = Object.assign(
720+
new Error("fetch failed", {
721+
cause: Object.assign(new Error("reset"), { code: "ECONNRESET" }),
722+
}),
723+
{ [field]: new SsrFBlockedError("blocked private address") },
724+
);
725+
726+
await expectInboundMediaFailure(
727+
new MediaFetchError("fetch_failed", "download failed", { cause }),
728+
false,
729+
);
730+
},
731+
);
732+
683733
it("keeps oversized MMS visible without retrying its sender lane", async () => {
684734
await expectInboundMediaFailure(new MediaFetchError("max_bytes", "too large"), false);
685735
});

‎extensions/sms/src/media.ts‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,7 @@ import {
66
toInboundMediaFactsWithMetadata,
77
type InboundMediaFacts,
88
} from "openclaw/plugin-sdk/channel-inbound";
9-
import {
10-
collectErrorGraphCandidates,
11-
extractErrorCode,
12-
readErrorName,
13-
} from "openclaw/plugin-sdk/error-runtime";
9+
import { collectErrorGraphCandidates } from "openclaw/plugin-sdk/error-runtime";
1410
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
1511
import { MediaFetchError, unlinkIfExists } from "openclaw/plugin-sdk/media-runtime";
1612
import { resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
@@ -22,7 +18,7 @@ import {
2218
type OutboundMediaLoadOptions,
2319
} from "openclaw/plugin-sdk/outbound-media";
2420
import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";
25-
import { classifyTransientNetworkErrorCode } from "openclaw/plugin-sdk/retry-runtime";
21+
import { isTransientNetworkError } from "openclaw/plugin-sdk/retry-runtime";
2622
import { safeEqualSecret, SsrFBlockedError } from "openclaw/plugin-sdk/security-runtime";
2723
import { getSmsRuntime } from "./runtime.js";
2824
import { TWILIO_MMS_MAX_BYTES } from "./twilio.js";
@@ -346,6 +342,22 @@ function createInboundMediaCleanup(paths: string[]): () => Promise<void> {
346342
};
347343
}
348344

345+
// Keep the SSRF veto on the same wrapper graph as the transient classifier;
346+
// otherwise a transient sibling could make a blocked fetch retry.
347+
function nestedSmsMediaErrorCandidates(candidate: Record<string, unknown>): unknown[] {
348+
const nested = [
349+
candidate.cause,
350+
candidate.reason,
351+
candidate.original,
352+
candidate.error,
353+
candidate.data,
354+
];
355+
if (Array.isArray(candidate.errors)) {
356+
nested.push(...candidate.errors);
357+
}
358+
return nested;
359+
}
360+
349361
function isRetryableSmsInboundMediaError(error: unknown): boolean {
350362
if (!(error instanceof MediaFetchError)) {
351363
return false;
@@ -360,18 +372,11 @@ function isRetryableSmsInboundMediaError(error: unknown): boolean {
360372
if (error.code !== "fetch_failed") {
361373
return false;
362374
}
363-
const causes = collectErrorGraphCandidates(error.cause, (candidate) => [candidate.cause]);
364-
if (causes.some((candidate) => candidate instanceof SsrFBlockedError)) {
375+
const candidates = collectErrorGraphCandidates(error.cause, nestedSmsMediaErrorCandidates);
376+
if (candidates.some((candidate) => candidate instanceof SsrFBlockedError)) {
365377
return false;
366378
}
367-
return causes.some((candidate) => {
368-
const name = readErrorName(candidate);
369-
return (
370-
classifyTransientNetworkErrorCode(extractErrorCode(candidate)) !== undefined ||
371-
name === "AbortError" ||
372-
name.endsWith("TimeoutError")
373-
);
374-
});
379+
return isTransientNetworkError(error.cause);
375380
}
376381

377382
export async function materializeSmsInboundMedia(params: {

‎src/infra/error-graph-internal.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Internal error-graph traversal shared by runtime classifiers.
2+
import { collectErrorGraphCandidates, extractErrorCode } from "./errors.js";
3+
4+
export function extractErrorCodeOrErrno(err: unknown): string | undefined {
5+
const code = extractErrorCode(err);
6+
if (code) {
7+
return code.trim().toUpperCase();
8+
}
9+
if (!err || typeof err !== "object") {
10+
return undefined;
11+
}
12+
const errno = (err as { errno?: unknown }).errno;
13+
if (typeof errno === "string" && errno.trim()) {
14+
return errno.trim().toUpperCase();
15+
}
16+
if (typeof errno === "number" && Number.isFinite(errno)) {
17+
return String(errno);
18+
}
19+
return undefined;
20+
}
21+
22+
export function collectNestedErrorCandidates(err: unknown): unknown[] {
23+
return collectErrorGraphCandidates(err, (current) => {
24+
const nested: unknown[] = [
25+
current.cause,
26+
current.reason,
27+
current.original,
28+
current.error,
29+
current.data,
30+
];
31+
if (Array.isArray(current.errors)) {
32+
nested.push(...current.errors);
33+
}
34+
return nested;
35+
});
36+
}

‎src/infra/errors.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Tests shared infra error formatting helpers.
22
import { describe, expect, it } from "vitest";
3+
import { collectNestedErrorCandidates, extractErrorCodeOrErrno } from "./error-graph-internal.js";
34
import {
45
collectErrorGraphCandidates,
56
extractErrorCode,
@@ -53,6 +54,44 @@ describe("error helpers", () => {
5354
expect(collectErrorGraphCandidates(null)).toStrictEqual([]);
5455
});
5556

57+
it("walks every canonical wrapper edge once despite duplicates and cycles", () => {
58+
const cause = { name: "cause" } as { name: string; cause?: unknown };
59+
const reason = { name: "reason" };
60+
const original = { name: "original" };
61+
const error = { name: "error" };
62+
const data = { name: "data" };
63+
const aggregate = { name: "aggregate" };
64+
const root = {
65+
name: "root",
66+
cause,
67+
reason,
68+
original,
69+
error,
70+
data,
71+
errors: [aggregate, cause],
72+
};
73+
cause.cause = root;
74+
75+
expect(collectNestedErrorCandidates(root)).toEqual([
76+
root,
77+
cause,
78+
reason,
79+
original,
80+
error,
81+
data,
82+
aggregate,
83+
]);
84+
});
85+
86+
it.each([
87+
{ value: { code: " econnreset " }, expected: "ECONNRESET" },
88+
{ value: { errno: " eai_again " }, expected: "EAI_AGAIN" },
89+
{ value: { errno: -3001 }, expected: "-3001" },
90+
{ value: { errno: false }, expected: undefined },
91+
])("normalizes error code or errno from %#", ({ value, expected }) => {
92+
expect(extractErrorCodeOrErrno(value)).toBe(expected);
93+
});
94+
5695
it("matches errno-shaped errors by code", () => {
5796
const err = Object.assign(new Error("busy"), { code: "EADDRINUSE" });
5897
expect(isErrno(err)).toBe(true);

‎src/infra/http-body.response.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,26 @@ describe("readResponseWithLimit", () => {
183183
5_000,
184184
);
185185

186+
it("names the default idle timeout for retry classifiers", async () => {
187+
vi.useFakeTimers();
188+
try {
189+
const result = readResponseWithLimit(
190+
new Response(makeStallingStream([new Uint8Array([1, 2])])),
191+
1024,
192+
{ chunkTimeoutMs: 50 },
193+
).catch((error: unknown) => error);
194+
195+
await vi.advanceTimersByTimeAsync(60);
196+
197+
await expect(result).resolves.toMatchObject({
198+
name: "TimeoutError",
199+
message: expect.stringMatching(/stalled/i),
200+
});
201+
} finally {
202+
vi.useRealTimers();
203+
}
204+
});
205+
186206
it.each([
187207
{
188208
name: "does not time out while chunks keep arriving",
@@ -265,6 +285,24 @@ describe("readResponseWithLimit", () => {
265285
}
266286
});
267287

288+
it("names the default overall timeout for retry classifiers", async () => {
289+
vi.useFakeTimers();
290+
try {
291+
const result = readResponseWithLimit(new Response(makeTricklingStream(40)), 1024, {
292+
timeoutMs: 50,
293+
}).catch((error: unknown) => error);
294+
295+
await vi.advanceTimersByTimeAsync(60);
296+
297+
await expect(result).resolves.toMatchObject({
298+
name: "TimeoutError",
299+
message: "Response body timed out after 50ms",
300+
});
301+
} finally {
302+
vi.useRealTimers();
303+
}
304+
});
305+
268306
it("resolves a lazy overall timeout immediately before reading", async () => {
269307
vi.useFakeTimers();
270308
try {

‎src/infra/http-response-body-timeout.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ import { resolveTimerTimeoutMs } from "@openclaw/normalization-core/number-coerc
44

55
type TimeoutErrorFactory = (params: { timeoutMs: number }) => Error;
66

7+
function createResponseBodyTimeoutError(message: string): Error {
8+
const error = new Error(message);
9+
error.name = "TimeoutError";
10+
return error;
11+
}
12+
713
async function withCancellableTimeout<T>(params: {
814
timeoutMs: number;
915
onTimeout: TimeoutErrorFactory;
@@ -62,7 +68,7 @@ export async function readChunkWithIdleTimeout(
6268
timeoutMs: chunkTimeoutMs,
6369
onTimeout: ({ timeoutMs }) =>
6470
onIdleTimeout?.({ chunkTimeoutMs: timeoutMs }) ??
65-
new Error(`Media download stalled: no data received for ${timeoutMs}ms`),
71+
createResponseBodyTimeoutError(`Media download stalled: no data received for ${timeoutMs}ms`),
6672
// Cancellation releases fetch sockets and buffers instead of letting the
6773
// pending read continue after the caller has failed.
6874
cancel: async (error) => await reader.cancel(error),
@@ -83,7 +89,7 @@ export async function withResponseBodyTimeout<T>(params: {
8389
timeoutMs: params.timeoutMs,
8490
onTimeout: ({ timeoutMs }) =>
8591
params.onTimeout?.({ timeoutMs }) ??
86-
new Error(`Response body timed out after ${timeoutMs}ms`),
92+
createResponseBodyTimeoutError(`Response body timed out after ${timeoutMs}ms`),
8793
// Fetch resolves at headers. Body cancellation owns socket cleanup when
8894
// the separate whole-body deadline wins.
8995
cancel: params.cancel,

0 commit comments

Comments
 (0)