The best way to control Claude Code, Codex and more from any computer or phone

main
ts 202 lines 7.18 KB
Raw
1 import * as NodeHttp from "node:http";
2 import type { IncomingMessage, ServerResponse } from "node:http";
3 import { finished } from "node:stream";
4 import { URL as NodeURL } from "node:url";
5 import type * as vite from "vite";
6 import { proxyRequestHeaders } from "./forwarded-host.ts";
7 import { HEADER_ERROR_STACK } from "./module-runner/constants.shared.ts";
8
9 /**
10 * The Worker runtime URL for a request target (`req.url`): the path and
11 * query of the request on the runtime's `address`.
12 *
13 * Never `new URL(requestTarget, address)`: a target starting with `//` is a
14 * protocol-relative reference there, so `//127.0.0.1:8080/x` would replace
15 * the host and send the request to another service on the machine (#2344).
16 * An absolute-form target (`GET http://host/x`) keeps only its path too.
17 */
18 export function workerRequestUrl(
19 requestTarget: string | undefined,
20 address: string | URL,
21 ): NodeURL {
22 const url = new NodeURL(address.toString());
23 const target = requestTarget || "/";
24 if (target.startsWith("/")) {
25 const query = target.indexOf("?");
26 url.pathname = query === -1 ? target : target.slice(0, query);
27 url.search = query === -1 ? "" : target.slice(query);
28 } else {
29 const parsed = new NodeURL(target, url);
30 url.pathname = parsed.pathname;
31 url.search = parsed.search;
32 }
33 return url;
34 }
35
36 /**
37 * Forwards a dev or preview server request to the Worker runtime at `target`
38 * and relays the Worker's response.
39 *
40 * When the client hangs up, the Worker request is cancelled, as it would be in
41 * production. Otherwise a stream the client abandoned (a closed page's SSE
42 * subscription) keeps running in workerd.
43 */
44 export function forwardWorkerRequest(
45 request: IncomingMessage,
46 response: ServerResponse,
47 target: NodeURL,
48 proxySharedSecret: string,
49 logger: vite.Logger,
50 /** Receives the Worker's uncaught error, for Vite's error page. */
51 next?: (error: Error) => void,
52 ): void {
53 const client = request.socket;
54 // The client hung up while earlier middlewares ran.
55 if (client.destroyed) {
56 return;
57 }
58 // A connection per request, as a defense: with a pooled connection, requests
59 // were reported to fail with a 502 under load after workerd cut a stream
60 // short (#1869). We couldn't reproduce that against workerd, but a fresh
61 // loopback connection costs next to nothing. See
62 // https://github.com/alchemy-run/alchemy/pull/2242.
63 //
64 // A request with a body asks workerd for `100 Continue` first, and the body
65 // is only forwarded once workerd sends it, which it does when the Worker
66 // starts reading. A Worker that answers without reading (a 413 for an
67 // oversized upload) then never receives the body: workerd closes the
68 // connection after such a response, and an upload still in flight races the
69 // response, which macOS can lose to the connection reset.
70 const hasBody =
71 request.headers["transfer-encoding"] !== undefined ||
72 Number(request.headers["content-length"] ?? 0) > 0;
73 const upstream = NodeHttp.request(target, {
74 agent: false,
75 method: request.method,
76 headers: {
77 ...proxyRequestHeaders(request, target, proxySharedSecret),
78 ...(hasBody ? { expect: "100-continue" } : {}),
79 },
80 });
81 // Watch the socket, not the response: Bun's `ServerResponse` emits no `close`
82 // on a hang-up. Once the request body has been read, Bun reports no hang-up
83 // at all, so there the Worker request runs to completion.
84 let hungUp = false;
85 const onHangUp = () => {
86 hungUp = true;
87 upstream.destroy();
88 };
89 client.once("close", onHangUp);
90 let settled = false;
91 const settle = () => {
92 const first = !settled;
93 settled = true;
94 client.off("close", onHangUp);
95 return first;
96 };
97 const fail = (error: Error) => {
98 // A failure caused by the hang-up has nobody to answer.
99 if (!settle() || hungUp) {
100 return;
101 }
102 logger.error(`Worker request failed: ${error.message}`, { error, timestamp: true });
103 if (response.headersSent) {
104 // A partial body must not be completed with a 502.
105 response.destroy();
106 return;
107 }
108 response.writeHead(502, { "content-type": "text/plain" });
109 response.end("Bad Gateway");
110 };
111 // Without a listener a connection error is an unhandled `error` event, which
112 // takes down the server. Requests in flight while the Worker runtime is
113 // being replaced hit exactly that.
114 //
115 // The Worker may also answer part-way through reading the body. workerd
116 // then closes the connection, so forwarding the rest of the body fails.
117 // That is no failure of the response, which `workerResponse` reports on its
118 // own.
119 let answered = false;
120 upstream.on("error", (error) => {
121 if (!answered) {
122 fail(error);
123 }
124 });
125 // Drain what is left of the body: a request whose body is never read makes
126 // Node drop the client's kept-alive connection, failing its next request.
127 // Forwarding continues until workerd closes the connection, so a Worker can
128 // stream its response while it still reads the body.
129 upstream.on("close", () => {
130 if (answered) {
131 request.unpipe(upstream);
132 request.resume();
133 }
134 });
135 upstream.on("response", (workerResponse) => {
136 answered = true;
137 if (next !== undefined && workerResponse.headers[HEADER_ERROR_STACK.toLowerCase()]) {
138 // The Worker threw: revive its error for Vite's error page, as
139 // `@cloudflare/vite-plugin` does.
140 const chunks: Array<Buffer> = [];
141 workerResponse.on("data", (chunk: Buffer) => chunks.push(chunk));
142 finished(workerResponse, (error) => {
143 if (error) {
144 fail(error);
145 } else if (settle()) {
146 next(reviveError(JSON.parse(Buffer.concat(chunks).toString("utf8"))));
147 }
148 });
149 return;
150 }
151 // The Worker's status text (`new Response(body, { statusText })`) is
152 // relayed as written, as `@cloudflare/vite-plugin` does since 1.65.
153 response.writeHead(
154 workerResponse.statusCode ?? 500,
155 workerResponse.statusMessage,
156 workerResponse.headers,
157 );
158 workerResponse.pipe(response);
159 // `pipe` alone would leave the client's response open forever when the
160 // Worker's is cut short.
161 finished(workerResponse, (error) => {
162 if (error) {
163 fail(error);
164 } else {
165 settle();
166 }
167 });
168 });
169 let forwarding = !hasBody;
170 if (hasBody) {
171 upstream.once("continue", () => {
172 forwarding = true;
173 request.pipe(upstream);
174 });
175 } else {
176 request.pipe(upstream);
177 }
178 // Answered without the body: drain the client's (see above), and close the
179 // upstream request, which never sent one.
180 upstream.once("response", (workerResponse) => {
181 if (forwarding) return;
182 request.resume();
183 finished(workerResponse, () => upstream.destroy());
184 });
185 }
186
187 interface ReducedError {
188 readonly name?: string;
189 readonly message?: string;
190 readonly stack?: string;
191 readonly cause?: ReducedError;
192 }
193
194 /** Revives an error the Worker serialized with `reduceError`. */
195 function reviveError(reduced: ReducedError): Error {
196 const error = new Error(reduced.message, {
197 cause: reduced.cause === undefined ? undefined : reviveError(reduced.cause),
198 });
199 if (reduced.name !== undefined) error.name = reduced.name;
200 if (reduced.stack !== undefined) error.stack = reduced.stack;
201 return error;
202 }