Skip to content

Commit 9904617

Browse files
Pick-catsteipete
andauthored
fix(vydra): bound stalled generated image download body reads (#109210)
* fix(vydra): bound dripping asset downloads with a wall-clock deadline * fix(vydra): bound dripping non-2xx error bodies with wall-clock deadline * fix(vydra): preserve bounded provider error metadata --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 723f5ba commit 9904617

2 files changed

Lines changed: 234 additions & 5 deletions

File tree

‎extensions/vydra/shared.test.ts‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
// Vydra tests cover shared download timeout plugin behavior.
2+
import { once } from "node:events";
3+
import http from "node:http";
4+
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import { downloadVydraAsset } from "./shared.js";
7+
8+
describe("downloadVydraAsset", () => {
9+
let server: http.Server | undefined;
10+
const dripTimers = new Set<ReturnType<typeof setTimeout>>();
11+
12+
afterEach(async () => {
13+
for (const timer of dripTimers) {
14+
clearTimeout(timer);
15+
}
16+
dripTimers.clear();
17+
if (!server) {
18+
return;
19+
}
20+
server.closeAllConnections?.();
21+
server.close();
22+
await once(server, "close").catch(() => undefined);
23+
server = undefined;
24+
});
25+
26+
async function listenDripServer(params: {
27+
statusCode: number;
28+
contentType: string;
29+
chunk: Buffer | string;
30+
}): Promise<number> {
31+
server = http.createServer((_req, res) => {
32+
res.on("error", () => {});
33+
res.writeHead(params.statusCode, {
34+
"Content-Type": params.contentType,
35+
"Transfer-Encoding": "chunked",
36+
});
37+
// Keep sending bytes so chunk idle alone would never fire.
38+
const drip = () => {
39+
if (res.writableEnded || res.destroyed) {
40+
return;
41+
}
42+
res.write(params.chunk);
43+
const timer = setTimeout(drip, 20);
44+
dripTimers.add(timer);
45+
};
46+
drip();
47+
});
48+
server.on("clientError", (_err, socket) => socket.destroy());
49+
server.listen(0, "127.0.0.1");
50+
await once(server, "listening");
51+
const address = server.address();
52+
if (!address || typeof address === "string") {
53+
throw new Error("expected loopback server address");
54+
}
55+
return address.port;
56+
}
57+
58+
it("bounds a dripping download body with one wall-clock deadline", async () => {
59+
const timeoutMs = 250;
60+
const port = await listenDripServer({
61+
statusCode: 200,
62+
contentType: "image/png",
63+
chunk: Buffer.from([0x00]),
64+
});
65+
66+
const startedAt = performance.now();
67+
await expect(
68+
downloadVydraAsset({
69+
url: `http://127.0.0.1:${port}/generated/test.png`,
70+
kind: "image",
71+
timeoutMs,
72+
fetchFn: fetch,
73+
maxBytes: 1024 * 1024,
74+
}),
75+
).rejects.toThrow(`Vydra image download timed out after ${timeoutMs}ms`);
76+
const elapsedMs = performance.now() - startedAt;
77+
78+
expect(elapsedMs).toBeGreaterThanOrEqual(timeoutMs - 50);
79+
expect(elapsedMs).toBeLessThan(timeoutMs + 1_500);
80+
});
81+
82+
it("bounds a dripping non-2xx error body with one wall-clock deadline", async () => {
83+
const timeoutMs = 250;
84+
const port = await listenDripServer({
85+
statusCode: 500,
86+
contentType: "text/plain",
87+
chunk: "e",
88+
});
89+
90+
const startedAt = performance.now();
91+
await expect(
92+
downloadVydraAsset({
93+
url: `http://127.0.0.1:${port}/generated/test.png`,
94+
kind: "image",
95+
timeoutMs,
96+
fetchFn: fetch,
97+
maxBytes: 1024 * 1024,
98+
}),
99+
).rejects.toThrow(`Vydra image download timed out after ${timeoutMs}ms`);
100+
const elapsedMs = performance.now() - startedAt;
101+
102+
expect(elapsedMs).toBeGreaterThanOrEqual(timeoutMs - 50);
103+
expect(elapsedMs).toBeLessThan(timeoutMs + 1_500);
104+
});
105+
106+
it("preserves normalized and redacted provider errors after the bounded read", async () => {
107+
const result = await downloadVydraAsset({
108+
url: "https://cdn.vydra.example/generated/test.png",
109+
kind: "image",
110+
timeoutMs: 250,
111+
fetchFn: async () =>
112+
new Response(
113+
JSON.stringify({ message: "Authorization: Bearer test-token", code: "asset_failed" }),
114+
{
115+
status: 502,
116+
headers: { "x-request-id": "req-vydra-test" },
117+
},
118+
),
119+
maxBytes: 1024 * 1024,
120+
}).catch((error: unknown) => error);
121+
122+
expect(result).toMatchObject({
123+
name: "ProviderHttpError",
124+
status: 502,
125+
statusCode: 502,
126+
errorCode: "asset_failed",
127+
requestId: "req-vydra-test",
128+
});
129+
expect(result).toBeInstanceOf(Error);
130+
expect(result instanceof Error ? result.message : "").not.toContain("test-token");
131+
});
132+
133+
it("normalizes null-body HTTP errors after the bounded read", async () => {
134+
const result = await downloadVydraAsset({
135+
url: "https://cdn.vydra.example/generated/test.png",
136+
kind: "image",
137+
timeoutMs: 250,
138+
fetchFn: async () => new Response(null, { status: 304 }),
139+
maxBytes: 1024 * 1024,
140+
}).catch((error: unknown) => error);
141+
142+
expect(result).toMatchObject({ name: "ProviderHttpError", status: 304, statusCode: 304 });
143+
});
144+
145+
it("does not bound a dripping body when only chunk idle timeout is used", async () => {
146+
// Negative control: chunkTimeoutMs resets on every drip, so idle alone never fires.
147+
server = http.createServer((_req, res) => {
148+
res.on("error", () => {});
149+
res.writeHead(200, {
150+
"Content-Type": "image/png",
151+
"Transfer-Encoding": "chunked",
152+
});
153+
const drip = () => {
154+
if (res.writableEnded || res.destroyed) {
155+
return;
156+
}
157+
res.write(Buffer.from([0x00]));
158+
const timer = setTimeout(drip, 20);
159+
dripTimers.add(timer);
160+
};
161+
drip();
162+
});
163+
server.listen(0, "127.0.0.1");
164+
await once(server, "listening");
165+
166+
const address = server.address();
167+
if (!address || typeof address === "string") {
168+
throw new Error("expected loopback server address");
169+
}
170+
171+
const response = await fetch(`http://127.0.0.1:${address.port}/`);
172+
let settled = false;
173+
void readResponseWithLimit(response, 1024 * 1024, {
174+
chunkTimeoutMs: 100,
175+
onIdleTimeout: ({ chunkTimeoutMs }) => new Error(`idle fired after ${chunkTimeoutMs}ms`),
176+
})
177+
.then(() => {
178+
settled = true;
179+
})
180+
.catch(() => {
181+
settled = true;
182+
});
183+
184+
await new Promise<void>((resolve) => {
185+
setTimeout(resolve, 400);
186+
});
187+
expect(settled).toBe(false);
188+
// Body reader is locked by readResponseWithLimit; tear down via server close in afterEach.
189+
});
190+
});

‎extensions/vydra/shared.ts‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
44
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
55
import {
66
assertOkOrThrowHttpError,
7+
createProviderHttpError,
78
createProviderOperationDeadline,
89
fetchWithTimeout,
910
readProviderJsonResponse,
@@ -13,7 +14,10 @@ import {
1314
type ProviderOperationDeadline,
1415
type ProviderOperationTimeoutMs,
1516
} from "openclaw/plugin-sdk/provider-http";
16-
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
17+
import {
18+
readResponseTextPrefix,
19+
readResponseWithLimit,
20+
} from "openclaw/plugin-sdk/response-limit-runtime";
1721
import {
1822
normalizeOptionalLowercaseString,
1923
normalizeOptionalString,
@@ -233,6 +237,21 @@ export function resolveVydraGeneratedMediaMaxBytes(params: {
233237
return DEFAULT_GENERATED_VIDEO_MAX_BYTES;
234238
}
235239

240+
function resolveVydraDownloadBodyTimeout(params: {
241+
kind: VydraMediaKind;
242+
timeoutMs: number;
243+
deadlineMs: number;
244+
}) {
245+
return {
246+
chunkTimeoutMs: params.timeoutMs,
247+
timeoutMs: Math.max(1, params.deadlineMs - Date.now()),
248+
onIdleTimeout: ({ chunkTimeoutMs }: { chunkTimeoutMs: number }) =>
249+
new Error(`Vydra ${params.kind} download stalled after ${chunkTimeoutMs}ms`),
250+
onTimeout: () =>
251+
new Error(`Vydra ${params.kind} download timed out after ${params.timeoutMs}ms`),
252+
};
253+
}
254+
236255
export async function downloadVydraAsset(params: {
237256
url: string;
238257
kind: VydraMediaKind;
@@ -241,17 +260,37 @@ export async function downloadVydraAsset(params: {
241260
maxBytes: number;
242261
}): Promise<{ buffer: Buffer; mimeType: string; fileName: string }> {
243262
const timeoutMs = resolveVydraHttpTimeoutMs(params.timeoutMs);
263+
// fetchWithTimeout clears its abort after headers land. Keep one wall-clock deadline across
264+
// non-2xx error-detail and successful-body reads so a slow drip cannot reset chunk idle forever.
265+
const deadlineMs = Date.now() + timeoutMs;
244266
const response = await fetchWithTimeout(params.url, { method: "GET" }, timeoutMs, params.fetchFn);
245-
await assertOkOrThrowHttpError(response, `Vydra ${params.kind} download failed`);
267+
if (!response.ok) {
268+
// Shared assertOkOrThrowHttpError reads error detail without a wall-clock bound; a dripping
269+
// non-2xx body would hang before the success-path reader runs.
270+
const prefix = await readResponseTextPrefix(
271+
response,
272+
16 * 1024,
273+
resolveVydraDownloadBodyTimeout({ kind: params.kind, timeoutMs, deadlineMs }),
274+
);
275+
// Re-run the bounded body through the shared formatter so provider error metadata and
276+
// sensitive-text redaction remain identical to the previous assertOkOrThrowHttpError path.
277+
throw await createProviderHttpError(
278+
new Response(prefix.text || null, {
279+
headers: response.headers,
280+
status: response.status,
281+
statusText: response.statusText,
282+
}),
283+
`Vydra ${params.kind} download failed`,
284+
{ statusPrefix: "HTTP " },
285+
);
286+
}
246287
const mimeType =
247288
response.headers.get("content-type")?.trim() ||
248289
(params.kind === "image" ? "image/png" : params.kind === "audio" ? "audio/mpeg" : "video/mp4");
249290
const buffer = await readResponseWithLimit(response, params.maxBytes, {
250-
chunkTimeoutMs: timeoutMs,
291+
...resolveVydraDownloadBodyTimeout({ kind: params.kind, timeoutMs, deadlineMs }),
251292
onOverflow: ({ maxBytes }) =>
252293
new Error(`Vydra ${params.kind} download exceeds ${maxBytes} bytes`),
253-
onIdleTimeout: ({ chunkTimeoutMs }) =>
254-
new Error(`Vydra ${params.kind} download stalled after ${chunkTimeoutMs}ms`),
255294
});
256295
const extension = resolveVydraFileExtension(params.kind, mimeType);
257296
const fileStem = params.kind === "image" ? "image" : params.kind === "audio" ? "audio" : "video";

0 commit comments

Comments
 (0)