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

main
ts 456 lines 15.8 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as workers from "@distilled.cloud/cloudflare/workers";
6 import * as Effect from "effect/Effect";
7 import { MinimumLogLevel } from "effect/References";
8 import * as Schedule from "effect/Schedule";
9 import { expectUrlContains } from "../Utils/Http.ts";
10 import CacheTestWorker from "./fixtures/cache/cache-worker.ts";
11
12 const { test } = Test.make({ providers: Cloudflare.providers() });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 // The worker stamps every invocation with a fresh UUID, so two fetches of
17 // the same URL returning the same body means the second response was served
18 // from the Workers Cache without invoking the worker.
19 const cachedScript = `export default {
20 async fetch() {
21 return new Response("id:" + crypto.randomUUID(), {
22 headers: { "Cache-Control": "public, max-age=300" },
23 });
24 },
25 };
26 `;
27
28 const fetchCached = (url: string) =>
29 Effect.tryPromise(async (signal) => {
30 // NO cache-busting here — the whole point is hitting the same cache key.
31 const res = await fetch(url, { signal });
32 return {
33 status: res.status,
34 cacheStatus: res.headers.get("cf-cache-status"),
35 body: await res.text(),
36 };
37 });
38
39 // Poll `url` until two consecutive responses carry the same worker-stamped
40 // body ("id:<uuid>"), proving the second was served from the Workers Cache
41 // without invoking the worker. Only marker-carrying bodies participate:
42 // workers.dev placeholder pages also serve identical 200 bodies, so an
43 // unanchored comparison would count two placeholders as a false "hit".
44 // Bounded so a broken cache fails fast instead of hitting the vitest
45 // timeout.
46 const pollForCacheHit = (url: string) => {
47 let previous: string | undefined;
48 return fetchCached(url).pipe(
49 Effect.map((res) => {
50 const isWorkerBody = res.status === 200 && res.body.startsWith("id:");
51 const isHit =
52 (isWorkerBody && previous !== undefined && res.body === previous) ||
53 res.cacheStatus === "HIT";
54 if (isWorkerBody) {
55 previous = res.body;
56 }
57 return { ...res, isHit };
58 }),
59 Effect.repeat({
60 schedule: Schedule.spaced("2 seconds"),
61 until: (res) => res.isHit,
62 times: 20,
63 }),
64 );
65 };
66
67 test.provider(
68 "worker with Workers Cache enabled serves repeat requests from cache",
69 (stack) =>
70 Effect.gen(function* () {
71 yield* stack.destroy();
72
73 const { worker } = yield* stack.deploy(
74 Effect.gen(function* () {
75 return {
76 worker: yield* Cloudflare.Worker("CachedWorker", {
77 script: cachedScript,
78 cache: {
79 enabled: true,
80 crossVersionCache: true,
81 },
82 }),
83 };
84 }),
85 );
86 expect(worker.url).toBeDefined();
87
88 // Ride out workers.dev propagation before probing cache behavior.
89 yield* expectUrlContains(worker.url!, "id:", {
90 label: "cached worker propagation",
91 });
92
93 const hit = yield* pollForCacheHit(`${worker.url}/cached`);
94 expect(hit.isHit).toBe(true);
95
96 // Metadata-only update: same script, cache turned off. The metadata
97 // hash must register the change and the API must accept the update.
98 const disabled = yield* stack.deploy(
99 Effect.gen(function* () {
100 return {
101 worker: yield* Cloudflare.Worker("CachedWorker", {
102 script: cachedScript,
103 cache: {
104 enabled: false,
105 },
106 }),
107 };
108 }),
109 );
110 expect(disabled.worker.workerName).toEqual(worker.workerName);
111
112 yield* stack.destroy();
113 }).pipe(logLevel),
114 {
115 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
116 timeout: 240_000,
117 },
118 );
119
120 // Effect-native path: `yield* Cloudflare.cache()` in the init phase enables
121 // Workers Cache via the binding contract (no `cache` prop) and returns the
122 // runtime purge client backed by `ctx.cache`.
123 test.provider(
124 "Cloudflare.cache() enables the cache and purges by tag",
125 (stack) =>
126 Effect.gen(function* () {
127 yield* stack.destroy();
128
129 const { worker } = yield* stack.deploy(
130 Effect.gen(function* () {
131 return { worker: yield* CacheTestWorker };
132 }),
133 );
134 expect(worker.url).toBeDefined();
135
136 yield* expectUrlContains(`${worker.url}/item`, "id:", {
137 label: "cache worker propagation",
138 });
139
140 // Poll the same URL until a repeat body proves the binding actually
141 // enabled the cache.
142 const url = `${worker.url}/item`;
143 const hit = yield* pollForCacheHit(url);
144 expect(hit.isHit).toBe(true);
145 const cachedBody = hit.body;
146
147 // Purge by Cache-Tag through the runtime client. Retried until the
148 // response parses as JSON — transient placeholders/5xx bodies throw
149 // and retry — and reports success: the purge runs on a token the
150 // binding just minted, which can be rejected until it propagates. A
151 // purge still failing after the retries surfaces its errors below.
152 const purged = yield* Effect.sync(() => `${worker.url}/purge?cb=${Date.now()}`).pipe(
153 Effect.flatMap(fetchCached),
154 Effect.flatMap((res) =>
155 res.status === 200
156 ? Effect.try(() => JSON.parse(res.body) as { success: boolean; errors?: unknown })
157 : Effect.fail(new Error(`Purge worker not ready: ${res.status}`)),
158 ),
159 Effect.retry({
160 schedule: Schedule.spaced("2 seconds"),
161 times: 10,
162 }),
163 Effect.repeat({
164 until: (result) => result.success,
165 schedule: Schedule.spaced("2 seconds"),
166 times: 10,
167 }),
168 );
169 expect(purged).toMatchObject({ success: true });
170
171 // A fresh invocation id proves the tag purge evicted the entry. The
172 // marker check keeps a placeholder page (also ≠ cachedBody) from
173 // passing as "fresh".
174 const fresh = yield* fetchCached(url).pipe(
175 Effect.repeat({
176 schedule: Schedule.spaced("2 seconds"),
177 until: (res) =>
178 res.status === 200 && res.body.startsWith("id:") && res.body !== cachedBody,
179 times: 20,
180 }),
181 );
182 expect(fresh.body).not.toBe(cachedBody);
183 expect(fresh.body.startsWith("id:")).toBe(true);
184
185 yield* stack.destroy();
186 }).pipe(logLevel),
187 {
188 tags: [
189 "provider:cloudflare",
190 "provider:cloudflare:cache",
191 "provider:cloudflare:worker",
192 "live",
193 ],
194 timeout: 240_000,
195 },
196 );
197
198 // A gateway default export that forwards to a named `Public` entrypoint via
199 // `ctx.exports`. Each layer stamps its own UUID, so one response body shows
200 // which layer ran: a repeated `pub:` id with a fresh `gw:` id means only
201 // `Public` was served from cache; a fully repeated body means the gateway
202 // itself was cached.
203 const entrypointScript = `import { WorkerEntrypoint } from "cloudflare:workers";
204
205 export class Public extends WorkerEntrypoint {
206 async fetch() {
207 return new Response("pub:" + crypto.randomUUID(), {
208 headers: { "Cache-Control": "public, max-age=300" },
209 });
210 }
211 }
212
213 export default {
214 async fetch(request, env, ctx) {
215 const inner = await ctx.exports.Public.fetch(request);
216 return new Response("gw:" + crypto.randomUUID() + "|" + (await inner.text()), {
217 headers: { "Cache-Control": "public, max-age=300" },
218 });
219 },
220 };
221 `;
222
223 const parseLayers = (body: string) => {
224 const match = /^gw:([^|]+)\|pub:(.+)$/.exec(body);
225 return match ? { gateway: match[1]!, public: match[2]! } : undefined;
226 };
227
228 // Poll until two consecutive worker-stamped responses satisfy `isHit`.
229 const pollForLayers = (
230 url: string,
231 isHit: (
232 previous: { gateway: string; public: string },
233 current: { gateway: string; public: string },
234 ) => boolean,
235 ) => {
236 let previous: { gateway: string; public: string } | undefined;
237 return fetchCached(url).pipe(
238 Effect.map((res) => {
239 const current = res.status === 200 ? parseLayers(res.body) : undefined;
240 const hit = current !== undefined && previous !== undefined && isHit(previous, current);
241 if (current) previous = current;
242 return { ...res, hit };
243 }),
244 Effect.repeat({
245 schedule: Schedule.spaced("2 seconds"),
246 until: (res) => res.hit,
247 times: 20,
248 }),
249 );
250 };
251
252 // The `exports` map Cloudflare recorded on the version serving traffic.
253 const liveExports = (scriptName: string) =>
254 Effect.gen(function* () {
255 const { accountId } = yield* yield* CloudflareEnvironment;
256 const { deployments } = yield* workers.listScriptDeployments({ accountId, scriptName });
257 const versionId = deployments[0]!.versions[0]!.versionId;
258 const version = yield* workers.getScriptVersion({ accountId, scriptName, versionId });
259 return version.resources?.scriptRuntime?.exports ?? {};
260 });
261
262 test.provider(
263 "entrypoints configures Workers Cache per entrypoint",
264 (stack) =>
265 Effect.gen(function* () {
266 yield* stack.destroy();
267
268 // Uncached gateway in front of a cached `Public` entrypoint, with no
269 // Worker-wide `cache` at all.
270 const { worker } = yield* stack.deploy(
271 Effect.gen(function* () {
272 return {
273 worker: yield* Cloudflare.Worker("EntrypointCacheWorker", {
274 script: entrypointScript,
275 entrypoints: {
276 default: { cache: { enabled: false } },
277 Public: { cache: { enabled: true } },
278 },
279 }),
280 };
281 }),
282 );
283 expect(worker.url).toBeDefined();
284 const exports = yield* liveExports(worker.workerName);
285 expect(exports.default).toMatchObject({ type: "worker", cache: { enabled: false } });
286 expect(exports.Public).toMatchObject({ type: "worker", cache: { enabled: true } });
287
288 yield* expectUrlContains(worker.url!, "gw:", {
289 label: "entrypoint cache worker propagation",
290 });
291
292 const publicHit = yield* pollForLayers(
293 `${worker.url}/gateway`,
294 (previous, current) =>
295 current.public === previous.public && current.gateway !== previous.gateway,
296 );
297 expect(publicHit.hit).toBe(true);
298
299 // Flip it: cache the gateway, not `Public`. The new version starts
300 // cold; a fully repeated body proves the default export is cached.
301 const flipped = yield* stack.deploy(
302 Effect.gen(function* () {
303 return {
304 worker: yield* Cloudflare.Worker("EntrypointCacheWorker", {
305 script: entrypointScript,
306 entrypoints: {
307 default: { cache: { enabled: true } },
308 Public: { cache: { enabled: false } },
309 },
310 }),
311 };
312 }),
313 );
314 expect(flipped.worker.workerName).toEqual(worker.workerName);
315 const flippedExports = yield* liveExports(worker.workerName);
316 expect(flippedExports.default).toMatchObject({ type: "worker", cache: { enabled: true } });
317 expect(flippedExports.Public).toMatchObject({ type: "worker", cache: { enabled: false } });
318
319 const gatewayHit = yield* pollForLayers(
320 `${worker.url}/gateway`,
321 (previous, current) => current.gateway === previous.gateway,
322 );
323 expect(gatewayHit.hit).toBe(true);
324
325 yield* stack.destroy();
326 }).pipe(logLevel),
327 {
328 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
329 timeout: 240_000,
330 },
331 );
332
333 // The `exports` map Cloudflare recorded on one version.
334 const versionExports = (scriptName: string, versionId: string) =>
335 Effect.gen(function* () {
336 const { accountId } = yield* yield* CloudflareEnvironment;
337 const version = yield* workers.getScriptVersion({ accountId, scriptName, versionId });
338 return version.resources?.scriptRuntime?.exports ?? {};
339 });
340
341 // Unlike Durable Object exports, entrypoint cache overrides may differ
342 // between the versions of a gradual rollout: each version carries its own.
343 test.provider(
344 "a gradual rollout may change an entrypoint's cache setting",
345 (stack) =>
346 Effect.gen(function* () {
347 yield* stack.destroy();
348
349 const program = (publicCache: boolean, marker: string, traffic?: number) =>
350 Cloudflare.Worker("EntrypointGradualWorker", {
351 script: `${entrypointScript}\n// ${marker}\n`,
352 entrypoints: { Public: { cache: { enabled: publicCache } } },
353 ...(traffic !== undefined ? { version: { traffic } } : {}),
354 });
355
356 const base = yield* stack.deploy(program(true, "v1"));
357 const gradual = yield* stack.deploy(program(false, "v2", 50));
358 expect(gradual.versionId).toBeDefined();
359
360 const { accountId } = yield* yield* CloudflareEnvironment;
361 const { deployments } = yield* workers.listScriptDeployments({
362 accountId,
363 scriptName: base.workerName,
364 });
365 const split = deployments[0]?.versions ?? [];
366 expect(split.map((v) => v.percentage)).toEqual([50, 50]);
367 const previous = split.find((v) => v.versionId !== gradual.versionId)!;
368 expect(split.some((v) => v.versionId === gradual.versionId)).toBe(true);
369
370 expect((yield* versionExports(base.workerName, previous.versionId)).Public).toMatchObject({
371 type: "worker",
372 cache: { enabled: true },
373 });
374 expect((yield* versionExports(base.workerName, gradual.versionId!)).Public).toMatchObject({
375 type: "worker",
376 cache: { enabled: false },
377 });
378
379 yield* stack.destroy();
380 }).pipe(logLevel),
381 {
382 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
383 timeout: 240_000,
384 },
385 );
386
387 // Previews upload their own `exports` map: the gateway/`Public` split
388 // applies on the Preview URL, independent of the parent's settings.
389 test.provider(
390 "a preview applies its own entrypoint cache settings",
391 (stack) =>
392 Effect.gen(function* () {
393 yield* stack.destroy();
394
395 const { preview } = yield* stack.deploy(
396 Effect.gen(function* () {
397 const parent = yield* Cloudflare.Worker("EntrypointCacheParent", {
398 script: cachedScript,
399 });
400 const preview = yield* Cloudflare.Worker("EntrypointCachePreview", {
401 script: entrypointScript,
402 preview: { of: parent },
403 entrypoints: {
404 default: { cache: { enabled: false } },
405 Public: { cache: { enabled: true } },
406 },
407 });
408 return { parent, preview };
409 }),
410 );
411 expect(preview.url).toBeDefined();
412
413 yield* expectUrlContains(preview.url!, "gw:", {
414 label: "entrypoint cache preview propagation",
415 });
416
417 const publicHit = yield* pollForLayers(
418 `${preview.url}/gateway`,
419 (previous, current) =>
420 current.public === previous.public && current.gateway !== previous.gateway,
421 );
422 expect(publicHit.hit).toBe(true);
423
424 yield* stack.destroy();
425 }).pipe(logLevel),
426 {
427 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
428 timeout: 240_000,
429 },
430 );
431
432 // Cloudflare rejects an `exports` cache override naming an export the script
433 // doesn't have (code 10375); the deploy fails with that typed tag.
434 test.provider(
435 "entrypoints naming an unknown export fails with UnknownWorkerEntrypoint",
436 (stack) =>
437 Effect.gen(function* () {
438 yield* stack.destroy();
439
440 const error = yield* stack
441 .deploy(
442 Cloudflare.Worker("UnknownEntrypointWorker", {
443 script: cachedScript,
444 entrypoints: { Missing: { cache: { enabled: true } } },
445 }),
446 )
447 .pipe(Effect.flip);
448 expect(error).toMatchObject({ _tag: "UnknownWorkerEntrypoint", code: 10375 });
449
450 yield* stack.destroy();
451 }).pipe(logLevel),
452 {
453 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
454 timeout: 120_000,
455 },
456 );