@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 465 lines 15.8 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import type { TestScheduleAttributes } from "@alchemy.run/cloudflare/Speed/TestSchedule";
4 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
5 import { expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as speed from "@distilled.cloud/cloudflare/speed";
8 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
9 import * as Provider from "alchemy/Provider";
10 import * as Cause from "effect/Cause";
11 import * as Effect from "effect/Effect";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 // Cloudflare counts schedule *creations* against a per-day quota and does NOT
18 // refund it on delete (Observatory docs: "Deleted tests are still counted as
19 // part of the quota"), so neither the trailing `stack.destroy()` nor
20 // `bun nuke` can reclaim budget. These tests each burn 1–2 creations per run
21 // and exhaust `3/3` after ~1–2 same-day runs, so they are skipped by default.
22 // Set RUN_SPEED_SCHEDULE_TESTS=1 to run them against an account/zone with
23 // fresh daily budget.
24 const runSpeedScheduleTests = !!process.env.RUN_SPEED_SCHEDULE_TESTS;
25
26 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
27
28 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
29
30 // Deterministic per-test URLs. Schedules are keyed per (url, region), so each
31 // test owns a disjoint page path — reruns and parallel runs never collide and
32 // the same identity is reused on every run.
33 //
34 // NOTE: Cloudflare caps schedule creations per URL at 3 per day
35 // (`speed.errors.Schedule daily quota reached 3 / 3`, typed as
36 // `TestScheduleQuotaReached`). Each test tolerates an exhausted quota by
37 // skipping its assertions gracefully, so same-day reruns stay green.
38 const URL_CREATE = `${zoneName}/speed-create`;
39 const URL_FREQ = `${zoneName}/speed-freq`;
40 const URL_REGION = `${zoneName}/speed-region`;
41 const URL_TAKEOVER = `${zoneName}/speed-takeover`;
42 const URL_LIST = `${zoneName}/speed-list`;
43
44 const resolveZoneId = Effect.gen(function* () {
45 const { accountId } = yield* yield* CloudflareEnvironment;
46 const zone = yield* findZoneByName({ accountId, name: zoneName });
47 if (!zone) {
48 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
49 }
50 return zone.id;
51 });
52
53 // The scoped API token the test harness mints propagates eventually-
54 // consistently across Cloudflare's edge — a fresh token intermittently 403s.
55 // Ride out the blips on the test's own out-of-band verification calls by
56 // retrying the typed `Forbidden` error (part of each speed operation's error
57 // union via distilled patches).
58 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
59
60 /** Out-of-band read: the live schedule for (url, region), or undefined. */
61 const findSchedule = (
62 zoneId: string,
63 url: string,
64 region: speed.GetScheduleRequest["region"] = "us-central1",
65 ) =>
66 speed.getSchedule({ zoneId, url, region }).pipe(
67 Effect.map((s): speed.GetScheduleResponse | undefined => s),
68 Effect.catchTag("TestScheduleNotFound", () => Effect.succeed(undefined)),
69 Effect.retry({
70 while: (e) => e._tag === "Forbidden",
71 schedule: forbiddenRetrySchedule,
72 times: 8,
73 }),
74 );
75
76 /** Purge a schedule left behind by an interrupted run. */
77 const purgeSchedule = (
78 zoneId: string,
79 url: string,
80 region: speed.DeleteScheduleRequest["region"] = "us-central1",
81 ) =>
82 speed.deleteSchedule({ zoneId, url, region }).pipe(
83 Effect.catchTag("TestScheduleNotFound", () => Effect.void),
84 Effect.retry({
85 while: (e) => e._tag === "Forbidden",
86 schedule: forbiddenRetrySchedule,
87 times: 8,
88 }),
89 );
90
91 /**
92 * Deploy, but converge a `TestScheduleQuotaReached` failure (Cloudflare's
93 * per-URL daily schedule-creation cap) to `undefined` so the calling test
94 * can skip its assertions gracefully instead of failing on same-day reruns.
95 */
96 const deployUnlessQuotaReached = (
97 stack: Test.ScratchStack,
98 eff: Effect.Effect<any, any, any>,
99 ): Effect.Effect<TestScheduleAttributes | undefined, any, any> =>
100 stack
101 .deploy(eff)
102 .pipe(
103 Effect.catchCause((cause): Effect.Effect<TestScheduleAttributes | undefined, any, never> =>
104 findQuotaError(cause) ? Effect.succeed(undefined) : Effect.failCause(cause),
105 ),
106 );
107
108 const logQuotaSkip = (what: string) =>
109 Effect.logWarning(
110 `skipping ${what}: Cloudflare's daily schedule-creation quota for this URL is exhausted (TestScheduleQuotaReached)`,
111 );
112
113 test.provider.skipIf(!runSpeedScheduleTests)(
114 "create and delete a scheduled speed test",
115 (stack) =>
116 Effect.gen(function* () {
117 const zoneId = yield* resolveZoneId;
118
119 yield* stack.destroy();
120 yield* purgeSchedule(zoneId, URL_CREATE);
121
122 const schedule = yield* deployUnlessQuotaReached(
123 stack,
124 Effect.gen(function* () {
125 return yield* Cloudflare.Speed.TestSchedule("DefaultSchedule", {
126 zoneId,
127 url: URL_CREATE,
128 frequency: "WEEKLY",
129 }).pipe(adopt(true));
130 }),
131 );
132
133 if (schedule === undefined) {
134 yield* logQuotaSkip("create/delete assertions");
135 yield* stack.destroy();
136 return;
137 }
138
139 expect(schedule.zoneId).toEqual(zoneId);
140 expect(schedule.url).toEqual(URL_CREATE);
141 expect(schedule.region).toEqual("us-central1");
142 expect(schedule.frequency).toEqual("WEEKLY");
143
144 const live = yield* findSchedule(zoneId, URL_CREATE);
145 expect(live).toBeDefined();
146 expect(live?.url).toEqual(URL_CREATE);
147 expect(live?.frequency).toEqual("WEEKLY");
148
149 yield* stack.destroy();
150
151 const gone = yield* findSchedule(zoneId, URL_CREATE);
152 expect(gone).toBeUndefined();
153 }).pipe(logLevel),
154 {
155 tags: ["provider:cloudflare", "provider:cloudflare:speed", "provider:cloudflare:zone", "live"],
156 timeout: 120_000,
157 },
158 );
159
160 test.provider.skipIf(!runSpeedScheduleTests)(
161 "changing the frequency converges in place",
162 (stack) =>
163 Effect.gen(function* () {
164 const zoneId = yield* resolveZoneId;
165
166 yield* stack.destroy();
167 yield* purgeSchedule(zoneId, URL_FREQ);
168
169 const initial = yield* deployUnlessQuotaReached(
170 stack,
171 Effect.gen(function* () {
172 return yield* Cloudflare.Speed.TestSchedule("UpdateSchedule", {
173 zoneId,
174 url: URL_FREQ,
175 frequency: "WEEKLY",
176 }).pipe(adopt(true));
177 }),
178 );
179 if (initial === undefined) {
180 yield* logQuotaSkip("frequency-update test");
181 yield* stack.destroy();
182 return;
183 }
184 expect(initial.frequency).toEqual("WEEKLY");
185
186 const updated = yield* deployUnlessQuotaReached(
187 stack,
188 Effect.gen(function* () {
189 return yield* Cloudflare.Speed.TestSchedule("UpdateSchedule", {
190 zoneId,
191 url: URL_FREQ,
192 frequency: "DAILY",
193 }).pipe(adopt(true));
194 }),
195 );
196
197 if (updated === undefined) {
198 yield* logQuotaSkip("frequency-update assertions");
199 // The provider restores the previous WEEKLY schedule when the
200 // post-delete re-create is quota-rejected (if even the restore was
201 // quota-rejected, the schedule is gone — both are acceptable here).
202 const restored = yield* findSchedule(zoneId, URL_FREQ);
203 if (restored) expect(restored.frequency).toEqual("WEEKLY");
204 yield* stack.destroy();
205 yield* purgeSchedule(zoneId, URL_FREQ);
206 return;
207 }
208
209 // Same identity — the schedule was converged, not replaced.
210 expect(updated.url).toEqual(URL_FREQ);
211 expect(updated.region).toEqual("us-central1");
212 expect(updated.frequency).toEqual("DAILY");
213
214 const live = yield* findSchedule(zoneId, URL_FREQ);
215 expect(live?.frequency).toEqual("DAILY");
216
217 yield* stack.destroy();
218
219 const gone = yield* findSchedule(zoneId, URL_FREQ);
220 expect(gone).toBeUndefined();
221 }).pipe(logLevel),
222 {
223 tags: ["provider:cloudflare", "provider:cloudflare:speed", "provider:cloudflare:zone", "live"],
224 timeout: 120_000,
225 },
226 );
227
228 test.provider.skipIf(!runSpeedScheduleTests)(
229 "changing the region triggers replacement",
230 (stack) =>
231 Effect.gen(function* () {
232 const zoneId = yield* resolveZoneId;
233
234 yield* stack.destroy();
235 yield* purgeSchedule(zoneId, URL_REGION, "us-central1");
236 yield* purgeSchedule(zoneId, URL_REGION, "us-east1");
237
238 const initial = yield* deployUnlessQuotaReached(
239 stack,
240 Effect.gen(function* () {
241 return yield* Cloudflare.Speed.TestSchedule("ReplaceSchedule", {
242 zoneId,
243 url: URL_REGION,
244 region: "us-central1",
245 frequency: "WEEKLY",
246 }).pipe(adopt(true));
247 }),
248 );
249 if (initial === undefined) {
250 yield* logQuotaSkip("region-replacement test");
251 yield* stack.destroy();
252 return;
253 }
254 expect(initial.region).toEqual("us-central1");
255
256 const replaced = yield* deployUnlessQuotaReached(
257 stack,
258 Effect.gen(function* () {
259 return yield* Cloudflare.Speed.TestSchedule("ReplaceSchedule", {
260 zoneId,
261 url: URL_REGION,
262 region: "us-east1",
263 frequency: "WEEKLY",
264 }).pipe(adopt(true));
265 }),
266 );
267 if (replaced === undefined) {
268 yield* logQuotaSkip("region-replacement assertions");
269 yield* stack.destroy();
270 yield* purgeSchedule(zoneId, URL_REGION, "us-central1");
271 yield* purgeSchedule(zoneId, URL_REGION, "us-east1");
272 return;
273 }
274
275 // (url, region) is the schedule's identity — a new schedule exists in
276 // the new region.
277 expect(replaced.region).toEqual("us-east1");
278
279 const live = yield* findSchedule(zoneId, URL_REGION, "us-east1");
280 expect(live).toBeDefined();
281
282 // The old region's schedule was deleted as part of the replacement.
283 const old = yield* findSchedule(zoneId, URL_REGION, "us-central1");
284 expect(old).toBeUndefined();
285
286 yield* stack.destroy();
287
288 const gone = yield* findSchedule(zoneId, URL_REGION, "us-east1");
289 expect(gone).toBeUndefined();
290 }).pipe(logLevel),
291 {
292 tags: ["provider:cloudflare", "provider:cloudflare:speed", "provider:cloudflare:zone", "live"],
293 timeout: 120_000,
294 },
295 );
296
297 test.provider(
298 "adoption — existing schedule errors without adopt, takes over with adopt(true)",
299 (stack) =>
300 Effect.gen(function* () {
301 const zoneId = yield* resolveZoneId;
302
303 yield* stack.destroy();
304 yield* purgeSchedule(zoneId, URL_TAKEOVER);
305
306 // Create the schedule out-of-band so the stack has no state of its own
307 // for it — exactly the "the schedule already exists" scenario.
308 const pre = yield* speed
309 .createSchedule({
310 zoneId,
311 url: URL_TAKEOVER,
312 region: "us-central1",
313 frequency: "WEEKLY",
314 })
315 .pipe(
316 Effect.map((r): speed.CreateScheduleResponse | undefined => r),
317 Effect.catchTag("TestScheduleQuotaReached", () => Effect.succeed(undefined)),
318 Effect.retry({
319 while: (e) => e._tag === "Forbidden",
320 schedule: forbiddenRetrySchedule,
321 times: 8,
322 }),
323 );
324 if (pre === undefined) {
325 yield* logQuotaSkip("adoption test");
326 return;
327 }
328 expect(pre.schedule?.url).toEqual(URL_TAKEOVER);
329
330 // Without `adopt`: schedules carry no ownership markers, so the engine
331 // cannot prove we created it and refuses to take it over.
332 // (Frequency stays WEEKLY throughout — converging the frequency is
333 // covered by the update test and would burn extra creation quota.)
334 const error = yield* stack
335 .deploy(
336 Effect.gen(function* () {
337 return yield* Cloudflare.Speed.TestSchedule("AdoptedSchedule", {
338 zoneId,
339 url: URL_TAKEOVER,
340 frequency: "WEEKLY",
341 });
342 }),
343 )
344 .pipe(
345 Effect.as(undefined),
346 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
347 );
348 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
349
350 // With `adopt(true)`: the engine takes over the pre-existing schedule
351 // (a no-op reconcile — no extra creation, so no quota concern).
352 const adopted = yield* stack.deploy(
353 Effect.gen(function* () {
354 return yield* Cloudflare.Speed.TestSchedule("AdoptedSchedule", {
355 zoneId,
356 url: URL_TAKEOVER,
357 frequency: "WEEKLY",
358 }).pipe(adopt(true));
359 }),
360 );
361
362 expect(adopted.url).toEqual(URL_TAKEOVER);
363 expect(adopted.frequency).toEqual("WEEKLY");
364
365 const live = yield* findSchedule(zoneId, URL_TAKEOVER);
366 expect(live?.frequency).toEqual("WEEKLY");
367
368 yield* stack.destroy();
369
370 const gone = yield* findSchedule(zoneId, URL_TAKEOVER);
371 expect(gone).toBeUndefined();
372 }).pipe(logLevel),
373 {
374 tags: ["provider:cloudflare", "provider:cloudflare:speed", "provider:cloudflare:zone", "live"],
375 timeout: 120_000,
376 },
377 );
378
379 test.provider.skipIf(!runSpeedScheduleTests)(
380 "list enumerates the deployed schedule across zones",
381 (stack) =>
382 Effect.gen(function* () {
383 const zoneId = yield* resolveZoneId;
384
385 yield* stack.destroy();
386 yield* purgeSchedule(zoneId, URL_LIST);
387
388 const schedule = yield* deployUnlessQuotaReached(
389 stack,
390 Effect.gen(function* () {
391 return yield* Cloudflare.Speed.TestSchedule("ListSchedule", {
392 zoneId,
393 url: URL_LIST,
394 frequency: "WEEKLY",
395 }).pipe(adopt(true));
396 }),
397 );
398
399 if (schedule === undefined) {
400 yield* logQuotaSkip("list assertions");
401 yield* stack.destroy();
402 return;
403 }
404
405 const provider = yield* Provider.findProvider(Cloudflare.Speed.TestSchedule);
406 // Ride out fresh-token 403 blips on the account-wide enumeration.
407 const all = yield* provider.list().pipe(
408 Effect.retry({
409 while: (e) => e._tag === "Forbidden",
410 schedule: forbiddenRetrySchedule,
411 times: 8,
412 }),
413 );
414
415 // Each element is the exact `read` Attributes shape, usable by delete.
416 expect(
417 all.some(
418 (s) =>
419 s.zoneId === schedule.zoneId && s.url === schedule.url && s.region === schedule.region,
420 ),
421 ).toBe(true);
422
423 yield* stack.destroy();
424
425 const gone = yield* findSchedule(zoneId, URL_LIST);
426 expect(gone).toBeUndefined();
427 }).pipe(logLevel),
428 {
429 tags: ["provider:cloudflare", "provider:cloudflare:speed", "provider:cloudflare:zone", "live"],
430 timeout: 120_000,
431 },
432 );
433
434 /**
435 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
436 * whether the engine raised it as a typed failure or a defect.
437 */
438 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
439 cause.reasons
440 .map((reason) =>
441 Cause.isFailReason(reason)
442 ? reason.error
443 : Cause.isDieReason(reason)
444 ? reason.defect
445 : undefined,
446 )
447 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);
448
449 /**
450 * Pull the typed {@link speed.TestScheduleQuotaReached} value out of a Cause
451 * regardless of whether the engine raised it as a typed failure or a defect.
452 */
453 const findQuotaError = (cause: Cause.Cause<unknown>): speed.TestScheduleQuotaReached | undefined =>
454 cause.reasons
455 .map((reason) =>
456 Cause.isFailReason(reason)
457 ? reason.error
458 : Cause.isDieReason(reason)
459 ? reason.defect
460 : undefined,
461 )
462 .find(
463 (value): value is speed.TestScheduleQuotaReached =>
464 value instanceof speed.TestScheduleQuotaReached,
465 );