Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ext/http): correctly consume response body in Deno.serve #24811

Merged
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
11 changes: 11 additions & 0 deletions ext/http/00_serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,11 @@ function fastSyncResponseOrStream(

const stream = respBody.streamOrStatic;
const body = stream.body;
if (body !== undefined) {
// We ensure the response has not been consumed yet in the caller of this
// function.
stream.consumed = true;
}

if (TypedArrayPrototypeGetSymbolToStringTag(body) === "Uint8Array") {
innerRequest?.close();
Expand Down Expand Up @@ -505,6 +510,12 @@ function mapToCallback(context, callback, onError) {
"Return value from serve handler must be a response or a promise resolving to a response",
);
}

if (response.bodyUsed) {
throw TypeError(
"The body of the Response returned from the serve handler has already been consumed.",
);
}
} catch (error) {
try {
response = await onError(error);
Expand Down
45 changes: 45 additions & 0 deletions tests/unit/serve_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,51 @@ Deno.test(
},
);

Deno.test(
{ permissions: { net: true } },
async function httpServerMultipleResponseBodyConsume() {
const ac = new AbortController();
const { promise, resolve } = Promise.withResolvers<void>();
const response = new Response("Hello World");
let hadError = false;
const server = Deno.serve({
handler: () => {
return response;
},
port: servePort,
signal: ac.signal,
onListen: onListen(resolve),
onError: () => {
hadError = true;
return new Response("Internal Server Error", { status: 500 });
},
});

await promise;
assert(!response.bodyUsed);

const resp = await fetch(`http://127.0.0.1:${servePort}/`, {
headers: { "connection": "close" },
});
assertEquals(resp.status, 200);
const text = await resp.text();
assertEquals(text, "Hello World");
assert(response.bodyUsed);

const resp2 = await fetch(`http://127.0.0.1:${servePort}/`, {
headers: { "connection": "close" },
});
assertEquals(resp2.status, 500);
const text2 = await resp2.text();
assertEquals(text2, "Internal Server Error");
assert(hadError);
assert(response.bodyUsed);

ac.abort();
await server.finished;
},
);

Deno.test({ permissions: { net: true } }, async function httpServerOverload1() {
const ac = new AbortController();
const deferred = Promise.withResolvers<void>();
Expand Down