Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/directory/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ async function fetchRaw(url: string, accept: string, options: FetchOptions): Pro
if (Number.isFinite(declared) && declared > cap) {
throw new FetchProblem(`${target} declared ${declared} bytes`);
}
return readCapped(response, cap);
// Keep the timeout and caller's abort listener until the body is read.
// Returning the promise directly runs finally as soon as headers arrive.
return await readCapped(response, cap);
}
throw new FetchProblem(`${url} redirected too many times`);
} catch (error) {
Expand Down
46 changes: 46 additions & 0 deletions test/fetch-body-timeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import { test, type TestContext } from 'node:test';
import { fetchText, FetchProblem } from '../src/directory/fetch.ts';

// Headers arrive immediately, but the body remains open. No external requests.
function delayedBody(t: TestContext, delayMs: number) {
t.mock.method(globalThis, 'fetch', async (_url: unknown, init: RequestInit) => {
const signal = init.signal!;
return new Response(new ReadableStream<Uint8Array>({
start(controller) {
const abort = () => {
clearTimeout(timer);
controller.error(new DOMException('Aborted', 'AbortError'));
};
const timer = setTimeout(() => {
signal.removeEventListener('abort', abort);
controller.enqueue(new TextEncoder().encode('complete'));
controller.close();
}, delayMs);
signal.addEventListener('abort', abort, { once: true });
t.after(() => clearTimeout(timer));
},
}));
});
}

test('the timeout covers reading the body after headers arrive', async (t) => {
delayedBody(t, 200);
await assert.rejects(fetchText('https://example.com', { timeoutMs: 20 }),
(error: unknown) => error instanceof FetchProblem && /timed out/.test(error.message));
});

test('caller cancellation still interrupts an in-progress body', async (t) => {
delayedBody(t, 200);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 20);
t.after(() => clearTimeout(timer));
await assert.rejects(fetchText('https://example.com', {
timeoutMs: 1000, signal: controller.signal,
}), FetchProblem);
});

test('a body completed before the deadline is returned', async (t) => {
delayedBody(t, 5);
assert.equal(await fetchText('https://example.com', { timeoutMs: 1000 }), 'complete');
});
Loading