Skip to content

Commit 85c570f

Browse files
committed
fix(nodes-camera): add timeout to URL media downloads
1 parent 372b527 commit 85c570f

2 files changed

Lines changed: 123 additions & 6 deletions

File tree

‎src/cli/nodes-camera.test.ts‎

Lines changed: 120 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Nodes camera tests cover camera node command media handling and file inputs.
22
import * as fs from "node:fs/promises";
3+
import * as http from "node:http";
4+
import type { AddressInfo } from "node:net";
35
import * as path from "node:path";
46
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
57
import {
@@ -9,12 +11,31 @@ import {
911
import { withTempDir } from "../test-utils/temp-dir.js";
1012

1113
const fetchGuardMocks = vi.hoisted(() => ({
12-
fetchWithSsrFGuard: vi.fn(async (params: { url: string }) => {
13-
return {
14-
response: await globalThis.fetch(params.url),
15-
finalUrl: params.url,
16-
release: async () => {},
14+
fetchWithSsrFGuard: vi.fn(async (params: { url: string; timeoutMs?: number }) => {
15+
const controller = new AbortController();
16+
const timeoutId =
17+
typeof params.timeoutMs === "number"
18+
? setTimeout(
19+
() => controller.abort(new Error(`timed out after ${params.timeoutMs}ms`)),
20+
Math.max(1, params.timeoutMs),
21+
)
22+
: undefined;
23+
timeoutId?.unref?.();
24+
const release = async () => {
25+
if (timeoutId) {
26+
clearTimeout(timeoutId);
27+
}
1728
};
29+
try {
30+
return {
31+
response: await globalThis.fetch(params.url, { signal: controller.signal }),
32+
finalUrl: params.url,
33+
release,
34+
};
35+
} catch (err) {
36+
await release();
37+
throw err;
38+
}
1839
}),
1940
}));
2041

@@ -49,6 +70,67 @@ async function expectPathMissing(targetPath: string): Promise<void> {
4970
throw new Error(`expected missing path: ${targetPath}`);
5071
}
5172

73+
async function withHangingHttpServer<T>(run: (url: string) => Promise<T>): Promise<T> {
74+
const server = http.createServer((_req, _res) => {
75+
// Intentionally leave the response open to model a node host that accepts
76+
// the media request and then never sends headers.
77+
});
78+
await new Promise<void>((resolve, reject) => {
79+
server.once("error", reject);
80+
server.listen(0, "127.0.0.1", () => resolve());
81+
});
82+
try {
83+
const address = server.address();
84+
if (!address || typeof address === "string") {
85+
throw new Error("expected TCP listener address");
86+
}
87+
return await run(`http://127.0.0.1:${(address as AddressInfo).port}/hang`);
88+
} finally {
89+
await new Promise<void>((resolve, reject) => {
90+
server.close((err) => (err ? reject(err) : resolve()));
91+
});
92+
}
93+
}
94+
95+
function mockFetchGuardToRealUrl(realUrl: string): { abort: () => void } {
96+
const controller = new AbortController();
97+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
98+
fetchGuardMocks.fetchWithSsrFGuard.mockImplementationOnce(
99+
async (params: { url: string; timeoutMs?: number }) => {
100+
if (typeof params.timeoutMs === "number") {
101+
timeoutId = setTimeout(
102+
() => controller.abort(new Error(`timed out after ${params.timeoutMs}ms`)),
103+
Math.max(1, params.timeoutMs),
104+
);
105+
timeoutId.unref?.();
106+
}
107+
const release = async () => {
108+
if (timeoutId) {
109+
clearTimeout(timeoutId);
110+
}
111+
};
112+
try {
113+
return {
114+
response: await globalThis.fetch(realUrl, { signal: controller.signal }),
115+
finalUrl: params.url,
116+
release,
117+
};
118+
} catch (err) {
119+
await release();
120+
throw err;
121+
}
122+
},
123+
);
124+
return {
125+
abort: () => {
126+
if (timeoutId) {
127+
clearTimeout(timeoutId);
128+
}
129+
controller.abort();
130+
},
131+
};
132+
}
133+
52134
function cancelTrackedResponse(init?: ResponseInit): {
53135
response: Response;
54136
wasCanceled: () => boolean;
@@ -257,6 +339,39 @@ describe("nodes camera helpers", () => {
257339
expectedHost: "198.51.100.42",
258340
});
259341
await expect(readFileUtf8AndCleanup(out)).resolves.toBe("url-content");
342+
expect(fetchGuardMocks.fetchWithSsrFGuard).toHaveBeenCalledWith(
343+
expect.objectContaining({ timeoutMs: 120_000 }),
344+
);
345+
});
346+
});
347+
348+
it("aborts hanging url payload downloads through the guarded fetch timeout", async () => {
349+
await withHangingHttpServer(async (hangingUrl) => {
350+
const controller = mockFetchGuardToRealUrl(hangingUrl);
351+
await withCameraTempDir(async (dir) => {
352+
const out = path.join(dir, "hanging.bin");
353+
const download = writeUrlToFile(out, "https://198.51.100.42/hanging.bin", {
354+
expectedHost: "198.51.100.42",
355+
timeoutMs: 50,
356+
});
357+
try {
358+
await expect(
359+
Promise.race([
360+
download,
361+
new Promise((_, reject) => {
362+
setTimeout(() => reject(new Error("download did not time out")), 500);
363+
}),
364+
]),
365+
).rejects.toThrow(/timed out after 50ms|abort/i);
366+
expect(fetchGuardMocks.fetchWithSsrFGuard).toHaveBeenCalledWith(
367+
expect.objectContaining({ timeoutMs: 50 }),
368+
);
369+
await expectPathMissing(out);
370+
} finally {
371+
controller.abort();
372+
await download.catch(() => undefined);
373+
}
374+
});
260375
});
261376
});
262377

‎src/cli/nodes-camera.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616

1717
const MAX_CAMERA_URL_DOWNLOAD_BYTES = 250 * 1024 * 1024;
1818
const MAX_CAMERA_BASE64_BYTES = MAX_CAMERA_URL_DOWNLOAD_BYTES;
19+
const CAMERA_URL_DOWNLOAD_TIMEOUT_MS = 120_000;
1920

2021
/** Camera orientation accepted by node camera commands. */
2122
export type CameraFacing = "front" | "back";
@@ -94,7 +95,7 @@ export function cameraTempPath(opts: {
9495
export async function writeUrlToFile(
9596
filePath: string,
9697
url: string,
97-
opts: { expectedHost: string },
98+
opts: { expectedHost: string; timeoutMs?: number },
9899
) {
99100
const parsed = new URL(url);
100101
if (parsed.protocol !== "https:") {
@@ -124,6 +125,7 @@ export async function writeUrlToFile(
124125
url,
125126
auditContext: "writeUrlToFile",
126127
policy,
128+
timeoutMs: opts.timeoutMs ?? CAMERA_URL_DOWNLOAD_TIMEOUT_MS,
127129
});
128130
release = guarded.release;
129131
const res = guarded.response;

0 commit comments

Comments
 (0)