Skip to content
Merged
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
13 changes: 12 additions & 1 deletion src/adapters/_node/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export const NodeRequest: {

class Request implements Partial<ServerRequest> {
runtime: ServerRequest["runtime"];
// Declared so the post-construction `request.waitUntil = ...` assignment
// in the adapters doesn't add a property (hidden-class transition) per
// request.
waitUntil?: ServerRequest["waitUntil"];

#req: NodeServerRequest;
#url?: URL;
Expand Down Expand Up @@ -148,7 +152,14 @@ export const NodeRequest: {
if (this.#request) {
return this.#request.json();
}
return this.text().then((text) => JSON.parse(text));
if (this.#bodyStream !== undefined) {
return this.text().then((text) => JSON.parse(text));
}
// Parse in a single continuation (readBody -> parse) instead of going
// through text() — one less promise + microtask hop per body read.
return readBody(this.#req, this.#maxRequestBodySize).then((buf) =>
JSON.parse(buf.toString()),
);
}

get _request(): globalThis.Request {
Expand Down
50 changes: 44 additions & 6 deletions src/adapters/_node/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,47 @@ import type NodeHttp from "node:http";
import type { NodeServerResponse } from "../../types.ts";
import type { NodeResponse } from "./response.ts";

export async function sendNodeResponse(
/**
* Sends a web `Response` to a Node.js `ServerResponse`.
*
* The returned promise resolves once the response has been fully sent
* (kept for `toNodeHandler` consumers that await completion).
*/
export function sendNodeResponse(
nodeRes: NodeServerResponse,
webRes: Response | NodeResponse,
): Promise<void> {
try {
return _sendNodeResponse(nodeRes, webRes, false) || Promise.resolve();
} catch (error) {
return Promise.reject(error);
}
}

/**
* Fire-and-forget variant for the internal `serve()` path: node:http ignores
* the request listener's return value, so tracking `end()` completion with a
* per-response Promise (and the microtask hops to settle it) is pure overhead
* there. Streaming bodies still return their tracking promise (it drives
* their own cleanup).
*
* @internal
*/
export function sendNodeResponseDetached(
nodeRes: NodeServerResponse,
webRes: Response | NodeResponse,
): Promise<void> | void {
return _sendNodeResponse(nodeRes, webRes, true);
}

function _sendNodeResponse(
nodeRes: NodeServerResponse,
webRes: Response | NodeResponse,
detached: boolean,
): Promise<void> | void {
if (!webRes) {
nodeRes.statusCode = 500;
return endNodeResponse(nodeRes);
return endNodeResponse(nodeRes, detached);
}

// Fast path for NodeResponse
Expand All @@ -31,7 +65,7 @@ export async function sendNodeResponse(
} else {
writeHead(nodeRes, res.status, res.statusText, res.headers);
}
return endNodeResponse(nodeRes);
return endNodeResponse(nodeRes, detached);
}

const rawHeaders: string[] = [];
Expand All @@ -40,7 +74,7 @@ export async function sendNodeResponse(
}
writeHead(nodeRes, webRes.status, webRes.statusText, rawHeaders);

return webRes.body ? streamBody(webRes.body, nodeRes) : endNodeResponse(nodeRes);
return webRes.body ? streamBody(webRes.body, nodeRes) : endNodeResponse(nodeRes, detached);
}

function writeHead(
Expand All @@ -66,7 +100,11 @@ function writeHead(
}
}

function endNodeResponse(nodeRes: NodeServerResponse) {
function endNodeResponse(nodeRes: NodeServerResponse, detached?: boolean): Promise<void> | void {
if (detached) {
nodeRes.end();
return;
}
return new Promise<void>((resolve) => nodeRes.end(resolve));
}

Expand Down Expand Up @@ -106,7 +144,7 @@ function pipeBody(
stream.off("readable", onReadable);
stream.destroy();
writeHead(nodeRes, 500, "Internal Server Error", []);
endNodeResponse(nodeRes).then(resolve);
(endNodeResponse(nodeRes) as Promise<void>).then(resolve);
}
function onReadable() {
stream.off("error", onEarlyError);
Expand Down
8 changes: 5 additions & 3 deletions src/adapters/node.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sendNodeResponse } from "./_node/send.ts";
import { sendNodeResponseDetached } from "./_node/send.ts";
import { NodeRequest } from "./_node/request.ts";
import {
fmtURL,
Expand Down Expand Up @@ -82,9 +82,11 @@ class NodeServer implements Server {
});
request.waitUntil = this.#wait?.waitUntil;
const res = fetchHandler(request);
// node:http ignores the listener's return value — use the detached
// variant to skip the per-response end-tracking Promise.
return res instanceof Promise
? res.then((resolvedRes) => sendNodeResponse(nodeRes, resolvedRes))
: sendNodeResponse(nodeRes, res);
? res.then((resolvedRes) => sendNodeResponseDetached(nodeRes, resolvedRes))
: sendNodeResponseDetached(nodeRes, res);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
};

this.node = { handler, server: undefined };
Expand Down
Loading