Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

httpResponseErrorGuard.ts

100 lines4.5 KB

1// These guards run on the raw Node HTTP server before Effect handles requests.
2// @effect-diagnostics nodeBuiltinImport:off
3import type * as NodeHttp from "node:http";
4import type * as NodeStream from "node:stream";
5import type { DatabaseMigrationProgress, ServerStartupStatus } from "@t3tools/contracts";
6​
7export function guardHttpResponseWriteErrors<T extends NodeHttp.Server>(
8 server: T,
9 onError?: (error: unknown) => void,
10): T {
11 server.on("request", (_request, response) => {
12 response.on("error", (error) => {
13 onError?.(error);
14 });
15 });
16 server.on("upgrade", (_request, socket) => {
17 socket.on("error", (error) => {
18 onError?.(error);
19 });
20 });
21 return server;
23​
24// cloudflared and Tailscale serve keep an idle connection to this server for 90
25// seconds. Node's 5 second default closes it first, so they can send a request
26// into a closed connection, and a slow client reconnects in the middle of a connect.
27const HTTP_KEEP_ALIVE_TIMEOUT_MS = 95_000;
28​
29export function keepIdleConnections<T extends NodeHttp.Server>(server: T): T {
30 server.keepAliveTimeout = HTTP_KEEP_ALIVE_TIMEOUT_MS;
31 // `close` drops only the connections idle at that moment. One that finishes
32 // its responses later would hold shutdown for the whole keep-alive time.
33 // `closeIdleConnections` cannot do this: it destroys a socket whose next
34 // pipelined response is ended but still has output to send.
35 const responsesInFlight = new WeakMap<object, number>();
36 server.on("request", (request, response) => {
37 const socket = request.socket;
38 responsesInFlight.set(socket, (responsesInFlight.get(socket) ?? 0) + 1);
39 response.once("close", () => {
40 const left = (responsesInFlight.get(socket) ?? 1) - 1;
41 responsesInFlight.set(socket, left);
42 // Pipelined requests share the socket, so the last response ends it.
43 if (left === 0 && !server.listening) socket.end();
44 });
45 });
46 return server;
48​
49/**
50 * NodeHttpServer listens before serve() attaches its handlers, so requests in
51 * between would hang. Its own pre-listen fallback stays silent while any other
52 * request listener exists, so only a listener added after listening takes over.
53 */
54export function rejectRequestsUntilServing<T extends NodeHttp.Server>(
55 server: T,
56 migrationProgress: () => DatabaseMigrationProgress | null = () => null,
57): T {
58 const rejectRequest = (request: NodeHttp.IncomingMessage, response: NodeHttp.ServerResponse) => {
59 const migration = migrationProgress();
60 const html = request.headers.accept?.includes("text/html") === true;
61 const status: ServerStartupStatus = { status: "starting", migration };
62 const message = migration
63 ? `Upgrading database (${migration.current} of ${migration.total})`
64 : "Starting T3 Code…";
65 const body = html
66 ? `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="refresh" content="1"><title>Starting T3 Code</title><style>:root{color-scheme:light dark}body{margin:0;min-height:100vh;display:grid;place-content:center;text-align:center;font:16px system-ui}h1{font-size:20px}p{opacity:.7}</style></head><body><h1>${message}</h1><p>The app will open when startup finishes.</p></body></html>`
67 : JSON.stringify(status);
68 response
69 .writeHead(503, {
70 "retry-after": "1",
71 connection: "close",
72 "cache-control": "no-store",
73 "content-type": html ? "text/html; charset=utf-8" : "application/json; charset=utf-8",
74 "content-security-policy":
75 "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
76 "x-content-type-options": "nosniff",
77 })
78 .end(body);
79 };
80 const rejectUpgrade = (_request: NodeHttp.IncomingMessage, socket: NodeStream.Duplex) => {
81 socket.end(
82 "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nConnection: close\r\nContent-Length: 0\r\n\r\n",
83 );
84 };
85 server.on("request", rejectRequest);
86 server.on("upgrade", rejectUpgrade);
87 // Node emits newListener before adding the handler, making the handoff synchronous.
88 server.on("newListener", function onNewListener(event) {
89 if (!server.listening) return;
90 if (event === "request") server.off("request", rejectRequest);
91 if (event === "upgrade") server.off("upgrade", rejectUpgrade);
92 if (
93 !server.listeners("request").includes(rejectRequest) &&
94 !server.listeners("upgrade").includes(rejectUpgrade)
95 ) {
96 server.off("newListener", onNewListener);
97 }
98 });
99 return server;