@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 266 lines 11.1 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 zones from "@distilled.cloud/cloudflare/zones";
7 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
8 import * as Provider from "alchemy/Provider";
9 import { destroy } from "alchemy/RemovalPolicy";
10 import * as Cause from "effect/Cause";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as Predicate from "effect/Predicate";
14 import * as Schedule from "effect/Schedule";
15
16 const { test } = Test.make({ providers: Cloudflare.providers() });
17
18 // Cloudflare intermittently blocks *all* zone creation on an account with
19 // error 1052 ("An error(zone setup) has occurred and it has been logged");
20 // the block is account-level and can persist for hours. The zone-provisioning
21 // tests below create fresh zones, so soft-skip them while the account is in
22 // that state; every other failure propagates unchanged.
23 const softSkipWhenZoneCreationBlocked = <A, E, R>(
24 effect: Effect.Effect<A, E, R>,
25 ): Effect.Effect<A | undefined, E, R> =>
26 effect.pipe(
27 Effect.catchCause((cause) => {
28 // Match by tag rather than `instanceof zones.ZoneCreationBlocked`: the
29 // error can be constructed inside the provider's copy of the distilled
30 // module, so `instanceof` across that module boundary can be false.
31 const blocked = cause.reasons
32 .map((reason) =>
33 Cause.isFailReason(reason)
34 ? reason.error
35 : Cause.isDieReason(reason)
36 ? reason.defect
37 : undefined,
38 )
39 .some(
40 (value) => Predicate.hasProperty(value, "_tag") && value._tag === "ZoneCreationBlocked",
41 );
42 return blocked
43 ? Effect.logWarning(
44 "Cloudflare has zone creation blocked on this account (error 1052) — skipping zone-provisioning assertions",
45 ).pipe(Effect.as(undefined))
46 : Effect.failCause(cause);
47 }),
48 );
49
50 // Cloudflare's POST /zones rejects reserved pseudo-TLDs (`.test`, `.local`,
51 // `.example`) with "unable to identify ... as a registered domain". A
52 // syntactically-valid, registerable name is accepted into a `pending` zone
53 // even when the domain isn't actually registered to us — which is all these
54 // create/delete lifecycle tests need. Derive the name from the test account id
55 // so it's deterministic and never collides with a real zone.
56 const zoneNameFor = (accountId: string, label: string) =>
57 process.env.TEST_ZONE_NAME ?? `alchemy-${label}-${accountId}.com`;
58
59 // Skipped: the testing account is out of Enterprise zone quota, so every
60 // zone create fails with `ZoneQuotaExceeded` ("You have exceeded your
61 // Enterprise zone quota"). No test zones leak into it; the account holds only
62 // its standing zones. Re-enable on an account with zone quota.
63 test.provider.skip(
64 "create zone retains by default — destroy() opts in to deletion",
65 (stack) =>
66 softSkipWhenZoneCreationBlocked(
67 Effect.gen(function* () {
68 const { accountId } = yield* yield* CloudflareEnvironment;
69 const TEST_ZONE = zoneNameFor(accountId, "destroy");
70
71 const zone = yield* stack.deploy(
72 Effect.gen(function* () {
73 return yield* Cloudflare.Zone.Zone("CreatedZone", { name: TEST_ZONE }).pipe(destroy());
74 }),
75 );
76
77 expect(zone.name).toBe(TEST_ZONE);
78 expect(zone.accountId).toBe(accountId);
79
80 // The mapped attributes should match what the Cloudflare API reports,
81 // with the API's `null`s normalized to `undefined`.
82 const live = yield* zones.getZone({ zoneId: zone.zoneId });
83 expect(zone.zoneId).toBe(live.id);
84 expect(zone.name).toBe(live.name);
85 expect(zone.accountName).toBe(live.account.name ?? undefined);
86 expect(zone.type).toBe(live.type ?? "full");
87 expect(zone.status).toBe(live.status ?? undefined);
88 expect(zone.paused).toBe(live.paused ?? false);
89 expect(zone.nameServers).toEqual(live.nameServers);
90 expect(zone.originalNameServers).toEqual(live.originalNameServers ?? undefined);
91 expect(zone.vanityNameServers).toEqual(live.vanityNameServers ?? undefined);
92 expect(zone.activatedOn).toBe(live.activatedOn ?? undefined);
93 expect(zone.createdOn).toBe(live.createdOn);
94 expect(zone.modifiedOn).toBe(live.modifiedOn);
95 expect(zone.developmentMode).toBe(live.developmentMode);
96 expect(zone.originalDnshost).toBe(live.originalDnshost ?? undefined);
97 expect(zone.originalRegistrar).toBe(live.originalRegistrar ?? undefined);
98 expect(zone.cnameSuffix).toBe(live.cnameSuffix ?? undefined);
99 expect(zone.verificationKey).toBe(live.verificationKey ?? undefined);
100 expect(zone.owner.id).toBe(live.owner.id ?? undefined);
101 expect(zone.meta.foundationDns).toBe(live.meta.foundationDns ?? undefined);
102
103 yield* stack.destroy();
104
105 yield* waitForZoneToBeDeleted(zone.zoneId);
106 }),
107 ),
108 { tags: ["provider:cloudflare", "provider:cloudflare:zone", "live"] },
109 );
110
111 // Skipped: `ZoneQuotaExceeded` on the testing account (see above).
112 test.provider.skip(
113 "create zone retains by default — survives stack.destroy()",
114 (stack) =>
115 softSkipWhenZoneCreationBlocked(
116 Effect.gen(function* () {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 const TEST_ZONE = zoneNameFor(accountId, "retain");
119
120 const zone = yield* stack.deploy(
121 Effect.gen(function* () {
122 return yield* Cloudflare.Zone.Zone("RetainedZone", { name: TEST_ZONE });
123 }),
124 );
125
126 expect(zone.name).toBe(TEST_ZONE);
127 expect(zone.accountId).toBe(accountId);
128
129 yield* stack.destroy();
130
131 const live = yield* zones.getZone({ zoneId: zone.zoneId });
132 expect(live.id).toBe(zone.zoneId);
133
134 // clean up the retained zone so the test is repeatable
135 yield* zones.deleteZone({ zoneId: zone.zoneId });
136 yield* waitForZoneToBeDeleted(zone.zoneId);
137 }),
138 ),
139 { tags: ["provider:cloudflare", "provider:cloudflare:zone", "live"] },
140 );
141
142 // Skipped: `ZoneQuotaExceeded` on the testing account (see above).
143 test.provider.skip(
144 "adoption — existing zone errors without adopt, takes over with adopt(true)",
145 (stack) =>
146 softSkipWhenZoneCreationBlocked(
147 Effect.gen(function* () {
148 const { accountId } = yield* yield* CloudflareEnvironment;
149 const TEST_ZONE = zoneNameFor(accountId, "adopt");
150
151 // Create the zone out-of-band so the stack has no state of its own for
152 // it — exactly the "the zone already exists" scenario. Tolerate a zone
153 // left behind by an interrupted run so the test stays repeatable.
154 const existing = yield* zones
155 .createZone({ account: { id: accountId }, name: TEST_ZONE, type: "full" })
156 .pipe(
157 Effect.catchTag("ZoneAlreadyExists", () =>
158 findZoneByName({ accountId, name: TEST_ZONE }).pipe(
159 Effect.flatMap((match) =>
160 match
161 ? Effect.succeed(match)
162 : Effect.die(new Error(`zone ${TEST_ZONE} not found`)),
163 ),
164 ),
165 ),
166 );
167
168 // Without `adopt`: a Cloudflare zone carries no ownership markers, so the
169 // engine cannot prove we created it and refuses to take it over. The
170 // engine surfaces this as a defect, so catch the whole cause and pull the
171 // typed error back out rather than string-matching the message.
172 const error = yield* stack
173 .deploy(
174 Effect.gen(function* () {
175 return yield* Cloudflare.Zone.Zone("AdoptedZone", { name: TEST_ZONE });
176 }),
177 )
178 .pipe(
179 Effect.as(undefined),
180 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
181 );
182 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
183
184 // With `adopt(true)`: the engine takes over the pre-existing zone instead
185 // of creating a new one. `destroy()` opts the adopted zone into deletion
186 // on teardown so the test stays repeatable.
187 const adopted = yield* stack
188 .deploy(
189 Effect.gen(function* () {
190 return yield* Cloudflare.Zone.Zone("AdoptedZone", { name: TEST_ZONE }).pipe(
191 destroy(),
192 );
193 }),
194 )
195 .pipe(adopt(true));
196 expect(adopted.zoneId).toBe(existing.id);
197 expect(adopted.name).toBe(TEST_ZONE);
198
199 yield* stack.destroy();
200 yield* waitForZoneToBeDeleted(existing.id);
201 }),
202 ),
203 { tags: ["provider:cloudflare", "provider:cloudflare:zone", "live"] },
204 );
205
206 // Standing test zone — always present in the testing account.
207 const TEST_ZONE_NAME = "alchemy-test-2.us";
208
209 test.provider.skipIf(!!process.env.FAST)(
210 "list enumerates every zone in the account",
211 (stack) =>
212 Effect.gen(function* () {
213 yield* stack.destroy();
214
215 const { accountId } = yield* yield* CloudflareEnvironment;
216 const testZone = yield* findZoneByName({ accountId, name: TEST_ZONE_NAME });
217 expect(testZone).toBeDefined();
218
219 const provider = yield* Provider.findProvider(Cloudflare.Zone.Zone);
220 const all = yield* provider.list();
221
222 // Exhaustive enumeration must include the standing test zone, returned in
223 // the full `read` Attributes shape.
224 const found = all.find((z) => z.zoneId === testZone!.id);
225 expect(found).toBeDefined();
226 expect(found!.name).toBe(TEST_ZONE_NAME);
227 expect(found!.accountId).toBe(accountId);
228 expect(typeof found!.createdOn).toBe("string");
229 expect(Array.isArray(found!.nameServers)).toBe(true);
230
231 yield* stack.destroy();
232 }),
233 { tags: ["provider:cloudflare", "provider:cloudflare:zone", "live"] },
234 );
235
236 const waitForZoneToBeDeleted = Effect.fn(function* (zoneId: string) {
237 yield* zones.getZone({ zoneId }).pipe(
238 // A successful read means the zone is still around — force a retry.
239 Effect.flatMap(() => new ZoneStillExists()),
240 // Any other failure (e.g. `Invalid zone identifier` / 404) means the zone
241 // is gone, which is exactly what we're waiting for.
242 Effect.catch((e) => (e instanceof ZoneStillExists ? Effect.fail(e) : Effect.void)),
243 Effect.retry({
244 while: (e): e is ZoneStillExists => e instanceof ZoneStillExists,
245 schedule: Schedule.exponential(100),
246 times: 20,
247 }),
248 );
249 });
250
251 class ZoneStillExists extends Data.TaggedError("ZoneStillExists") {}
252
253 /**
254 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
255 * whether the engine raised it as a typed failure or a defect.
256 */
257 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
258 cause.reasons
259 .map((reason) =>
260 Cause.isFailReason(reason)
261 ? reason.error
262 : Cause.isDieReason(reason)
263 ? reason.defect
264 : undefined,
265 )
266 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);