@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 372 lines 12.9 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 spectrum from "@distilled.cloud/cloudflare/spectrum";
7 import * as zones from "@distilled.cloud/cloudflare/zones";
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 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 // Spectrum is plan-gated: the standard testing zone (Free plan) rejects
24 // every protocol — even `tcp/22` — with Cloudflare code 13002 "The
25 // requested protocol is not available", surfaced as the typed
26 // `SpectrumProtocolNotAvailable` error. The full lifecycle tests below are
27 // gated behind a Spectrum-entitled zone id supplied via env.
28 const entitledZoneId = process.env.CLOUDFLARE_TEST_SPECTRUM_ZONE_ID;
29
30 const resolveZoneId = Effect.gen(function* () {
31 const { accountId } = yield* yield* CloudflareEnvironment;
32 const zone = yield* findZoneByName({ accountId, name: zoneName });
33 if (!zone) {
34 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
35 }
36 return zone.id;
37 });
38
39 // The scoped API token the test harness mints propagates eventually-
40 // consistently across Cloudflare's edge — ride out 403 blips on the
41 // out-of-band verification calls by retrying the typed `Forbidden` tag.
42 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
43
44 const getApp = (zoneId: string, appId: string) =>
45 spectrum.getApp({ zoneId, appId }).pipe(
46 Effect.retry({
47 while: (e) => e._tag === "Forbidden",
48 schedule: forbiddenRetrySchedule,
49 times: 8,
50 }),
51 );
52
53 const findApp = (zoneId: string, dnsName: string, protocol: string) =>
54 spectrum.listApps.items({ zoneId }).pipe(
55 Stream.filter((a) => a.dns.name === dnsName && a.protocol === protocol),
56 Stream.runCollect,
57 Effect.map((chunk) => Array.from(chunk)[0]),
58 Effect.retry({
59 while: (e) => e._tag === "Forbidden",
60 schedule: forbiddenRetrySchedule,
61 times: 8,
62 }),
63 );
64
65 // Delete every app matching (dns.name, protocol) — purges leftovers from
66 // interrupted runs so the adoption test starts from a clean slate.
67 const purgeApps = (zoneId: string, dnsName: string, protocol: string) =>
68 spectrum.listApps.items({ zoneId }).pipe(
69 Stream.filter((a) => a.dns.name === dnsName && a.protocol === protocol),
70 Stream.runCollect,
71 Effect.flatMap(
72 Effect.forEach((a) =>
73 spectrum
74 .deleteApp({ zoneId, appId: a.id })
75 .pipe(Effect.catchTag("SpectrumAppNotFound", () => Effect.void)),
76 ),
77 ),
78 Effect.retry({
79 while: (e) => e._tag === "Forbidden",
80 schedule: forbiddenRetrySchedule,
81 times: 8,
82 }),
83 );
84
85 // Hostname of the entitled zone, resolved from its id so the gated tests
86 // can build deterministic edge hostnames inside that zone. (No Forbidden
87 // retry here — `zones.getZone`'s typed error union does not include it.)
88 const resolveEntitledZoneName = (zoneId: string) =>
89 zones.getZone({ zoneId }).pipe(Effect.map((z) => z.name));
90
91 test.provider(
92 "surfaces the typed SpectrumProtocolNotAvailable error on unentitled zones",
93 (stack) =>
94 Effect.gen(function* () {
95 const zoneId = yield* resolveZoneId;
96
97 yield* stack.destroy();
98
99 // The standard testing zone has no Spectrum entitlement — the
100 // distilled create must fail with the typed plan-gate tag.
101 const error = yield* spectrum
102 .createApp({
103 zoneId,
104 dns: { type: "CNAME", name: `${testName("alchemy-spectrum-gate")}.${zoneName}` },
105 protocol: "tcp/22",
106 originDirect: ["tcp://192.0.2.1:22"],
107 })
108 .pipe(
109 Effect.retry({
110 while: (e) => e._tag === "Forbidden",
111 schedule: forbiddenRetrySchedule,
112 times: 8,
113 }),
114 Effect.flip,
115 );
116 expect(error._tag).toEqual("SpectrumProtocolNotAvailable");
117
118 yield* stack.destroy();
119 }).pipe(logLevel),
120 {
121 tags: [
122 "provider:cloudflare",
123 "provider:cloudflare:spectrum",
124 "provider:cloudflare:zone",
125 "live",
126 ],
127 },
128 );
129
130 test.provider.skipIf(!entitledZoneId)(
131 "create, update in place, and destroy a tcp/22 application",
132 (stack) =>
133 Effect.gen(function* () {
134 const zoneId = entitledZoneId!;
135 const entitledZoneName = yield* resolveEntitledZoneName(zoneId);
136 const dnsName = `${testName("alchemy-spectrum-lifecycle")}.${entitledZoneName}`;
137
138 yield* stack.destroy();
139 yield* purgeApps(zoneId, dnsName, "tcp/22");
140
141 const app = yield* stack.deploy(
142 Effect.gen(function* () {
143 return yield* Cloudflare.Spectrum.Application("Ssh", {
144 zoneId,
145 dns: { type: "CNAME", name: dnsName },
146 protocol: "tcp/22",
147 originDirect: ["tcp://192.0.2.1:22"],
148 }).pipe(adopt(true));
149 }),
150 );
151
152 expect(app.appId).toBeDefined();
153 expect(app.zoneId).toEqual(zoneId);
154 expect(app.dnsName).toEqual(dnsName);
155 expect(app.protocol).toEqual("tcp/22");
156 expect(app.originDirect).toEqual(["tcp://192.0.2.1:22"]);
157 expect(app.ipFirewall).toEqual(false);
158
159 // Out-of-band verification via the distilled API.
160 const live = yield* getApp(zoneId, app.appId);
161 expect(live.id).toEqual(app.appId);
162 expect(live.dns.name).toEqual(dnsName);
163 expect(live.protocol).toEqual("tcp/22");
164
165 // Update in place: new origin address + ipFirewall on. Same appId —
166 // not a replacement.
167 const updated = yield* stack.deploy(
168 Effect.gen(function* () {
169 return yield* Cloudflare.Spectrum.Application("Ssh", {
170 zoneId,
171 dns: { type: "CNAME", name: dnsName },
172 protocol: "tcp/22",
173 originDirect: ["tcp://192.0.2.2:22"],
174 ipFirewall: true,
175 }).pipe(adopt(true));
176 }),
177 );
178
179 expect(updated.appId).toEqual(app.appId);
180 expect(updated.originDirect).toEqual(["tcp://192.0.2.2:22"]);
181 expect(updated.ipFirewall).toEqual(true);
182
183 const converged = yield* getApp(zoneId, updated.appId);
184 expect(converged.originDirect).toEqual(["tcp://192.0.2.2:22"]);
185
186 yield* stack.destroy();
187
188 // Destroy removed the application (and its Spectrum-managed edge
189 // DNS record with it).
190 const gone = yield* findApp(zoneId, dnsName, "tcp/22");
191 expect(gone).toBeUndefined();
192 }).pipe(logLevel),
193 {
194 tags: [
195 "provider:cloudflare",
196 "provider:cloudflare:spectrum",
197 "provider:cloudflare:zone",
198 "live",
199 ],
200 timeout: 120_000,
201 },
202 );
203
204 test.provider.skipIf(!entitledZoneId)(
205 "adoption — existing app errors without adopt, takes over with adopt(true)",
206 (stack) =>
207 Effect.gen(function* () {
208 const zoneId = entitledZoneId!;
209 const entitledZoneName = yield* resolveEntitledZoneName(zoneId);
210 const dnsName = `${testName("alchemy-spectrum-adopt")}.${entitledZoneName}`;
211
212 yield* stack.destroy();
213 yield* purgeApps(zoneId, dnsName, "tcp/22");
214
215 // Create the application out-of-band so the stack has no state of
216 // its own for it — exactly the "the app already exists" scenario.
217 const pre = yield* spectrum
218 .createApp({
219 zoneId,
220 dns: { type: "CNAME", name: dnsName },
221 protocol: "tcp/22",
222 originDirect: ["tcp://192.0.2.10:22"],
223 })
224 .pipe(
225 Effect.retry({
226 while: (e) => e._tag === "Forbidden",
227 schedule: forbiddenRetrySchedule,
228 times: 8,
229 }),
230 );
231 expect(pre.id).toBeDefined();
232
233 // Without `adopt`: Spectrum apps carry no ownership markers, so the
234 // engine cannot prove we created it and refuses to take it over.
235 const error = yield* stack
236 .deploy(
237 Effect.gen(function* () {
238 return yield* Cloudflare.Spectrum.Application("Adopted", {
239 zoneId,
240 dns: { type: "CNAME", name: dnsName },
241 protocol: "tcp/22",
242 originDirect: ["tcp://192.0.2.11:22"],
243 });
244 }),
245 )
246 .pipe(
247 Effect.as(undefined),
248 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
249 );
250 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
251
252 // With `adopt(true)`: the engine takes over the pre-existing app
253 // (same physical id) and converges it to the desired origin.
254 const adopted = yield* stack.deploy(
255 Effect.gen(function* () {
256 return yield* Cloudflare.Spectrum.Application("Adopted", {
257 zoneId,
258 dns: { type: "CNAME", name: dnsName },
259 protocol: "tcp/22",
260 originDirect: ["tcp://192.0.2.11:22"],
261 }).pipe(adopt(true));
262 }),
263 );
264
265 expect(adopted.appId).toEqual(pre.id);
266 expect(adopted.originDirect).toEqual(["tcp://192.0.2.11:22"]);
267
268 const live = yield* getApp(zoneId, adopted.appId);
269 expect(live.originDirect).toEqual(["tcp://192.0.2.11:22"]);
270
271 yield* stack.destroy();
272
273 const gone = yield* findApp(zoneId, dnsName, "tcp/22");
274 expect(gone).toBeUndefined();
275 }).pipe(logLevel),
276 {
277 tags: [
278 "provider:cloudflare",
279 "provider:cloudflare:spectrum",
280 "provider:cloudflare:zone",
281 "live",
282 ],
283 timeout: 120_000,
284 },
285 );
286
287 // Canonical `list()` test (zone-scoped collection): `list()` fans out over
288 // every zone via `listAllZones`, exhaustively paginates the Spectrum apps in
289 // each, and hydrates them into the exact `read` Attributes shape. Listing is
290 // not entitlement-gated — the standing test zone (no Spectrum) simply yields
291 // no apps for that zone — so this read-only assertion runs unconditionally:
292 // `list()` must resolve to a well-typed array without throwing.
293 test.provider(
294 "list enumerates Spectrum applications across all zones",
295 (stack) =>
296 Effect.gen(function* () {
297 yield* stack.destroy();
298
299 const provider = yield* Provider.findProvider(Cloudflare.Spectrum.Application);
300 const all = yield* provider.list();
301
302 expect(Array.isArray(all)).toBe(true);
303 // Every hydrated item carries the full `read` Attributes shape.
304 for (const app of all) {
305 expect(typeof app.appId).toBe("string");
306 expect(typeof app.zoneId).toBe("string");
307 expect(typeof app.protocol).toBe("string");
308 }
309
310 yield* stack.destroy();
311 }).pipe(logLevel),
312 { tags: ["provider:cloudflare", "provider:cloudflare:spectrum", "live"] },
313 );
314
315 // Full deploy + list assertion: requires a Spectrum-entitled zone (create is
316 // gated by `SpectrumProtocolNotAvailable`, Cloudflare code 13002, on
317 // unentitled zones). When supplied, deploy a tcp/22 app and assert `list()`
318 // surfaces it.
319 test.provider.skipIf(!entitledZoneId)(
320 "list surfaces a deployed Spectrum application (entitled zone)",
321 (stack) =>
322 Effect.gen(function* () {
323 const zoneId = entitledZoneId!;
324 const entitledZoneName = yield* resolveEntitledZoneName(zoneId);
325 const dnsName = `${testName("alchemy-spectrum-list")}.${entitledZoneName}`;
326
327 yield* stack.destroy();
328 yield* purgeApps(zoneId, dnsName, "tcp/22");
329
330 const app = yield* stack.deploy(
331 Effect.gen(function* () {
332 return yield* Cloudflare.Spectrum.Application("Listed", {
333 zoneId,
334 dns: { type: "CNAME", name: dnsName },
335 protocol: "tcp/22",
336 originDirect: ["tcp://192.0.2.1:22"],
337 }).pipe(adopt(true));
338 }),
339 );
340
341 const provider = yield* Provider.findProvider(Cloudflare.Spectrum.Application);
342 const all = yield* provider.list();
343
344 expect(all.some((a) => a.appId === app.appId)).toBe(true);
345
346 yield* stack.destroy();
347 }).pipe(logLevel),
348 {
349 tags: [
350 "provider:cloudflare",
351 "provider:cloudflare:spectrum",
352 "provider:cloudflare:zone",
353 "live",
354 ],
355 timeout: 120_000,
356 },
357 );
358
359 /**
360 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
361 * whether the engine raised it as a typed failure or a defect.
362 */
363 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
364 cause.reasons
365 .map((reason) =>
366 Cause.isFailReason(reason)
367 ? reason.error
368 : Cause.isDieReason(reason)
369 ? reason.defect
370 : undefined,
371 )
372 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);