Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
82 changes: 82 additions & 0 deletions src/adapters/_node/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,83 @@ function isBodySourceFinished(req: NodeServerRequest): boolean {
return isClientGone(req) || req.destroyed || req.readableEnded;
}

const UNREAD_BODY_DRAIN_CAP = 1024 * 1024; // 1 MiB
const UNREAD_BODY_DRAIN_TIMEOUT_MS = 1000;

/**
* Node's `resOnFinish` only dumps an unread body when `req._consuming` is false.
* Calling `Readable.toWeb(req)` flips `_consuming` to true and pauses `req` when
* nothing reads the web stream, leaving unread bytes on the HTTP/1.1 socket so
* the next keep-alive request stalls until `keepAliveTimeout` (#371).
*
* When the response finishes with an unread, unlocked web stream, drain up to a
* bounded byte/time cap so keep-alive can reuse the connection for small bodies,
* and tear down the connection (or HTTP/2 stream) if the client keeps sending.
*/
function drainUnreadBodyOnFinish(
req: NodeServerRequest,
res: NodeServerResponse | undefined,
stream: ReadableStream,
): void {
if (!res) {
return;
}
const onFinish = () => {
// Do not require `req.isPaused()`: `Readable.toWeb()` resumes `req` inside
// `pull()`, so an unread upload still in flight is flowing when the response
// finishes and only pauses once the web stream's queue fills.
if (stream.locked || req.destroyed || req.readableEnded) {
return;
}
if (req.complete && req.readableLength === 0) {
req.removeAllListeners("data");
req.removeAllListeners("readable");
req.read(0);
return;
}
const isH2 = req.httpVersion === "2.0";
let drained = 0;
const stop = () => {
clearTimeout(timer);
req.off("data", onData);
req.off("end", stop);
req.off("close", stop);
req.off("error", stop);
};
const tearDown = () => {
stop();
if (isH2) {
req.destroy();
} else {
req.socket?.destroy();
}
};
const onData = (chunk: Buffer | string) => {
drained += typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.byteLength;
if (drained > UNREAD_BODY_DRAIN_CAP) {
tearDown();
}
};
const timer = setTimeout(tearDown, UNREAD_BODY_DRAIN_TIMEOUT_MS);
timer.unref?.();
req.removeAllListeners("data");
req.removeAllListeners("readable");
req.on("data", onData);
req.once("end", stop);
req.once("close", stop);
req.once("error", stop);
req.resume();
};
// On HTTP/2, `Http2ServerResponse` only emits `finish` when the underlying
// stream closes, so listen on `res.stream`'s writable `finish` instead.
const finishTarget = "stream" in res && res.stream ? res.stream : res;
if (finishTarget.writableFinished) {
onFinish();
} else {
finishTarget.once("finish", onFinish);
}
}

/** Request-target checks (e.g. `hasBackslashInPath`) run in `serve()`/`toNodeHandler()`, not here. */
export const NodeRequest: {
new (nodeCtx: NodeRequestContext): ServerRequest;
Expand Down Expand Up @@ -322,6 +399,7 @@ export const NodeRequest: {
// already-consumed IncomingMessage (the fast path leaves it ended, so a
// fresh `Readable.toWeb` would produce a stream whose `end` never fires).
let stream: ReadableStream | null = null;
let wrappedLiveReq = false;
if (this.#hasBody() && !this.#bodyUsed) {
// A body already buffered on `req.rawBody` (e.g. by Google Cloud
// Functions, which drains the stream first) is served from it, as
Expand All @@ -346,6 +424,7 @@ export const NodeRequest: {
stream = Readable.toWeb(
this.#req as NodeJS.ReadableStream,
) as unknown as ReadableStream;
wrappedLiveReq = true;
}
}
// Enforce `maxRequestBodySize` at the single choke point every stream
Expand All @@ -355,6 +434,9 @@ export const NodeRequest: {
if (stream && this.#maxRequestBodySize !== undefined) {
stream = limitBodyStream(stream, this.#maxRequestBodySize);
}
if (wrappedLiveReq && stream) {
drainUnreadBodyOnFinish(this.#req, this.runtime?.node?.res, stream);
}
this.#bodyStream = stream;
}
return this.#bodyStream;
Expand Down
109 changes: 109 additions & 0 deletions test/node-streams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -704,3 +704,112 @@ describe("sendNodeResponse buffered bodies", () => {
});
}
});

describe("node unread request.body keep-alive handling (#371)", () => {
test("accessing request.body without reading does not stall subsequent keep-alive requests", async () => {
const server = serve({
port: 0,
async fetch(req) {
// Touching `req.body` wraps the IncomingMessage via Readable.toWeb without reading it.
void req.body;
await new Promise((r) => setTimeout(r, 30));
const path = new URL(req.url).pathname;
return new Response(path, { status: path === "/big" ? 413 : 200 });
},
});
await server.ready();

try {
const base = server.url!.replace(/\/$/, "");
for (const [name, size] of [
["small", 64 * 1024],
["empty", 0],
["big", 2 * 1024 * 1024],
["empty", 0],
["empty", 0],
["empty", 0],
] as const) {
const init: RequestInit = { signal: AbortSignal.timeout(3000) };
if (size > 0) {
init.method = "POST";
init.body = "x".repeat(size);
}
const res = await fetch(`${base}/${name}`, init);
const text = await res.text();
expect(res.status).toBe(name === "big" ? 413 : 200);
expect(text).toBe(`/${name}`);
}
} finally {
await server.close(true);
}
});

test("drains unread body that arrives after the response finishes without stalling keep-alive", async () => {
const server = serve({
port: 0,
fetch(req) {
void req.body;
const path = new URL(req.url).pathname;
return new Response(path, { status: path === "/delayed" ? 413 : 200 });
},
});
await server.ready();

const agent = new (await import("node:http")).Agent({ keepAlive: true, maxSockets: 1 });
try {
const { port } = server.node!.server!.address() as AddressInfo;
const payload = Buffer.alloc(128 * 1024, 0x78);

// Send headers immediately, wait for the 413 response to finish, then write the body.
const firstStatus = await new Promise<number>((resolve, reject) => {
const req = request(
{
hostname: "127.0.0.1",
port,
path: "/delayed",
method: "POST",
agent,
headers: { "content-length": String(payload.byteLength) },
},
(res) => {
res.resume();
res.once("end", () => {
req.end(payload);
resolve(res.statusCode!);
});
},
);
req.once("error", reject);
req.flushHeaders();
});
expect(firstStatus).toBe(413);

// Next request on the same keep-alive agent must complete promptly.
const second = await new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = request(
{
hostname: "127.0.0.1",
port,
path: "/next",
method: "GET",
agent,
signal: AbortSignal.timeout(3000),
},
(res) => {
const chunks: Buffer[] = [];
res.on("data", (c) => chunks.push(c));
res.once("end", () =>
resolve({ status: res.statusCode!, body: Buffer.concat(chunks).toString() }),
);
},
);
req.once("error", reject);
req.end();
});
expect(second).toEqual({ status: 200, body: "/next" });
} finally {
agent.destroy();
await server.close(true);
}
});
});