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

main
ts 302 lines 11.4 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Alchemy from "alchemy";
5 import * as Effect from "effect/Effect";
6 import * as Cookies from "effect/http/Cookies";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as HttpClientResponse from "effect/http/HttpClientResponse";
10 import * as ChildProcess from "effect/process/ChildProcess";
11 import * as Schedule from "effect/Schedule";
12 import * as Socket from "effect/socket/Socket";
13 import * as Stream from "effect/Stream";
14 import { expectUrlContains } from "../Utils/Http.ts";
15 import { requestWorker, waitUntilStable } from "../Utils/WorkerRequest.ts";
16 import HttpServerWorker, { readyMarker, sensitiveContext } from "./fixtures/http-server-worker.ts";
17 import RawResponseWorker from "./fixtures/raw-response/worker.ts";
18 import NoSignalWorker from "./fixtures/request-abort/no-signal-worker.ts";
19 import RequestAbortWorker from "./fixtures/request-abort/worker.ts";
20
21 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
22 providers: Cloudflare.providers(),
23 });
24
25 const Stack = Alchemy.Stack(
26 "WorkersHttpServerStack",
27 { providers: Cloudflare.providers(), state: Cloudflare.state() },
28 Effect.gen(function* () {
29 const worker = yield* HttpServerWorker;
30 return { url: worker.url.as<string>() };
31 }),
32 );
33
34 const stack = beforeAll(deploy(Stack));
35 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
36
37 /**
38 * GET `url` until it serves `status` with an empty body. Both error routes
39 * respond with no body, which also distinguishes them from the workers.dev
40 * placeholder page (a 404 *with* a body) during edge propagation.
41 */
42 const getEmptyResponse = (url: string, status: number) =>
43 Effect.gen(function* () {
44 const client = yield* HttpClient.HttpClient;
45 const response = yield* client.get(url);
46 const body = yield* response.text;
47 if (response.status !== status || body !== "") {
48 return yield* Effect.fail(
49 new Error(
50 `expected empty ${status} from ${url}, got ${response.status}: ${body.slice(0, 160)}`,
51 ),
52 );
53 }
54 return response;
55 }).pipe(Effect.retry({ schedule: Schedule.spaced("1500 millis"), times: 20 }));
56
57 test(
58 "a Respondable defect keeps its intended response over the wire",
59 Effect.gen(function* () {
60 const { url } = yield* stack;
61 yield* expectUrlContains(url, readyMarker);
62
63 yield* getEmptyResponse(`${url}/missing`, 404);
64 }),
65 {
66 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
67 timeout: 180_000,
68 },
69 );
70
71 test(
72 "a failed handler responds 500 without exposing the cause",
73 Effect.gen(function* () {
74 const { url } = yield* stack;
75 yield* expectUrlContains(url, readyMarker);
76
77 const response = yield* getEmptyResponse(`${url}/boom`, 500);
78 const wireResponse = JSON.stringify(response.headers);
79 for (const sensitiveValue of sensitiveContext) {
80 expect(wireResponse).not.toContain(sensitiveValue);
81 }
82 }),
83 {
84 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
85 timeout: 180_000,
86 },
87 );
88
89 // `HttpServerResponse.fromWeb` responses take Effect-level status, headers and
90 // cookies on GET and HEAD, bodyless responses (HEAD, 204/205/304) still close
91 // their request scope, and a raw 101 upgrade passes through untouched.
92 for (const dev of [false, true]) {
93 const { test: providerTest } = Test.make({ providers: Cloudflare.providers(), dev });
94
95 providerTest.provider(
96 `web responses over HTTP (${dev ? "local" : "live"})`,
97 (stack) =>
98 Effect.gen(function* () {
99 yield* stack.destroy();
100 const worker = yield* stack.deploy(RawResponseWorker);
101 const client = yield* HttpClient.HttpClient;
102 const ready = yield* client.get(`${worker.url!}/ready`).pipe(
103 Effect.flatMap((response) => response.text),
104 Effect.retry({ schedule: Schedule.spaced("1 second"), times: 8 }),
105 Effect.repeat({
106 schedule: Schedule.spaced("1 second"),
107 times: 8,
108 until: (body) => body === "raw-response:ready",
109 }),
110 );
111 expect(ready).toBe("raw-response:ready");
112
113 for (const path of [
114 "/status",
115 "/native",
116 "/constructed-header",
117 "/explicit-status",
118 "/cookie",
119 "/stream",
120 "/no-content",
121 "/reset-content",
122 "/not-modified",
123 ]) {
124 for (const method of ["GET", "HEAD"] as const) {
125 const url = `${worker.url!}${path}`;
126 // Routes can propagate after /ready starts serving.
127 const { response, body } = yield* Effect.gen(function* () {
128 const response = yield* method === "GET" ? client.get(url) : client.head(url);
129 return { response, body: yield* response.text };
130 }).pipe(
131 Effect.repeat({
132 schedule: Schedule.spaced("1 second"),
133 times: 8,
134 until: ({ response }) =>
135 response.status !== 404 || response.headers["x-native"] !== undefined,
136 }),
137 );
138 const mutated = path === "/status" || path === "/stream";
139 const status =
140 path === "/no-content"
141 ? 204
142 : path === "/reset-content"
143 ? 205
144 : path === "/not-modified"
145 ? 304
146 : path === "/explicit-status"
147 ? 201
148 : mutated
149 ? 418
150 : 202;
151 expect(response.status).toBe(status);
152 expect(response.headers["x-native"]).toBe(
153 mutated ? "effect" : path === "/constructed-header" ? "constructed" : "native",
154 );
155 expect(response.headers["x-remove"]).toBe(mutated ? undefined : "native");
156 if (mutated) {
157 expect(response.headers["x-observed-status"]).toBe("202");
158 expect(response.headers["x-observed-native"]).toBe("native");
159 }
160 expect(Cookies.toRecord(response.cookies)).toEqual(
161 path === "/cookie" ? { a: "1", b: "2", session: "abc" } : { a: "1", b: "2" },
162 );
163 expect(body).toBe(
164 method === "HEAD" || [204, 205, 304].includes(status)
165 ? ""
166 : path === "/stream"
167 ? "raw-response:streamed"
168 : "raw-response:body",
169 );
170 const finalized = yield* client
171 .get(`${worker.url!}/finalized?entry=${encodeURIComponent(`${method}:${path}`)}`)
172 .pipe(
173 Effect.flatMap((response) => response.text),
174 Effect.repeat({
175 schedule: Schedule.spaced("1 second"),
176 times: 8,
177 until: (body) => body === "true",
178 }),
179 );
180 expect({ request: `${method} ${path}`, finalized }).toEqual({
181 request: `${method} ${path}`,
182 finalized: "true",
183 });
184 }
185 }
186
187 yield* Effect.gen(function* () {
188 const socket = yield* Socket.makeWebSocket(
189 `${worker.url!.replace(/^http/, "ws")}/websocket`,
190 );
191 const reader = yield* socket.reader;
192 const writer = yield* socket.writer;
193 yield* writer.write("response-upgrade");
194 expect(yield* reader.pull).toEqual(["response-upgrade"]);
195 }).pipe(Effect.scoped, Effect.provide(Socket.layerWebSocketConstructorGlobal));
196 yield* stack.destroy();
197 }),
198 {
199 tags: ["provider:cloudflare", "provider:cloudflare:worker", ...(dev ? ["local"] : ["live"])],
200 },
201 );
202 }
203
204 /**
205 * Holds a raw HTTP/1.1 request open over `openssl s_client`. Closing the
206 * scope SIGKILLs the client, so the kernel drops the connection without a TLS
207 * `close_notify`, the way a client that went away does. (A `close_notify`
208 * reads as an HTTP half-close, which Cloudflare keeps serving, and Bun's
209 * `node:tls` sends one even from `destroy()`.)
210 */
211 const rawRequest = (host: string, request: string) =>
212 ChildProcess.make(
213 "openssl",
214 ["s_client", "-connect", `${host}:443`, "-servername", host, "-alpn", "http/1.1", "-quiet"],
215 {
216 // `-quiet` keeps the connection open after stdin ends.
217 stdin: Stream.make(request).pipe(Stream.encodeText),
218 stdout: "ignore",
219 stderr: "ignore",
220 killSignal: "SIGKILL",
221 },
222 );
223
224 /**
225 * Deploy `worker`, send `/slow` over a raw connection, kill the client once
226 * the handler has started, and return what the handler recorded within
227 * `polls` seconds afterwards.
228 */
229 const disconnectMidRequest = (worker: { url: string | undefined }, polls: number) =>
230 Effect.gen(function* () {
231 // `/ready` calls the journal Durable Object, whose first calls after a
232 // deploy can fail with an opaque "internal error".
233 yield* waitUntilStable(
234 `request-abort Worker at ${worker.url}`,
235 requestWorker(HttpClientRequest.get(`${worker.url!}/ready`)).pipe(
236 Effect.flatMap((response) => response.text),
237 Effect.map((body) => body === "request-abort:ready"),
238 Effect.catch(() => Effect.succeed(false)),
239 ),
240 { timeout: "60 seconds" },
241 );
242 const id = yield* Effect.sync(() => crypto.randomUUID());
243 const events = requestWorker(HttpClientRequest.get(`${worker.url!}/events?id=${id}`)).pipe(
244 Effect.flatMap(HttpClientResponse.filterStatusOk),
245 Effect.flatMap((response) => response.json),
246 Effect.map((body) => body as string[]),
247 Effect.retry({ schedule: Schedule.spaced("1 second"), times: 10 }),
248 );
249
250 const host = yield* Effect.sync(() => new URL(worker.url!).host);
251 yield* Effect.scoped(
252 Effect.gen(function* () {
253 yield* rawRequest(host, `GET /slow?id=${id} HTTP/1.1\r\nHost: ${host}\r\n\r\n`);
254 yield* events.pipe(
255 Effect.repeat({
256 schedule: Schedule.spaced("500 millis"),
257 times: 30,
258 until: (events) => events.includes("started"),
259 }),
260 );
261 }),
262 );
263
264 return yield* events.pipe(
265 Effect.repeat({
266 schedule: Schedule.spaced("1 second"),
267 times: polls,
268 until: (events) => events.some((event) => event.startsWith("released:")),
269 }),
270 );
271 });
272
273 // A client that disconnects interrupts the handler, so its resources are
274 // released as an interruption instead of staying open for nobody. Live only:
275 // local workerd does not fire `request.signal` when the client disconnects.
276 test.provider(
277 "a client disconnect interrupts the handler",
278 (stack) =>
279 Effect.gen(function* () {
280 yield* stack.destroy();
281 const worker = yield* stack.deploy(RequestAbortWorker);
282 const events = yield* disconnectMidRequest(worker, 20);
283 expect(events).toEqual(["started", "released:interrupt"]);
284 yield* stack.destroy();
285 }),
286 { timeout: 120_000 },
287 );
288
289 // Without `enable_request_signal`, Cloudflare cancels the request when the
290 // client disconnects and the handler's finalizers never run.
291 test.provider(
292 "without enable_request_signal a client disconnect skips the handler's release",
293 (stack) =>
294 Effect.gen(function* () {
295 yield* stack.destroy();
296 const worker = yield* stack.deploy(NoSignalWorker);
297 const events = yield* disconnectMidRequest(worker, 10);
298 expect(events).toEqual(["started"]);
299 yield* stack.destroy();
300 }),
301 { timeout: 120_000 },
302 );