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

main
ts 465 lines 16.3 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as dns from "@distilled.cloud/cloudflare/dns";
7 import * as workers from "@distilled.cloud/cloudflare/workers";
8 import * as Drift from "alchemy/Drift";
9 import * as Cause from "effect/Cause";
10 import * as Effect from "effect/Effect";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import * as pathe from "pathe";
15 import { stageSuffix } from "../../names.ts";
16 import { expectUrlAbsent, expectUrlContains } from "../Utils/Http.ts";
17 import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 const main = pathe.resolve(import.meta.dirname, "fixtures/worker.ts");
24
25 const zoneName =
26 process.env.CLOUDFLARE_TEST_WORKER_ROUTE_ZONE_NAME ??
27 process.env.CLOUDFLARE_TEST_R2_DOMAIN_ZONE_NAME ??
28 "alchemy-test-2.us";
29
30 // Deterministic per-test path prefixes on the zone apex. Each test owns a
31 // disjoint prefix so reruns and parallel runs never collide, and the same
32 // patterns are reused on every run (never derive names from Date.now()).
33 const routeSuffix = `alchemy-worker-route-${stageSuffix()}`;
34
35 const workerMarker = "Hello from TestWorker";
36
37 const resolveZoneId = Effect.gen(function* () {
38 const { accountId } = yield* yield* CloudflareEnvironment;
39 const zone = yield* findZoneByName({ accountId, name: zoneName });
40 if (!zone) {
41 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
42 }
43 return zone.id;
44 });
45
46 // A freshly-minted scoped API token propagates eventually-consistently
47 // across Cloudflare's edge — retry the typed `Forbidden` blips on the
48 // tests' own out-of-band verification calls.
49 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
50
51 const listByPattern = (zoneId: string, pattern: string) =>
52 workers.listRoutes.items({ zoneId }).pipe(
53 Stream.filter((r) => r.pattern === pattern),
54 Stream.runCollect,
55 Effect.map((chunk) => Array.from(chunk)),
56 Effect.retry({
57 while: (e) => e._tag === "Forbidden",
58 schedule: forbiddenRetrySchedule,
59 times: 8,
60 }),
61 );
62
63 const findRoute = (zoneId: string, pattern: string) =>
64 listByPattern(zoneId, pattern).pipe(Effect.map((rs) => rs[0]));
65
66 // Workers only run on proxied hostnames, so the zone apex needs a proxied
67 // placeholder record for route-matched requests to reach Cloudflare's edge
68 // at all. The record is standing test-zone infrastructure (like the zone
69 // itself): ensure it exists out-of-band, never tear it down.
70 const ensureApexPlaceholder = (zoneId: string) =>
71 Effect.gen(function* () {
72 const existing = yield* dns.listRecords.items({ zoneId }).pipe(
73 Stream.filter((r) => r.name === zoneName && (r.type === "A" || r.type === "AAAA")),
74 Stream.runCollect,
75 Effect.map((chunk) => Array.from(chunk)[0]),
76 Effect.retry({
77 while: (e) => e._tag === "Forbidden",
78 schedule: forbiddenRetrySchedule,
79 times: 8,
80 }),
81 );
82 if (existing) return;
83 yield* dns.createRecord({
84 zoneId,
85 name: zoneName,
86 type: "AAAA",
87 content: "100::",
88 proxied: true,
89 ttl: 1,
90 comment: "standing placeholder so Workers routes serve on the zone apex",
91 });
92 });
93
94 // Delete every route matching the pattern — purge leftovers from
95 // interrupted runs so tests start from a clean slate (Cloudflare enforces
96 // one route per pattern per zone).
97 const purgeRoutes = (zoneId: string, ...patterns: string[]) =>
98 Effect.forEach(patterns, (pattern) =>
99 listByPattern(zoneId, pattern).pipe(
100 Effect.flatMap(
101 Effect.forEach((r) =>
102 workers.deleteRoute({ zoneId, routeId: r.id }).pipe(Effect.catch(() => Effect.void)),
103 ),
104 ),
105 ),
106 );
107
108 // --- lifecycle: create → no-op → update (change + add) → remove ---------
109
110 const T1_V1 = `${zoneName}/${routeSuffix}/t1/api/*`;
111 const T1_V2 = `${zoneName}/${routeSuffix}/t1/api/v2/*`;
112 const T1_ADDED = `${zoneName}/${routeSuffix}/t1/other/*`;
113 const T1_MATCH_URL = `https://${zoneName}/${routeSuffix}/t1/api/ping`;
114 const T1_MISS_URL = `https://${zoneName}/${routeSuffix}/t1/unknown`;
115
116 test.provider(
117 "creates, keeps, updates, and removes worker zone routes",
118 (stack) =>
119 Effect.gen(function* () {
120 const { accountId } = yield* yield* CloudflareEnvironment;
121 const zoneId = yield* resolveZoneId;
122
123 yield* stack.destroy();
124 yield* purgeRoutes(zoneId, T1_V1, T1_V2, T1_ADDED);
125 yield* ensureApexPlaceholder(zoneId);
126
127 let workerName: string | undefined;
128
129 yield* Effect.gen(function* () {
130 // Create — zone resolved from `zoneName`.
131 const worker = yield* stack.deploy(
132 Effect.gen(function* () {
133 return yield* Cloudflare.Worker("RouteWorker", {
134 main,
135 workersDev: false,
136 routes: [{ pattern: T1_V1, zoneName }],
137 });
138 }),
139 );
140 workerName = worker.workerName;
141
142 expect(worker.routes).toHaveLength(1);
143 expect(worker.routes[0]?.pattern).toEqual(T1_V1);
144 expect(worker.routes[0]?.zoneId).toEqual(zoneId);
145 const initialRouteId = worker.routes[0]!.id;
146
147 const liveRoute = yield* findRoute(zoneId, T1_V1);
148 expect(liveRoute?.script).toEqual(worker.workerName);
149
150 yield* expectUrlContains(T1_MATCH_URL, workerMarker, {
151 label: "worker route match",
152 timeout: "60 seconds",
153 });
154 yield* expectUrlAbsent(T1_MISS_URL, workerMarker, {
155 label: "worker route miss",
156 timeout: "30 seconds",
157 });
158
159 // No-op — identical props must not churn the route (same id).
160 const noop = yield* stack.deploy(
161 Effect.gen(function* () {
162 return yield* Cloudflare.Worker("RouteWorker", {
163 main,
164 workersDev: false,
165 routes: [{ pattern: T1_V1, zoneName }],
166 });
167 }),
168 );
169 expect(noop.routes).toHaveLength(1);
170 expect(noop.routes[0]?.id).toEqual(initialRouteId);
171
172 // Update — change the first pattern (delete + create, addressed by
173 // explicit `zoneId`) and add a second route whose zone is inferred
174 // from the pattern's hostname.
175 const updated = yield* stack.deploy(
176 Effect.gen(function* () {
177 return yield* Cloudflare.Worker("RouteWorker", {
178 main,
179 workersDev: false,
180 routes: [{ pattern: T1_V2, zoneId }, { pattern: T1_ADDED }],
181 });
182 }),
183 );
184
185 const updatedPatterns = updated.routes.map((r) => r.pattern).sort();
186 expect(updatedPatterns).toEqual([T1_V2, T1_ADDED].sort());
187 expect(updated.routes.every((r) => r.zoneId === zoneId)).toBe(true);
188
189 expect(yield* findRoute(zoneId, T1_V1)).toBeUndefined();
190 expect((yield* findRoute(zoneId, T1_V2))?.script).toEqual(worker.workerName);
191 expect((yield* findRoute(zoneId, T1_ADDED))?.script).toEqual(worker.workerName);
192
193 // Remove — omitting the `routes` prop entirely detaches everything
194 // recorded in the previous state.
195 const removed = yield* stack.deploy(
196 Effect.gen(function* () {
197 return yield* Cloudflare.Worker("RouteWorker", {
198 main,
199 workersDev: false,
200 });
201 }),
202 );
203 expect(removed.routes).toHaveLength(0);
204
205 expect(yield* findRoute(zoneId, T1_V2)).toBeUndefined();
206 expect(yield* findRoute(zoneId, T1_ADDED)).toBeUndefined();
207 }).pipe(
208 Effect.ensuring(
209 Effect.gen(function* () {
210 yield* stack.destroy().pipe(Effect.ignore);
211 if (workerName) {
212 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
213 }
214 }),
215 ),
216 );
217 }).pipe(logLevel),
218 {
219 tags: [
220 "provider:cloudflare",
221 "provider:cloudflare:dns",
222 "provider:cloudflare:worker",
223 "provider:cloudflare:zone",
224 "live",
225 ],
226 timeout: 300_000,
227 },
228 );
229
230 // --- observed state is the baseline: drift removal + destroy cleanup ----
231
232 const T2_KEPT = `${zoneName}/${routeSuffix}/t2/api/*`;
233 const T2_DRIFT = `${zoneName}/${routeSuffix}/t2/drift/*`;
234
235 test.provider(
236 "removes out-of-band routes on update and detaches routes on destroy",
237 (stack) =>
238 Effect.gen(function* () {
239 const { accountId } = yield* yield* CloudflareEnvironment;
240 const zoneId = yield* resolveZoneId;
241
242 yield* stack.destroy();
243 yield* purgeRoutes(zoneId, T2_KEPT, T2_DRIFT);
244
245 let workerName: string | undefined;
246
247 yield* Effect.gen(function* () {
248 const worker = yield* stack.deploy(
249 Effect.gen(function* () {
250 return yield* Cloudflare.Worker("DriftRouteWorker", {
251 main,
252 workersDev: false,
253 compatibility: { date: "2024-01-01" },
254 routes: [{ pattern: T2_KEPT, zoneName }],
255 });
256 }),
257 );
258 workerName = worker.workerName;
259 const keptRouteId = worker.routes[0]!.id;
260
261 // Attach a route to the same script out-of-band — the reconciler
262 // never recorded it, so it is pure drift.
263 const drift = yield* workers
264 .createRoute({
265 zoneId,
266 pattern: T2_DRIFT,
267 script: worker.workerName,
268 })
269 .pipe(
270 Effect.retry({
271 while: (e) => e._tag === "Forbidden",
272 schedule: forbiddenRetrySchedule,
273 times: 8,
274 }),
275 );
276 expect(drift.id).toBeDefined();
277
278 // Force an update (compat date bump) with the same desired routes:
279 // the kept route must survive untouched (same id) and the drift
280 // route — observed in the same zone, attached to this script, not
281 // desired — must be removed.
282 const updated = yield* stack.deploy(
283 Effect.gen(function* () {
284 return yield* Cloudflare.Worker("DriftRouteWorker", {
285 main,
286 workersDev: false,
287 compatibility: { date: "2024-01-02" },
288 routes: [{ pattern: T2_KEPT, zoneName }],
289 });
290 }),
291 );
292
293 expect(updated.routes).toHaveLength(1);
294 expect(updated.routes[0]?.id).toEqual(keptRouteId);
295 expect(yield* findRoute(zoneId, T2_DRIFT)).toBeUndefined();
296 }).pipe(
297 Effect.ensuring(
298 Effect.gen(function* () {
299 yield* stack.destroy().pipe(Effect.ignore);
300 if (workerName) {
301 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
302 }
303 }),
304 ),
305 );
306
307 // Destroying the worker detaches its routes from the zone.
308 expect(yield* findRoute(zoneId, T2_KEPT)).toBeUndefined();
309 }).pipe(logLevel),
310 {
311 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
312 timeout: 300_000,
313 },
314 );
315
316 // --- refusal: a pattern already routed to a different Worker ------------
317
318 const T3_PATTERN = `${zoneName}/${routeSuffix}/t3/api/*`;
319
320 test.provider(
321 "refuses to steal a route pattern attached to another Worker",
322 (stack) =>
323 Effect.gen(function* () {
324 const zoneId = yield* resolveZoneId;
325
326 yield* stack.destroy();
327 yield* purgeRoutes(zoneId, T3_PATTERN);
328
329 yield* Effect.gen(function* () {
330 const owner = yield* stack.deploy(
331 Effect.gen(function* () {
332 return yield* Cloudflare.Worker("RouteOwnerWorker", {
333 main,
334 workersDev: false,
335 routes: [{ pattern: T3_PATTERN, zoneName }],
336 });
337 }),
338 );
339
340 const error = yield* stack
341 .deploy(
342 Effect.gen(function* () {
343 const owner = yield* Cloudflare.Worker("RouteOwnerWorker", {
344 main,
345 workersDev: false,
346 routes: [{ pattern: T3_PATTERN, zoneName }],
347 });
348 const thief = yield* Cloudflare.Worker("RouteThiefWorker", {
349 main,
350 workersDev: false,
351 routes: [{ pattern: T3_PATTERN, zoneName }],
352 });
353 return { owner, thief };
354 }),
355 )
356 .pipe(
357 Effect.as(undefined),
358 Effect.catchCause((cause) => Effect.succeed(findAttachRefusal(cause))),
359 );
360
361 expect(error).toBeDefined();
362 expect(error?.message).toContain("already attached to Worker");
363
364 // The pattern still routes to its original owner.
365 const live = yield* findRoute(zoneId, T3_PATTERN);
366 expect(live?.script).toEqual(owner.workerName);
367 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)));
368 }).pipe(logLevel),
369 {
370 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
371 timeout: 300_000,
372 },
373 );
374
375 // --- drift ignores the order Cloudflare lists unchanged routes in (#1825) -
376
377 const T4_PATTERNS = ["a", "b", "c", "d"].map(
378 (segment) => `${zoneName}/${routeSuffix}/t4/${segment}/*`,
379 );
380
381 test.provider(
382 "drift reports unchanged routes as unchanged whatever order Cloudflare lists them in",
383 (stack) =>
384 Effect.gen(function* () {
385 const { accountId } = yield* yield* CloudflareEnvironment;
386 const zoneId = yield* resolveZoneId;
387
388 yield* stack.destroy();
389 yield* purgeRoutes(zoneId, ...T4_PATTERNS);
390
391 const deployRoutes = (patterns: readonly string[]) =>
392 stack.deploy(
393 Effect.gen(function* () {
394 return yield* Cloudflare.Worker("RouteOrderWorker", {
395 main,
396 workersDev: false,
397 routes: patterns.map((pattern) => ({ pattern, zoneName })),
398 });
399 }),
400 );
401
402 const listedOrder = (workerName: string) =>
403 workers.listRoutes.items({ zoneId }).pipe(
404 Stream.filter((r) => r.script === workerName && T4_PATTERNS.includes(r.pattern)),
405 Stream.map((r) => r.pattern),
406 Stream.runCollect,
407 Effect.map((chunk) => Array.from(chunk)),
408 );
409
410 let workerName: string | undefined;
411
412 yield* Effect.gen(function* () {
413 const worker = yield* deployRoutes(T4_PATTERNS);
414 workerName = worker.workerName;
415
416 // Redeploy the same routes declared in the reverse of Cloudflare's
417 // listing order, so state's order and the listing order differ.
418 const listed = yield* listedOrder(worker.workerName);
419 expect([...listed].sort()).toEqual([...T4_PATTERNS].sort());
420 const reordered = yield* deployRoutes([...listed].reverse());
421 expect(reordered.routes.map((r) => r.pattern)).toEqual([...listed].reverse());
422 expect(yield* listedOrder(worker.workerName)).toEqual(listed);
423
424 const detected = yield* Drift.detect({
425 name: stack.name,
426 stage: stack.stage,
427 }).pipe(Effect.provide(stack.state));
428 expect(detected.resources.RouteOrderWorker).toMatchObject({
429 action: "unchanged",
430 resourceType: "Cloudflare.Worker",
431 });
432 }).pipe(
433 Effect.ensuring(
434 Effect.gen(function* () {
435 yield* stack.destroy().pipe(Effect.ignore);
436 if (workerName) {
437 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
438 }
439 }),
440 ),
441 );
442 }).pipe(logLevel),
443 {
444 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
445 timeout: 300_000,
446 },
447 );
448
449 /**
450 * Pull the attach-refusal `Error` out of a Cause regardless of whether the
451 * engine surfaced it as a typed failure or a defect (`Effect.die`).
452 */
453 const findAttachRefusal = (cause: Cause.Cause<unknown>): Error | undefined =>
454 cause.reasons
455 .map((reason) =>
456 Cause.isFailReason(reason)
457 ? reason.error
458 : Cause.isDieReason(reason)
459 ? reason.defect
460 : undefined,
461 )
462 .find(
463 (value): value is Error =>
464 value instanceof Error && value.message.includes("already attached to Worker"),
465 );