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

main
ts 389 lines 14.6 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 rulesets from "@distilled.cloud/cloudflare/rulesets";
7 import * as workers from "@distilled.cloud/cloudflare/workers";
8 import * as Drift from "alchemy/Drift";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as pathe from "pathe";
13 import { stageSuffix } from "../../names.ts";
14 import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
15
16 const { test } = Test.make({ providers: Cloudflare.providers() });
17
18 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
19
20 const main = pathe.resolve(import.meta.dirname, "fixtures/worker.ts");
21
22 const zoneName =
23 process.env.CLOUDFLARE_TEST_WORKER_DOMAIN_ZONE_NAME ??
24 process.env.CLOUDFLARE_TEST_R2_DOMAIN_ZONE_NAME ??
25 "alchemy-test-2.us";
26
27 // Deterministic per-run hostnames on the standing test zone. Each rerun
28 // reuses the same hostnames (never derive names from Date.now()).
29 const domainSuffix = `alchemy-worker-domain-${stageSuffix()}`;
30
31 const DECLARED_HOSTNAME = `wd1-${domainSuffix}.${zoneName}`;
32 const OUT_OF_BAND_HOSTNAME = `wd2-${domainSuffix}.${zoneName}`;
33 const REDIRECT_NAME_A = `wd3-${domainSuffix}.${zoneName}`;
34 const REDIRECT_NAME_B = `wd4-${domainSuffix}.${zoneName}`;
35 const REDIRECT_FROM = `wd5-${domainSuffix}.${zoneName}`;
36 const ZONED_HOSTNAME = `wd6-${domainSuffix}.${zoneName}`;
37 const ZONED_DRIFT_HOSTNAME = `wd7-${domainSuffix}.${zoneName}`;
38
39 const resolveZoneId = Effect.gen(function* () {
40 const { accountId } = yield* yield* CloudflareEnvironment;
41 const zone = yield* findZoneByName({ accountId, name: zoneName });
42 if (!zone) {
43 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
44 }
45 return zone.id;
46 });
47
48 // Retry rate-limit blips on the tests' own out-of-band verification calls.
49 const transientRetrySchedule = Schedule.exponential("500 millis");
50
51 const listAttachments = (hostname: string) =>
52 Effect.gen(function* () {
53 const { accountId } = yield* yield* CloudflareEnvironment;
54 return yield* workers.listDomains({ accountId, hostname }).pipe(
55 Effect.map((r) => (r.result ?? []).filter((d) => d.hostname === hostname)),
56 Effect.retry({
57 while: (e) => e._tag === "TooManyRequests",
58 schedule: transientRetrySchedule,
59 times: 8,
60 }),
61 );
62 });
63
64 const findAttachment = (hostname: string) =>
65 listAttachments(hostname).pipe(Effect.map((ds) => ds[0]));
66
67 // Detach every worker-domain attachment for the given hostnames — purge
68 // leftovers from interrupted runs so tests start from a clean slate.
69 const purgeDomains = (...hostnames: string[]) =>
70 Effect.gen(function* () {
71 const { accountId } = yield* yield* CloudflareEnvironment;
72 yield* Effect.forEach(hostnames, (hostname) =>
73 listAttachments(hostname).pipe(
74 Effect.flatMap(
75 Effect.forEach((d) =>
76 d.id
77 ? workers
78 .deleteDomain({ accountId, domainId: d.id })
79 .pipe(Effect.catch(() => Effect.void))
80 : Effect.void,
81 ),
82 ),
83 ),
84 );
85 });
86
87 // #942: an omitted `domain` prop must leave live attachments alone —
88 // including hostnames attached outside Alchemy — while `domain: null` is the
89 // explicit detach-all. The gate keys on declared intent (props), never on
90 // domains persisted in state, so state written by older providers that
91 // observed listDomains unconditionally cannot re-arm the destructive path.
92 test.provider(
93 "omitted domain preserves live attachments; null detaches all",
94 (stack) =>
95 Effect.gen(function* () {
96 const { accountId } = yield* yield* CloudflareEnvironment;
97 const zoneId = yield* resolveZoneId;
98
99 yield* stack.destroy();
100 yield* purgeDomains(DECLARED_HOSTNAME, OUT_OF_BAND_HOSTNAME);
101
102 let workerName: string | undefined;
103
104 yield* Effect.gen(function* () {
105 // Create — one declared custom domain.
106 const worker = yield* stack.deploy(
107 Effect.gen(function* () {
108 return yield* Cloudflare.Worker("DomainWorker", {
109 main,
110 workersDev: false,
111 compatibility: { date: "2024-01-01" },
112 domain: DECLARED_HOSTNAME,
113 });
114 }),
115 );
116 workerName = worker.workerName;
117
118 expect(worker.urls).toEqual([`https://${DECLARED_HOSTNAME}`]);
119 expect(worker.domain).toEqual({
120 name: DECLARED_HOSTNAME,
121 aliases: [],
122 redirects: [],
123 });
124 const declared = yield* findAttachment(DECLARED_HOSTNAME);
125 expect(declared?.service).toEqual(worker.workerName);
126
127 // Attach a second hostname to the same script out-of-band — the
128 // reconciler never recorded it, so it is unmanaged drift.
129 yield* workers
130 .putDomain({
131 accountId,
132 hostname: OUT_OF_BAND_HOSTNAME,
133 service: worker.workerName,
134 zoneId,
135 })
136 .pipe(
137 // Same eventual-consistency window as the provider's own
138 // attachDomain: PUT domains right after putScript can race the
139 // script registry and return WorkerNotFound.
140 Effect.retry({
141 while: (e): boolean => e._tag === "WorkerNotFound" || e._tag === "TooManyRequests",
142 schedule: transientRetrySchedule,
143 times: 8,
144 }),
145 );
146
147 // Update with `domain` omitted (compat date bump forces the
148 // update): both attachments must survive — omission unmanages the
149 // surface, it does not mean "detach everything".
150 const unmanaged = yield* stack.deploy(
151 Effect.gen(function* () {
152 return yield* Cloudflare.Worker("DomainWorker", {
153 main,
154 workersDev: false,
155 compatibility: { date: "2024-01-02" },
156 });
157 }),
158 );
159
160 expect((yield* findAttachment(DECLARED_HOSTNAME))?.service).toEqual(worker.workerName);
161 expect((yield* findAttachment(OUT_OF_BAND_HOSTNAME))?.service).toEqual(worker.workerName);
162 // Previously-observed custom domains carry forward in state so
163 // subsequent reads keep observing them.
164 expect(unmanaged.domain?.name).toEqual(DECLARED_HOSTNAME);
165 expect(unmanaged.urls).toContain(`https://${DECLARED_HOSTNAME}`);
166
167 // The unmanaged surface must also converge: the custom domains
168 // carried forward in state must not diff dirty against the omitted
169 // `domain` prop — an identical program plans as a noop.
170 const settled = yield* stack.plan(
171 Effect.gen(function* () {
172 return yield* Cloudflare.Worker("DomainWorker", {
173 main,
174 workersDev: false,
175 compatibility: { date: "2024-01-02" },
176 });
177 }),
178 );
179 const settledAction = (Object.values(settled.resources) as any[]).find(
180 (node: any) => node.resource.LogicalId === "DomainWorker",
181 )?.action;
182 expect(settledAction).toBe("noop");
183
184 // `domain: null` is the explicit detach-all.
185 const detached = yield* stack.deploy(
186 Effect.gen(function* () {
187 return yield* Cloudflare.Worker("DomainWorker", {
188 main,
189 workersDev: false,
190 compatibility: { date: "2024-01-02" },
191 domain: null,
192 });
193 }),
194 );
195
196 expect(detached.domain).toBeUndefined();
197 expect(detached.urls).toHaveLength(0);
198 expect(yield* findAttachment(DECLARED_HOSTNAME)).toBeUndefined();
199 expect(yield* findAttachment(OUT_OF_BAND_HOSTNAME)).toBeUndefined();
200 }).pipe(
201 Effect.ensuring(
202 Effect.gen(function* () {
203 yield* stack.destroy().pipe(Effect.ignore);
204 yield* purgeDomains(DECLARED_HOSTNAME, OUT_OF_BAND_HOSTNAME).pipe(Effect.ignore);
205 if (workerName) {
206 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
207 }
208 }),
209 ),
210 );
211 }).pipe(logLevel),
212 {
213 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
214 timeout: 300_000,
215 },
216 );
217
218 test.provider(
219 "a domain with zoneName does not drift until a hostname is attached out-of-band",
220 (stack) =>
221 Effect.gen(function* () {
222 const { accountId } = yield* yield* CloudflareEnvironment;
223 const zoneId = yield* resolveZoneId;
224 const detectDrift = () => Drift.detect(stack).pipe(Effect.provide(stack.state));
225
226 yield* stack.destroy();
227 yield* purgeDomains(ZONED_HOSTNAME, ZONED_DRIFT_HOSTNAME);
228
229 let workerName: string | undefined;
230
231 yield* Effect.gen(function* () {
232 const worker = yield* stack.deploy(
233 Effect.gen(function* () {
234 return yield* Cloudflare.Worker("ZonedDomainWorker", {
235 main,
236 workersDev: false,
237 compatibility: { date: "2024-01-01" },
238 domain: { name: ZONED_HOSTNAME, zoneName },
239 });
240 }),
241 );
242 workerName = worker.workerName;
243 expect(worker.domain).toEqual({
244 name: ZONED_HOSTNAME,
245 aliases: [],
246 redirects: [],
247 zone: zoneName,
248 });
249
250 // `read` keeps the resolved zone while the declared hostname is
251 // attached, so an unchanged Worker is not reported as drifted.
252 const unchanged = yield* detectDrift();
253 expect(unchanged.resources.ZonedDomainWorker?.action).toBe("unchanged");
254
255 // A hostname attached outside Alchemy is still real drift.
256 yield* workers
257 .putDomain({
258 accountId,
259 hostname: ZONED_DRIFT_HOSTNAME,
260 service: worker.workerName,
261 zoneId,
262 })
263 .pipe(
264 Effect.retry({
265 while: (e): boolean => e._tag === "WorkerNotFound" || e._tag === "TooManyRequests",
266 schedule: transientRetrySchedule,
267 times: 8,
268 }),
269 );
270 const changed = yield* detectDrift();
271 expect(changed.resources.ZonedDomainWorker?.action).toBe("drifted");
272 expect(changed.resources.ZonedDomainWorker?.attr.domain).toEqual({
273 name: ZONED_HOSTNAME,
274 aliases: [ZONED_DRIFT_HOSTNAME],
275 redirects: [],
276 zone: zoneName,
277 });
278 }).pipe(
279 Effect.ensuring(
280 Effect.gen(function* () {
281 yield* stack.destroy().pipe(Effect.ignore);
282 yield* purgeDomains(ZONED_HOSTNAME, ZONED_DRIFT_HOSTNAME).pipe(Effect.ignore);
283 if (workerName) {
284 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
285 }
286 }),
287 ),
288 );
289 }).pipe(logLevel),
290 {
291 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
292 timeout: 300_000,
293 },
294 );
295
296 /**
297 * The redirect-target expression of every redirect rule this Worker owns
298 * in the zone's dynamic-redirect phase, keyed by the redirected hostname.
299 */
300 const listRedirectTargets = Effect.fn(function* (zoneId: string, scriptName: string) {
301 const prefix = `alchemy:worker:${scriptName}:redirect:`;
302 const entrypoint = yield* rulesets
303 .getPhasForZone({ zoneId, rulesetPhase: "http_request_dynamic_redirect" })
304 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.succeed(undefined)));
305 return Object.fromEntries(
306 (entrypoint?.rules ?? []).flatMap((rule) => {
307 const description = rule.description ?? "";
308 if (!description.startsWith(prefix)) return [];
309 const fromValue =
310 "actionParameters" in rule
311 ? (
312 rule.actionParameters as
313 | { fromValue?: { targetUrl?: { expression?: unknown } | null } | null }
314 | null
315 | undefined
316 )?.fromValue
317 : undefined;
318 return [[description.slice(prefix.length), fromValue?.targetUrl?.expression]];
319 }),
320 );
321 });
322
323 // #2759: renaming the canonical `name` keeps every redirect rule's
324 // description and match expression, so a convergence check on those alone
325 // skipped the PUT and the redirects kept pointing at the old host.
326 test.provider(
327 "changing the canonical name retargets domain redirects",
328 (stack) =>
329 Effect.gen(function* () {
330 const { accountId } = yield* yield* CloudflareEnvironment;
331 const zoneId = yield* resolveZoneId;
332
333 yield* stack.destroy();
334 yield* purgeDomains(REDIRECT_NAME_A, REDIRECT_NAME_B, REDIRECT_FROM);
335
336 let workerName: string | undefined;
337
338 const deploy = (name: string) =>
339 stack.deploy(
340 Effect.gen(function* () {
341 return yield* Cloudflare.Worker("RedirectWorker", {
342 main,
343 workersDev: false,
344 compatibility: { date: "2024-01-01" },
345 domain: { name, redirects: [REDIRECT_FROM] },
346 });
347 }),
348 );
349
350 yield* Effect.gen(function* () {
351 const worker = yield* deploy(REDIRECT_NAME_A);
352 workerName = worker.workerName;
353 expect(worker.domain).toEqual({
354 name: REDIRECT_NAME_A,
355 aliases: [],
356 redirects: [REDIRECT_FROM],
357 });
358 expect(yield* listRedirectTargets(zoneId, worker.workerName)).toEqual({
359 [REDIRECT_FROM]: `concat("https://${REDIRECT_NAME_A}", http.request.uri.path)`,
360 });
361
362 // Same redirect hostname, new canonical name: the rule must follow.
363 const renamed = yield* deploy(REDIRECT_NAME_B);
364 expect(renamed.domain?.name).toEqual(REDIRECT_NAME_B);
365 expect(yield* listRedirectTargets(zoneId, worker.workerName)).toEqual({
366 [REDIRECT_FROM]: `concat("https://${REDIRECT_NAME_B}", http.request.uri.path)`,
367 });
368
369 yield* stack.destroy();
370 expect(yield* listRedirectTargets(zoneId, worker.workerName)).toEqual({});
371 }).pipe(
372 Effect.ensuring(
373 Effect.gen(function* () {
374 yield* stack.destroy().pipe(Effect.ignore);
375 yield* purgeDomains(REDIRECT_NAME_A, REDIRECT_NAME_B, REDIRECT_FROM).pipe(
376 Effect.ignore,
377 );
378 if (workerName) {
379 yield* waitForWorkerToBeDeleted(workerName, accountId).pipe(Effect.ignore);
380 }
381 }),
382 ),
383 );
384 }).pipe(logLevel),
385 {
386 tags: ["provider:cloudflare", "provider:cloudflare:worker", "provider:cloudflare:zone", "live"],
387 timeout: 300_000,
388 },
389 );