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

main
ts 346 lines 12 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 emailSending from "@distilled.cloud/cloudflare/email-sending";
7 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
8 import * as Provider from "alchemy/Provider";
9 import * as Cause from "effect/Cause";
10 import * as Effect from "effect/Effect";
11 import * as Option from "effect/Option";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14 import * as Stream from "effect/Stream";
15 import { testName } from "../../names.ts";
16 import { emailRoutingScoped } from "./scope.ts";
17
18 const { test } = Test.make({ providers: Cloudflare.providers() });
19
20 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
21
22 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
23
24 // Deterministic per-test subdomain names. Each test owns a disjoint
25 // subdomain so reruns and parallel runs never collide, and the same name is
26 // reused on every run (never derive physical names from Date.now()/random).
27 const NAME_DEFAULT = `${testName("alchemy-sendsub-default")}.${zoneName}`;
28 const NAME_REPLACE_A = `${testName("alchemy-sendsub-replace-a")}.${zoneName}`;
29 const NAME_REPLACE_B = `${testName("alchemy-sendsub-replace-b")}.${zoneName}`;
30 const NAME_ADOPT = `${testName("alchemy-sendsub-adopt")}.${zoneName}`;
31 const NAME_LIST = `${testName("alchemy-sendsub-list")}.${zoneName}`;
32 const NAME_PREVIEW = `${testName("alchemy-sendsub-preview")}.${zoneName}`;
33
34 const resolveZoneId = Effect.gen(function* () {
35 const { accountId } = yield* yield* CloudflareEnvironment;
36 const zone = yield* findZoneByName({ accountId, name: zoneName });
37 if (!zone) {
38 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
39 }
40 return zone.id;
41 });
42
43 // The scoped API token the test harness mints propagates eventually-
44 // consistently across Cloudflare's edge — a fresh token intermittently 403s
45 // with "Unable to authenticate request". Ride out the blips on the test's
46 // own out-of-band verification calls by retrying the typed `Forbidden`
47 // error (part of each email-sending operation's error union via distilled
48 // patches).
49 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
50
51 const findByName = (zoneId: string, name: string) =>
52 emailSending.listSubdomains.items({ zoneId }).pipe(
53 Stream.filter((s) => s.name === name),
54 Stream.runHead,
55 Effect.map(Option.getOrUndefined),
56 Effect.retry({
57 while: (e) => e._tag === "Forbidden",
58 schedule: forbiddenRetrySchedule,
59 times: 8,
60 }),
61 );
62
63 const getSubdomain = (zoneId: string, subdomainId: string) =>
64 emailSending.getSubdomain({ zoneId, subdomainId }).pipe(
65 Effect.retry({
66 while: (e) => e._tag === "Forbidden",
67 schedule: forbiddenRetrySchedule,
68 times: 8,
69 }),
70 );
71
72 // Delete any subdomain matching `name` — used to purge leftovers from
73 // interrupted runs so tests start from a clean slate.
74 const purgeSubdomain = (zoneId: string, name: string) =>
75 findByName(zoneId, name).pipe(
76 Effect.flatMap((existing) =>
77 existing
78 ? emailSending.deleteSubdomain({ zoneId, subdomainId: existing.tag }).pipe(
79 Effect.catchTag("SendingSubdomainNotFound", () => Effect.void),
80 Effect.retry({
81 while: (e) => e._tag === "Forbidden",
82 schedule: forbiddenRetrySchedule,
83 times: 8,
84 }),
85 )
86 : Effect.void,
87 ),
88 );
89
90 test.provider.skipIf(!emailRoutingScoped)(
91 "create and destroy a sending subdomain",
92 (stack) =>
93 Effect.gen(function* () {
94 const zoneId = yield* resolveZoneId;
95
96 yield* stack.destroy();
97 yield* purgeSubdomain(zoneId, NAME_DEFAULT);
98
99 const sending = yield* stack.deploy(
100 Effect.gen(function* () {
101 return yield* Cloudflare.Email.SendingSubdomain("Sending", {
102 zoneId,
103 name: NAME_DEFAULT,
104 });
105 }),
106 );
107
108 expect(sending.subdomainId).toBeDefined();
109 expect(sending.zoneId).toEqual(zoneId);
110 expect(sending.name).toEqual(NAME_DEFAULT);
111 // CF-hosted zone — DNS records are auto-created and validate
112 // immediately; the reconciler polls briefly for `enabled`.
113 expect(sending.enabled).toEqual(true);
114 expect(sending.dkimSelector).toBeDefined();
115 expect(sending.returnPathDomain).toContain(NAME_DEFAULT);
116
117 // Out-of-band verification against the live API.
118 const live = yield* getSubdomain(zoneId, sending.subdomainId);
119 expect(live.tag).toEqual(sending.subdomainId);
120 expect(live.name).toEqual(NAME_DEFAULT);
121
122 yield* stack.destroy();
123
124 // Gone after destroy — the typed not-found is the success signal.
125 const gone = yield* getSubdomain(zoneId, sending.subdomainId).pipe(
126 Effect.map(() => "still-there" as const),
127 Effect.catchTag("SendingSubdomainNotFound", () => Effect.succeed("gone" as const)),
128 );
129 expect(gone).toEqual("gone");
130
131 // Destroy again — delete is idempotent.
132 yield* stack.destroy();
133 }).pipe(logLevel),
134 {
135 tags: ["provider:cloudflare", "provider:cloudflare:email", "provider:cloudflare:zone", "live"],
136 },
137 );
138
139 test.provider.skipIf(!emailRoutingScoped)(
140 "previewEnabled is set on create and updated in place",
141 (stack) =>
142 Effect.gen(function* () {
143 const zoneId = yield* resolveZoneId;
144
145 yield* stack.destroy();
146 yield* purgeSubdomain(zoneId, NAME_PREVIEW);
147
148 const deploy = (previewEnabled: boolean) =>
149 stack.deploy(
150 Effect.gen(function* () {
151 return yield* Cloudflare.Email.SendingSubdomain("PreviewSending", {
152 zoneId,
153 name: NAME_PREVIEW,
154 previewEnabled,
155 });
156 }),
157 );
158
159 const off = yield* deploy(false);
160 expect(off.previewEnabled).toEqual(false);
161 expect((yield* getSubdomain(zoneId, off.subdomainId)).previewEnabled).toEqual(false);
162
163 const on = yield* deploy(true);
164 expect(on.subdomainId).toEqual(off.subdomainId);
165 expect(on.previewEnabled).toEqual(true);
166 expect((yield* getSubdomain(zoneId, on.subdomainId)).previewEnabled).toEqual(true);
167
168 yield* stack.destroy();
169 }).pipe(logLevel),
170 {
171 tags: ["provider:cloudflare", "provider:cloudflare:email", "provider:cloudflare:zone", "live"],
172 },
173 );
174
175 test.provider.skipIf(!emailRoutingScoped)(
176 "changing the name triggers replacement",
177 (stack) =>
178 Effect.gen(function* () {
179 const zoneId = yield* resolveZoneId;
180
181 yield* stack.destroy();
182 yield* purgeSubdomain(zoneId, NAME_REPLACE_A);
183 yield* purgeSubdomain(zoneId, NAME_REPLACE_B);
184
185 const initial = yield* stack.deploy(
186 Effect.gen(function* () {
187 return yield* Cloudflare.Email.SendingSubdomain("ReplaceSending", {
188 zoneId,
189 name: NAME_REPLACE_A,
190 });
191 }),
192 );
193
194 expect(initial.name).toEqual(NAME_REPLACE_A);
195
196 const replaced = yield* stack.deploy(
197 Effect.gen(function* () {
198 return yield* Cloudflare.Email.SendingSubdomain("ReplaceSending", {
199 zoneId,
200 name: NAME_REPLACE_B,
201 });
202 }),
203 );
204
205 // The name is the subdomain's identity — a new physical resource.
206 expect(replaced.subdomainId).not.toEqual(initial.subdomainId);
207 expect(replaced.name).toEqual(NAME_REPLACE_B);
208
209 // The old subdomain was deleted as part of the replacement.
210 const old = yield* findByName(zoneId, NAME_REPLACE_A);
211 expect(old).toBeUndefined();
212
213 const live = yield* findByName(zoneId, NAME_REPLACE_B);
214 expect(live?.tag).toEqual(replaced.subdomainId);
215
216 yield* stack.destroy();
217
218 const gone = yield* findByName(zoneId, NAME_REPLACE_B);
219 expect(gone).toBeUndefined();
220 }).pipe(logLevel),
221 {
222 tags: ["provider:cloudflare", "provider:cloudflare:email", "provider:cloudflare:zone", "live"],
223 },
224 );
225
226 test.provider.skipIf(!emailRoutingScoped)(
227 "adoption — existing subdomain errors without adopt, takes over with adopt(true)",
228 (stack) =>
229 Effect.gen(function* () {
230 const zoneId = yield* resolveZoneId;
231
232 yield* stack.destroy();
233 yield* purgeSubdomain(zoneId, NAME_ADOPT);
234
235 // Create the subdomain out-of-band so the stack has no state of its
236 // own for it — exactly the "already exists" scenario.
237 const pre = yield* emailSending.createSubdomain({ zoneId, name: NAME_ADOPT }).pipe(
238 Effect.retry({
239 while: (e) => e._tag === "Forbidden",
240 schedule: forbiddenRetrySchedule,
241 times: 8,
242 }),
243 );
244 expect(pre.tag).toBeDefined();
245
246 // Without `adopt`: sending subdomains carry no ownership markers, so
247 // the engine cannot prove we created it and refuses to take it over.
248 const error = yield* stack
249 .deploy(
250 Effect.gen(function* () {
251 return yield* Cloudflare.Email.SendingSubdomain("AdoptSending", {
252 zoneId,
253 name: NAME_ADOPT,
254 });
255 }),
256 )
257 .pipe(
258 Effect.as(undefined),
259 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
260 );
261 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
262
263 // With adopt(true): the engine takes over the existing subdomain
264 // instead of failing.
265 const adopted = yield* stack.deploy(
266 Effect.gen(function* () {
267 return yield* Cloudflare.Email.SendingSubdomain("AdoptSending", {
268 zoneId,
269 name: NAME_ADOPT,
270 }).pipe(adopt(true));
271 }),
272 );
273 expect(adopted.subdomainId).toEqual(pre.tag);
274 expect(adopted.name).toEqual(NAME_ADOPT);
275
276 yield* stack.destroy();
277
278 const gone = yield* findByName(zoneId, NAME_ADOPT);
279 expect(gone).toBeUndefined();
280 }).pipe(logLevel),
281 {
282 tags: ["provider:cloudflare", "provider:cloudflare:email", "provider:cloudflare:zone", "live"],
283 timeout: 180_000,
284 },
285 );
286
287 test.provider.skipIf(!emailRoutingScoped)(
288 "list enumerates the deployed sending subdomain",
289 (stack) =>
290 Effect.gen(function* () {
291 const zoneId = yield* resolveZoneId;
292
293 yield* stack.destroy();
294 yield* purgeSubdomain(zoneId, NAME_LIST);
295
296 const sending = yield* stack.deploy(
297 Effect.gen(function* () {
298 return yield* Cloudflare.Email.SendingSubdomain("ListSending", {
299 zoneId,
300 name: NAME_LIST,
301 });
302 }),
303 );
304
305 const provider = yield* Provider.findProvider(Cloudflare.Email.SendingSubdomain);
306 // The scoped token may still be propagating across the edge; ride out
307 // the typed Forbidden blips on the enumeration itself.
308 const all = yield* provider.list().pipe(
309 Effect.retry({
310 while: (e) => e._tag === "Forbidden",
311 schedule: forbiddenRetrySchedule,
312 times: 8,
313 }),
314 );
315
316 // The deployed subdomain is present, with the full read Attributes shape.
317 const found = all.find((s) => s.subdomainId === sending.subdomainId);
318 expect(found).toBeDefined();
319 expect(found?.zoneId).toEqual(zoneId);
320 expect(found?.name).toEqual(NAME_LIST);
321
322 yield* stack.destroy();
323
324 const gone = yield* findByName(zoneId, NAME_LIST);
325 expect(gone).toBeUndefined();
326 }).pipe(logLevel),
327 {
328 tags: ["provider:cloudflare", "provider:cloudflare:email", "provider:cloudflare:zone", "live"],
329 timeout: 180_000,
330 },
331 );
332
333 /**
334 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
335 * whether the engine raised it as a typed failure or a defect.
336 */
337 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
338 cause.reasons
339 .map((reason) =>
340 Cause.isFailReason(reason)
341 ? reason.error
342 : Cause.isDieReason(reason)
343 ? reason.defect
344 : undefined,
345 )
346 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);