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

main
ts 423 lines 13.8 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 healthchecks from "@distilled.cloud/cloudflare/healthchecks";
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
17 const { test } = Test.make({ providers: Cloudflare.providers() });
18
19 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
20
21 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
22
23 // Deterministic per-test names (alphanumeric/hyphen/underscore only). The
24 // same name is reused on every run — never derive from Date.now()/random.
25 const NAME_UPDATE = testName("alchemy-healthcheck-update");
26 const NAME_UPDATE_V2 = testName("alchemy-healthcheck-update-v2");
27 const NAME_TYPE = testName("alchemy-healthcheck-type");
28 const NAME_ADOPT = testName("alchemy-healthcheck-adopt");
29 const NAME_LIST = testName("alchemy-healthcheck-list");
30
31 const resolveZoneId = Effect.gen(function* () {
32 const { accountId } = yield* yield* CloudflareEnvironment;
33 const zone = yield* findZoneByName({ accountId, name: zoneName });
34 if (!zone) {
35 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
36 }
37 return zone.id;
38 });
39
40 // The scoped API token the test harness mints propagates eventually-
41 // consistently across Cloudflare's edge — ride out 403 blips
42 // (`Forbidden`, declared in the distilled error union via patches) on the
43 // test's own out-of-band verification calls.
44 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
45
46 const getHealthcheck = (zoneId: string, healthcheckId: string) =>
47 healthchecks.getHealthcheck({ zoneId, healthcheckId }).pipe(
48 Effect.retry({
49 while: (e) => e._tag === "Forbidden",
50 schedule: forbiddenRetrySchedule,
51 times: 8,
52 }),
53 );
54
55 const findByName = (zoneId: string, name: string) =>
56 healthchecks.listHealthchecks.items({ zoneId }).pipe(
57 Stream.filter((h) => h.name === name),
58 Stream.runHead,
59 Effect.map(Option.getOrUndefined),
60 Effect.retry({
61 while: (e) => e._tag === "Forbidden",
62 schedule: forbiddenRetrySchedule,
63 times: 8,
64 }),
65 );
66
67 const expectGone = (zoneId: string, healthcheckId: string) =>
68 getHealthcheck(zoneId, healthcheckId).pipe(
69 Effect.flatMap(() => Effect.fail({ _tag: "HealthcheckNotDeleted" } as const)),
70 // A missing health check surfaces as `HealthcheckNotFound` (404) —
71 // that's the success condition here.
72 Effect.catchTag("HealthcheckNotFound", () => Effect.void),
73 Effect.retry({
74 while: (e) => e._tag === "HealthcheckNotDeleted",
75 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
76 }),
77 );
78
79 // Purge leftovers from interrupted runs so tests start from a clean
80 // slate (and the Pro-plan quota of 2 checks is never exhausted).
81 const purgeByName = (zoneId: string, name: string) =>
82 findByName(zoneId, name).pipe(
83 Effect.flatMap((found) =>
84 found?.id
85 ? healthchecks.deleteHealthcheck({ zoneId, healthcheckId: found.id }).pipe(
86 Effect.catchTag("HealthcheckNotFound", () => Effect.void),
87 Effect.retry({
88 while: (e) => e._tag === "Forbidden",
89 schedule: forbiddenRetrySchedule,
90 times: 8,
91 }),
92 )
93 : Effect.void,
94 ),
95 );
96
97 test.provider(
98 "create and delete an HTTP health check with default name",
99 (stack) =>
100 Effect.gen(function* () {
101 const zoneId = yield* resolveZoneId;
102
103 yield* stack.destroy();
104
105 const check = yield* stack.deploy(
106 Cloudflare.Healthcheck.Healthcheck("DefaultCheck", {
107 zoneId,
108 address: "www.cloudflare.com",
109 }),
110 );
111
112 expect(check.healthcheckId).toBeDefined();
113 expect(check.zoneId).toEqual(zoneId);
114 expect(check.name).toBeTruthy();
115 expect(check.address).toEqual("www.cloudflare.com");
116 expect(check.type).toEqual("HTTP");
117 expect(check.interval).toEqual(60);
118 expect(check.retries).toEqual(2);
119 expect(check.timeout).toEqual(5);
120 expect(check.suspended).toEqual(false);
121 // Status is eventually consistent — new checks start as "unknown",
122 // so only assert it is one of the documented values.
123 expect(["unknown", "healthy", "unhealthy", "suspended"]).toContain(check.status);
124
125 const live = yield* getHealthcheck(zoneId, check.healthcheckId);
126 expect(live.id).toEqual(check.healthcheckId);
127 expect(live.name).toEqual(check.name);
128 expect(live.address).toEqual("www.cloudflare.com");
129 expect(live.type).toEqual("HTTP");
130
131 yield* stack.destroy();
132
133 yield* expectGone(zoneId, check.healthcheckId);
134 }).pipe(logLevel),
135 {
136 tags: [
137 "provider:cloudflare",
138 "provider:cloudflare:healthcheck",
139 "provider:cloudflare:zone",
140 "live",
141 ],
142 },
143 );
144
145 test.provider(
146 "update mutable props in place (same id), then no-op redeploy",
147 (stack) =>
148 Effect.gen(function* () {
149 const zoneId = yield* resolveZoneId;
150
151 yield* stack.destroy();
152 yield* purgeByName(zoneId, NAME_UPDATE);
153 yield* purgeByName(zoneId, NAME_UPDATE_V2);
154
155 const initial = yield* stack.deploy(
156 Cloudflare.Healthcheck.Healthcheck("UpdateCheck", {
157 zoneId,
158 name: NAME_UPDATE,
159 address: "www.cloudflare.com",
160 type: "HTTPS",
161 interval: 60,
162 httpConfig: { path: "/", port: 443 },
163 }),
164 );
165
166 expect(initial.name).toEqual(NAME_UPDATE);
167 expect(initial.type).toEqual("HTTPS");
168 expect(initial.interval).toEqual(60);
169 expect(initial.suspended).toEqual(false);
170
171 const updated = yield* stack.deploy(
172 Cloudflare.Healthcheck.Healthcheck("UpdateCheck", {
173 zoneId,
174 name: NAME_UPDATE_V2,
175 address: "www.cloudflare.com",
176 type: "HTTPS",
177 interval: 120,
178 suspended: true,
179 description: "updated by alchemy test",
180 httpConfig: { path: "/cdn-cgi/trace", port: 443 },
181 }),
182 );
183
184 // Same health check mutated in place — not a replacement.
185 expect(updated.healthcheckId).toEqual(initial.healthcheckId);
186 expect(updated.name).toEqual(NAME_UPDATE_V2);
187 expect(updated.interval).toEqual(120);
188 expect(updated.suspended).toEqual(true);
189
190 const live = yield* getHealthcheck(zoneId, updated.healthcheckId);
191 expect(live.name).toEqual(NAME_UPDATE_V2);
192 expect(live.interval).toEqual(120);
193 expect(live.suspended).toEqual(true);
194 expect(live.description).toEqual("updated by alchemy test");
195 expect(live.httpConfig?.path).toEqual("/cdn-cgi/trace");
196
197 // Redeploying identical props is a no-op (still the same check).
198 const noop = yield* stack.deploy(
199 Cloudflare.Healthcheck.Healthcheck("UpdateCheck", {
200 zoneId,
201 name: NAME_UPDATE_V2,
202 address: "www.cloudflare.com",
203 type: "HTTPS",
204 interval: 120,
205 suspended: true,
206 description: "updated by alchemy test",
207 httpConfig: { path: "/cdn-cgi/trace", port: 443 },
208 }),
209 );
210 expect(noop.healthcheckId).toEqual(initial.healthcheckId);
211
212 yield* stack.destroy();
213
214 yield* expectGone(zoneId, initial.healthcheckId);
215 }).pipe(logLevel),
216 {
217 tags: [
218 "provider:cloudflare",
219 "provider:cloudflare:healthcheck",
220 "provider:cloudflare:zone",
221 "live",
222 ],
223 },
224 );
225
226 test.provider(
227 "changing type HTTP→TCP updates in place; delete is idempotent",
228 (stack) =>
229 Effect.gen(function* () {
230 const zoneId = yield* resolveZoneId;
231
232 yield* stack.destroy();
233 yield* purgeByName(zoneId, NAME_TYPE);
234
235 const initial = yield* stack.deploy(
236 Cloudflare.Healthcheck.Healthcheck("TypeCheck", {
237 zoneId,
238 name: NAME_TYPE,
239 address: "www.cloudflare.com",
240 type: "HTTP",
241 }),
242 );
243
244 expect(initial.type).toEqual("HTTP");
245
246 const switched = yield* stack.deploy(
247 Cloudflare.Healthcheck.Healthcheck("TypeCheck", {
248 zoneId,
249 name: NAME_TYPE,
250 address: "www.cloudflare.com",
251 type: "TCP",
252 tcpConfig: { port: 443 },
253 }),
254 );
255
256 // Type is mutable — same physical check, not a replacement.
257 expect(switched.healthcheckId).toEqual(initial.healthcheckId);
258 expect(switched.type).toEqual("TCP");
259
260 const live = yield* getHealthcheck(zoneId, switched.healthcheckId);
261 expect(live.type).toEqual("TCP");
262 expect(live.tcpConfig?.port).toEqual(443);
263
264 // Delete out-of-band, then destroy — the provider must treat the
265 // already-gone check as success (idempotent delete).
266 yield* healthchecks.deleteHealthcheck({ zoneId, healthcheckId: switched.healthcheckId }).pipe(
267 Effect.retry({
268 while: (e) => e._tag === "Forbidden",
269 schedule: forbiddenRetrySchedule,
270 times: 8,
271 }),
272 );
273
274 yield* stack.destroy();
275
276 yield* expectGone(zoneId, switched.healthcheckId);
277 }).pipe(logLevel),
278 {
279 tags: [
280 "provider:cloudflare",
281 "provider:cloudflare:healthcheck",
282 "provider:cloudflare:zone",
283 "live",
284 ],
285 },
286 );
287
288 test.provider(
289 "adoption — existing check errors without adopt, takes over with adopt(true)",
290 (stack) =>
291 Effect.gen(function* () {
292 const zoneId = yield* resolveZoneId;
293
294 yield* stack.destroy();
295 yield* purgeByName(zoneId, NAME_ADOPT);
296
297 // Create the check out-of-band so the stack has no state of its
298 // own for it — exactly the "already exists" scenario.
299 const pre = yield* healthchecks
300 .createHealthcheck({
301 zoneId,
302 name: NAME_ADOPT,
303 address: "www.cloudflare.com",
304 type: "HTTP",
305 })
306 .pipe(
307 Effect.retry({
308 while: (e) => e._tag === "Forbidden",
309 schedule: forbiddenRetrySchedule,
310 times: 8,
311 }),
312 );
313 expect(pre.id).toBeDefined();
314
315 // Without `adopt`: health checks carry no ownership markers, so the
316 // engine cannot prove we created it and refuses to take it over.
317 const error = yield* stack
318 .deploy(
319 Cloudflare.Healthcheck.Healthcheck("AdoptedCheck", {
320 zoneId,
321 name: NAME_ADOPT,
322 address: "www.cloudflare.com",
323 interval: 120,
324 }),
325 )
326 .pipe(
327 Effect.as(undefined),
328 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
329 );
330 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
331
332 // With `adopt(true)`: the engine takes over the pre-existing check
333 // (same physical id) and converges it to the desired props.
334 const adopted = yield* stack.deploy(
335 Effect.gen(function* () {
336 return yield* Cloudflare.Healthcheck.Healthcheck("AdoptedCheck", {
337 zoneId,
338 name: NAME_ADOPT,
339 address: "www.cloudflare.com",
340 interval: 120,
341 }).pipe(adopt(true));
342 }),
343 );
344
345 expect(adopted.healthcheckId).toEqual(pre.id);
346 expect(adopted.interval).toEqual(120);
347
348 const live = yield* getHealthcheck(zoneId, adopted.healthcheckId);
349 expect(live.interval).toEqual(120);
350
351 yield* stack.destroy();
352
353 const gone = yield* findByName(zoneId, NAME_ADOPT);
354 expect(gone).toBeUndefined();
355 }).pipe(logLevel),
356 {
357 tags: [
358 "provider:cloudflare",
359 "provider:cloudflare:healthcheck",
360 "provider:cloudflare:zone",
361 "live",
362 ],
363 },
364 );
365
366 test.provider(
367 "list enumerates the deployed health check across zones",
368 (stack) =>
369 Effect.gen(function* () {
370 const zoneId = yield* resolveZoneId;
371
372 yield* stack.destroy();
373 yield* purgeByName(zoneId, NAME_LIST);
374
375 const deployed = yield* stack.deploy(
376 Cloudflare.Healthcheck.Healthcheck("ListCheck", {
377 zoneId,
378 name: NAME_LIST,
379 address: "www.cloudflare.com",
380 }),
381 );
382
383 // Resolve the provider with the typed helper so list()'s element type
384 // is exactly the resource's Attributes (no `any`).
385 const provider = yield* Provider.findProvider(Cloudflare.Healthcheck.Healthcheck);
386 const all = yield* provider.list();
387
388 // The exhaustively-paginated, all-zones result must contain the check we
389 // just deployed in the standing test zone.
390 expect(all.some((h) => h.healthcheckId === deployed.healthcheckId)).toBe(true);
391 const found = all.find((h) => h.healthcheckId === deployed.healthcheckId);
392 expect(found?.zoneId).toEqual(zoneId);
393 expect(found?.name).toEqual(NAME_LIST);
394 expect(found?.address).toEqual("www.cloudflare.com");
395
396 yield* stack.destroy();
397
398 yield* expectGone(zoneId, deployed.healthcheckId);
399 }).pipe(logLevel),
400 {
401 tags: [
402 "provider:cloudflare",
403 "provider:cloudflare:healthcheck",
404 "provider:cloudflare:zone",
405 "live",
406 ],
407 },
408 );
409
410 /**
411 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
412 * whether the engine raised it as a typed failure or a defect.
413 */
414 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
415 cause.reasons
416 .map((reason) =>
417 Cause.isFailReason(reason)
418 ? reason.error
419 : Cause.isDieReason(reason)
420 ? reason.defect
421 : undefined,
422 )
423 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);