1import * as Cloudflare from "@/Cloudflare/index.ts";
2import * as Test from "@/Test/Alchemy";
3import { expect } from "alchemy-test";
4import * as Data from "effect/Data";
5import * as Effect from "effect/Effect";
6import { MinimumLogLevel } from "effect/References";
7import * as Schedule from "effect/Schedule";
8import * as HttpClient from "effect/http/HttpClient";
9import * as pathe from "pathe";
10
11const { test } = Test.make({
12 providers: Cloudflare.providers(),
13 dev: true,
14});
15
16const logLevel = Effect.provideService(
17 MinimumLogLevel,
18 process.env.DEBUG ? "Debug" : "Info",
19);
20
21class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
22 status: number;
23}> {}
24
25const getJsonReady = (url: string) =>
26 Effect.gen(function* () {
27 const client = yield* HttpClient.HttpClient;
28 const res = yield* client.get(url).pipe(
29 Effect.flatMap((res) =>
30 res.status === 200
31 ? Effect.succeed(res)
32 : Effect.fail(new WorkerNotReady({ status: res.status })),
33 ),
34 Effect.retry({
35 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
36 // Cap the backoff: an uncapped exponential over 10 recurs sums to
37 // ~8.5 minutes and turns a persistent non-200 into an apparent hang.
38 schedule: Schedule.max([
39 Schedule.min([
40 Schedule.exponential("500 millis"),
41 Schedule.spaced("2 seconds"),
42 ]),
43 Schedule.recurs(10),
44 ]),
45 }),
46 );
47 return yield* res.json;
48 }).pipe(Effect.orDie);
49
50/**
51 * The local runtime ships an always-on Cache API simulator
52 * (`caches.default` persisted under `.alchemy/local/cache`) and builds
53 * `request.cf` from a fallback blob in the entry middleware. Neither needs
54 * any alchemy-side wiring — this pins that both actually work for a worker
55 * deployed by the local provider.
56 */
57test.provider(
58 "Cache API and request.cf work under the local runtime",
59 (stack) =>
60 Effect.gen(function* () {
61 yield* stack.destroy();
62
63 const deployed = yield* stack.deploy(
64 Effect.gen(function* () {
65 const worker = yield* Cloudflare.Worker("cache-cf-worker", {
66 main: pathe.resolve(
67 import.meta.dirname,
68 "fixtures/cache-cf/worker.ts",
69 ),
70 });
71 return { worker };
72 }),
73 );
74 const url = deployed.worker.url!;
75
76 // The local provider serves from the dev proxy — proof no cloud call
77 // ran.
78 expect(url).toMatch(/^http:\/\/localhost:\d+$/);
79
80 // request.cf: the middleware injects Miniflare's static fallback blob,
81 // so `colo`/`country` are present without any configuration.
82 const cf = (yield* getJsonReady(`${url}/cf`)) as {
83 colo: string | null;
84 country: string | null;
85 clientAcceptEncoding: string | null;
86 };
87 expect(cf.colo).toBeTruthy();
88 expect(cf.country).toBeTruthy();
89
90 // Cache API: first request misses and populates, second hits. The
91 // simulator's storage persists across runs, so use a per-run key.
92 const cacheKey = crypto.randomUUID();
93 const first = (yield* getJsonReady(`${url}/cache?key=${cacheKey}`)) as {
94 hit: boolean;
95 body: string;
96 };
97 expect(first.hit).toBe(false);
98 expect(first.body).toBe("cached-body");
99
100 const second = (yield* getJsonReady(`${url}/cache?key=${cacheKey}`)) as {
101 hit: boolean;
102 body: string;
103 };
104 expect(second.hit).toBe(true);
105 expect(second.body).toBe("cached-body");
106
107 yield* stack.destroy();
108 }).pipe(logLevel),
109 {
110 tags: ["provider:cloudflare", "provider:cloudflare:worker", "local"],
111 timeout: 120_000,
112 },
113);
114
115/**
116 * `dev: { cache: false }` turns every Cache API operation into a no-op
117 * (matching production workers.dev), and `dev: { cf }` overrides the
118 * `request.cf` blob served to this Worker.
119 */
120test.provider(
121 "dev.cache=false disables the Cache API and dev.cf overrides request.cf",
122 (stack) =>
123 Effect.gen(function* () {
124 yield* stack.destroy();
125
126 const deployed = yield* stack.deploy(
127 Effect.gen(function* () {
128 const worker = yield* Cloudflare.Worker("cache-off-worker", {
129 main: pathe.resolve(
130 import.meta.dirname,
131 "fixtures/cache-cf/worker.ts",
132 ),
133 dev: {
134 cache: false,
135 cf: { colo: "TST", country: "XX" },
136 },
137 });
138 return { worker };
139 }),
140 );
141 const url = deployed.worker.url!;
142
143 // The overridden blob is served verbatim.
144 const cf = (yield* getJsonReady(`${url}/cf`)) as {
145 colo: string | null;
146 country: string | null;
147 };
148 expect(cf.colo).toBe("TST");
149 expect(cf.country).toBe("XX");
150
151 // With the cache disabled, every request misses — the put is a no-op.
152 const first = (yield* getJsonReady(`${url}/cache`)) as { hit: boolean };
153 const second = (yield* getJsonReady(`${url}/cache`)) as { hit: boolean };
154 expect(first.hit).toBe(false);
155 expect(second.hit).toBe(false);
156
157 yield* stack.destroy();
158 }).pipe(logLevel),
159 {
160 tags: ["provider:cloudflare", "provider:cloudflare:worker", "local"],
161 timeout: 120_000,
162 },
163);