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

main
ts 264 lines 9.81 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 Effect from "effect/Effect";
5 import * as HttpApiClient from "effect/http-api/HttpApiClient";
6 import * as HttpClient from "effect/http/HttpClient";
7 import * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import type { HttpClientResponse } from "effect/http/HttpClientResponse";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import { TaskApi } from "./fixtures/http-api/api.ts";
12 import Stack from "./fixtures/http-api/stack.ts";
13
14 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
15 providers: Cloudflare.providers(),
16 });
17
18 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
19
20 const testTimeout = 60_000;
21 const burstTimeout = 90_000;
22 const requestTimeout = "5 seconds";
23 // A fresh Cloudflare deploy is eventually consistent and NOT atomic across
24 // edge PoPs: the script, the workers.dev route, and each binding (R2 / D1 /
25 // DO namespace + migration) propagate independently. Until they converge,
26 // requests landing on a cold PoP return a `404` (route not resolvable) or a
27 // `500` (script up, binding not ready). New DO namespaces / D1 databases are
28 // the slowest, so the readiness window comfortably exceeds 15s in the tail.
29 // Retry on a steady 1.5s cadence for ~60s so every first-touch request rides
30 // out the convergence window regardless of which PoP it hits. Under a
31 // full-suite run (dozens of concurrent deploys) fresh DO namespaces have
32 // been observed to serve 500s for well over 30s before converging.
33 const readinessRetry = {
34 schedule: Schedule.spaced("1500 millis"),
35 times: 40,
36 } as const;
37
38 const makeClient = (url: string) => HttpApiClient.make(TaskApi, { baseUrl: url });
39
40 // The raw `HttpClient` (used for transport-level CORS checks) does not fail on
41 // a non-2xx status, so `Effect.retry` won't fire on the freshly-deployed edge
42 // 404/500 window. Explicitly `Effect.fail` non-2xx responses to force the
43 // retry (unlike the typed `HttpApiClient`, which already fails on them).
44 const requestUntilReady = (effect: Effect.Effect<HttpClientResponse, unknown, never>) =>
45 effect.pipe(
46 Effect.timeout(requestTimeout),
47 Effect.flatMap(
48 Effect.fn(function* (res) {
49 return res.status >= 200 && res.status < 300
50 ? res
51 : yield* Effect.fail(new Error(`Worker not ready: ${res.status} ${yield* res.text}`));
52 }),
53 ),
54 Effect.retry(readinessRetry),
55 );
56
57 // Gate the deploy on the worker having propagated to the edge: hit both the
58 // R2-backed (`createTask`) and DO-backed (`createTaskDO`) paths once, retrying
59 // through the freshly-deployed 404 window, then give it extra time to settle
60 // across edge PoPs. Individual tests can then call the API directly without
61 // each re-implementing a per-request readiness retry.
62 const stack = beforeAll(
63 deploy(Stack).pipe(
64 Effect.tap(({ url }) =>
65 Effect.gen(function* () {
66 const client = yield* makeClient(url);
67 yield* client.Tasks.createTask({ payload: { title: "warmup" } }).pipe(
68 Effect.timeout(requestTimeout),
69 Effect.retry(readinessRetry),
70 );
71 yield* client.Tasks.createTaskDO({ payload: { title: "warmup" } }).pipe(
72 Effect.timeout(requestTimeout),
73 Effect.retry(readinessRetry),
74 );
75 }),
76 ),
77 // just give it some extra time to propagate
78 Effect.tap(Effect.sleep("5 seconds")),
79 ),
80 );
81 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
82
83 test(
84 "deployed http-api worker handles createTask + getTask via typed HttpApiClient",
85 Effect.gen(function* () {
86 const { url } = yield* stack;
87 expect(url).toBeTypeOf("string");
88 const client = yield* makeClient(url);
89
90 const created = yield* client.Tasks.createTask({
91 payload: { title: "Write docs" },
92 }).pipe(Effect.timeout(requestTimeout), Effect.retry(readinessRetry));
93 expect(created.title).toBe("Write docs");
94 expect(created.completed).toBe(false);
95 expect(created.id).toBeTypeOf("string");
96
97 const fetched = yield* client.Tasks.getTask({
98 params: { id: created.id },
99 }).pipe(Effect.timeout(requestTimeout), Effect.retry(readinessRetry));
100 expect(fetched.id).toBe(created.id);
101 expect(fetched.title).toBe("Write docs");
102
103 // The "missing task" path must surface the worker's domain `TaskNotFound`,
104 // not a transient edge `HttpClientError` (a cold PoP that returns a raw
105 // 404/500 placeholder before the script resolves). Retry every *non-domain*
106 // failure through the readiness window and stop the instant we observe
107 // `TaskNotFound` — so we never re-run the real domain 404, but we do ride
108 // out cold-start transport errors.
109 const missing = yield* client.Tasks.getTask({
110 params: { id: "does-not-exist" },
111 }).pipe(
112 Effect.timeout(requestTimeout),
113 Effect.retry({
114 while: (e) => e._tag !== "TaskNotFound",
115 schedule: readinessRetry.schedule,
116 times: readinessRetry.times,
117 }),
118 Effect.flip,
119 );
120 expect(missing._tag).toBe("TaskNotFound");
121 if (missing._tag === "TaskNotFound") {
122 expect(missing.id).toBe("does-not-exist");
123 }
124
125 // The Durable Object-backed route must surface the same domain 404:
126 // the DO's `getTask` fails with `TaskNotFound` for a missing key (it
127 // used to fail schema decoding and die with a 500), and the Worker
128 // forwards it.
129 const missingDO = yield* client.Tasks.getTaskDO({
130 params: { id: "does-not-exist" },
131 }).pipe(
132 Effect.timeout(requestTimeout),
133 Effect.retry({
134 while: (e) => e._tag !== "TaskNotFound",
135 schedule: readinessRetry.schedule,
136 times: readinessRetry.times,
137 }),
138 Effect.flip,
139 );
140 expect(missingDO._tag).toBe("TaskNotFound");
141 if (missingDO._tag === "TaskNotFound") {
142 expect(missingDO.id).toBe("does-not-exist");
143 }
144 }).pipe(logLevel),
145 {
146 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
147 timeout: testTimeout,
148 },
149 );
150
151 test(
152 "cors middleware adds Access-Control-Allow-Origin header on preflight",
153 Effect.gen(function* () {
154 const { url } = yield* stack;
155 // CORS preflight (OPTIONS) is transport-level and not part of the typed
156 // HttpApi surface, so this single check uses the raw HttpClient.
157 const client = yield* HttpClient.HttpClient;
158
159 const res = yield* requestUntilReady(
160 client.execute(
161 HttpClientRequest.make("OPTIONS")(url).pipe(
162 HttpClientRequest.setHeaders({
163 Origin: "https://example.com",
164 "Access-Control-Request-Method": "POST",
165 "Access-Control-Request-Headers": "content-type",
166 }),
167 ),
168 ),
169 );
170 expect(res.headers["access-control-allow-origin"]).toBeDefined();
171 }).pipe(logLevel),
172 {
173 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
174 timeout: testTimeout,
175 },
176 );
177
178 test(
179 "cors middleware adds Access-Control-Allow-Origin header on actual requests",
180 Effect.gen(function* () {
181 const { url } = yield* stack;
182 const client = yield* HttpClient.HttpClient;
183
184 const res = yield* requestUntilReady(
185 client.execute(
186 HttpClientRequest.post(`${url}/`).pipe(
187 HttpClientRequest.setHeaders({ Origin: "https://example.com" }),
188 HttpClientRequest.bodyJsonUnsafe({ title: "cors-check" }),
189 ),
190 ),
191 );
192 expect(res.status).toBe(200);
193 expect(res.headers["access-control-allow-origin"]).toBeDefined();
194 }).pipe(logLevel),
195 {
196 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
197 timeout: testTimeout,
198 },
199 );
200
201 test(
202 "concurrent createTask survives scope-lifecycle pressure",
203 Effect.gen(function* () {
204 const { url } = yield* stack;
205 const client = yield* makeClient(url);
206
207 const N = 200;
208 const results = yield* Effect.forEach(
209 Array.from({ length: N }, (_, i) => i),
210 (i) =>
211 Effect.gen(function* () {
212 const created = yield* client.Tasks.createTask({
213 payload: { title: `task-${i}` },
214 }).pipe(Effect.timeout(requestTimeout), Effect.retry(readinessRetry));
215 if (created.title !== `task-${i}`) {
216 return yield* Effect.fail(new Error(`create ${i} title mismatch: ${created.title}`));
217 }
218 return created.id;
219 }),
220 { concurrency: 64 },
221 );
222
223 expect(results).toHaveLength(N);
224 expect(new Set(results).size).toBe(N);
225 }).pipe(logLevel),
226 {
227 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
228 timeout: burstTimeout,
229 },
230 );
231
232 test(
233 "createTaskDO + getTaskDO round-trip 100x in parallel through the DO HttpApi",
234 Effect.gen(function* () {
235 const { url } = yield* stack;
236 const client = yield* makeClient(url);
237
238 const N = 100;
239 yield* Effect.forEach(
240 Array.from({ length: N }, (_, i) => i),
241 (i) =>
242 Effect.gen(function* () {
243 const title = `do-task-${i}`;
244 const created = yield* client.Tasks.createTaskDO({
245 payload: { title },
246 }).pipe(Effect.timeout(requestTimeout), Effect.retry(readinessRetry));
247 expect(created.title).toBe(title);
248 expect(created.completed).toBe(false);
249 expect(created.id).toBeTypeOf("string");
250
251 const fetched = yield* client.Tasks.getTaskDO({
252 params: { id: created.id },
253 }).pipe(Effect.timeout(requestTimeout), Effect.retry(readinessRetry));
254 expect(fetched.id).toBe(created.id);
255 expect(fetched.title).toBe(title);
256 }),
257 { concurrency: 32 },
258 );
259 }).pipe(logLevel),
260 {
261 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
262 timeout: burstTimeout,
263 },
264 );