Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import type * as NodeHttp from "node:http";
3
4/**
5 * An "error" event without a listener escalates into an uncaught exception and
6 * terminates the whole server process, taking every other client and all
7 * in-flight provider work with it.
8 */
9export function guardHttpResponseWriteErrors<T extends NodeHttp.Server>(
10 server: T,
11 onError?: (error: unknown) => void,
12): T {
13 server.on("request", (_request, response) => {
14 response.on("error", (error) => {
15 onError?.(error);
16 });
17 });
18 server.on("upgrade", (_request, socket) => {
19 socket.on("error", (error) => {
20 onError?.(error);
21 });
22 });
23 return server;
24}
25
26/**
27 * `NodeHttpServer` listens while its layer builds but attaches its request
28 * and upgrade handlers only when `HttpRouter.serve` runs, after the whole
29 * runtime graph: about a second at startup. Node accepts connections in that
30 * window, and with no handler they were never answered, so a client that
31 * reconnected into it waited out its socket timeout. Park those requests and
32 * hand them to the first real handler, which answers them like any request
33 * that arrived a moment later.
34 */
35export function holdRequestsUntilServing<T extends NodeHttp.Server>(server: T): T {
36 for (const event of ["request", "upgrade"] as const) {
37 const parked: Array<ReadonlyArray<unknown>> = [];
38 const park = (...args: ReadonlyArray<unknown>) => {
39 parked.push(args);
40 };
41 const onNewListener = (name: string | symbol) => {
42 if (name !== event) return;
43 server.off("newListener", onNewListener);
44 server.off(event, park);
45 // "newListener" fires before the listener is added. A microtask runs
46 // once it is, and before any later connection's I/O callback, so parked
47 // requests still reach the handler in arrival order.
48 queueMicrotask(() => {
49 for (const args of parked.splice(0)) server.emit(event, ...args);
50 });
51 };
52 server.on(event, park);
53 server.on("newListener", onNewListener);
54 }
55 return server;
56}