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

main
ts 273 lines 9.84 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 loadBalancers from "@distilled.cloud/cloudflare/load-balancers";
7 import * as Provider from "alchemy/Provider";
8 import * as Effect from "effect/Effect";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import { testName } from "../../names.ts";
12
13 const { test } = Test.make({ providers: Cloudflare.providers() });
14
15 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
16
17 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
18
19 // Load Balancing is a paid add-on subscription. The testing zone does not
20 // have it: load balancer creation is rejected with "load balancing not
21 // enabled for zone" (Cloudflare code 1002), surfaced as the typed
22 // `LoadBalancingNotEnabledForZone` error. Set CLOUDFLARE_LB_ENABLED=1 once
23 // the subscription is provisioned to run the full lifecycle test.
24 const lbEnabled = !!process.env.CLOUDFLARE_LB_ENABLED;
25
26 // Deterministic per-test hostnames — reused on every run.
27 const NAME_ENTITLEMENT = `${testName("alchemy-lb-entitlement-probe")}.${zoneName}`;
28 const NAME_LIFECYCLE = `${testName("alchemy-lb-lifecycle")}.${zoneName}`;
29 const NAME_POOL = testName("alchemy-lb-lifecycle-pool");
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 // Freshly minted scoped tokens propagate eventually-consistently across
41 // Cloudflare's edge — retry the typed `Forbidden` blips on out-of-band calls.
42 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
43
44 const getLoadBalancer = (zoneId: string, loadBalancerId: string) =>
45 loadBalancers.getLoadBalancer({ zoneId, loadBalancerId }).pipe(
46 Effect.retry({
47 while: (e) => e._tag === "Forbidden",
48 schedule: forbiddenRetrySchedule,
49 times: 8,
50 }),
51 );
52
53 const expectGone = (zoneId: string, loadBalancerId: string) =>
54 getLoadBalancer(zoneId, loadBalancerId).pipe(
55 Effect.flatMap(() => Effect.fail({ _tag: "LoadBalancerNotDeleted" } as const)),
56 // A missing load balancer surfaces as the typed `LoadBalancerNotFound`
57 // (Cloudflare error code 1001) — that's the success condition here.
58 Effect.catchTag("LoadBalancerNotFound", () => Effect.void),
59 Effect.retry({
60 while: (e) => e._tag === "LoadBalancerNotDeleted",
61 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
62 }),
63 );
64
65 // Unentitlement probe: pins the typed plan-gate rejection, so it must skip
66 // on entitled accounts — there the create would succeed instead of failing.
67 test.provider.skipIf(lbEnabled)(
68 "surfaces the typed LoadBalancingNotEnabledForZone error without the LB subscription",
69 (stack) =>
70 Effect.gen(function* () {
71 const zoneId = yield* resolveZoneId;
72
73 yield* stack.destroy();
74
75 // The zone entitlement gate fires before pool validation, so
76 // placeholder pool ids are fine here.
77 const error = yield* loadBalancers
78 .createLoadBalancer({
79 zoneId,
80 name: NAME_ENTITLEMENT,
81 defaultPools: ["17b5962d775c646f3f9725cbc7a53df4"],
82 fallbackPool: "17b5962d775c646f3f9725cbc7a53df4",
83 })
84 .pipe(
85 Effect.retry({
86 while: (e) => e._tag === "Forbidden",
87 schedule: forbiddenRetrySchedule,
88 times: 8,
89 }),
90 Effect.flip,
91 );
92 expect(error._tag).toEqual("LoadBalancingNotEnabledForZone");
93
94 yield* stack.destroy();
95 }).pipe(logLevel),
96 {
97 tags: [
98 "provider:cloudflare",
99 "provider:cloudflare:loadbalancer",
100 "provider:cloudflare:zone",
101 "live",
102 ],
103 },
104 );
105
106 test.provider.skipIf(!lbEnabled)(
107 "create, update in place, and destroy a load balancer",
108 (stack) =>
109 Effect.gen(function* () {
110 const zoneId = yield* resolveZoneId;
111
112 yield* stack.destroy();
113
114 const initial = yield* stack.deploy(
115 Effect.gen(function* () {
116 const pool = yield* Cloudflare.LoadBalancer.Pool("Pool", {
117 name: NAME_POOL,
118 origins: [{ name: "origin-1", address: "203.0.113.10" }],
119 });
120 const lb = yield* Cloudflare.LoadBalancer.LoadBalancer("Lb", {
121 zoneId,
122 name: NAME_LIFECYCLE,
123 defaultPools: [pool.poolId],
124 fallbackPool: pool.poolId,
125 proxied: false,
126 ttl: 30,
127 });
128 return { pool, lb };
129 }),
130 );
131
132 expect(initial.lb.loadBalancerId).toBeTruthy();
133 expect(initial.lb.zoneId).toEqual(zoneId);
134 expect(initial.lb.name).toEqual(NAME_LIFECYCLE);
135 expect(initial.lb.proxied).toEqual(false);
136 expect(initial.lb.defaultPools).toEqual([initial.pool.poolId]);
137 expect(initial.lb.fallbackPool).toEqual(initial.pool.poolId);
138
139 const live = yield* getLoadBalancer(zoneId, initial.lb.loadBalancerId);
140 expect(live.name).toEqual(NAME_LIFECYCLE);
141 expect(live.defaultPools).toEqual([initial.pool.poolId]);
142
143 // Mutable props (steering, affinity, proxied) update in place — same
144 // loadBalancerId. Keep the pool deployed across every step so the
145 // engine never has to replace and drop a dependency in one deploy.
146 const updated = yield* stack.deploy(
147 Effect.gen(function* () {
148 const pool = yield* Cloudflare.LoadBalancer.Pool("Pool", {
149 name: NAME_POOL,
150 origins: [{ name: "origin-1", address: "203.0.113.10" }],
151 });
152 const lb = yield* Cloudflare.LoadBalancer.LoadBalancer("Lb", {
153 zoneId,
154 name: NAME_LIFECYCLE,
155 defaultPools: [pool.poolId],
156 fallbackPool: pool.poolId,
157 proxied: true,
158 steeringPolicy: "random",
159 sessionAffinity: "cookie",
160 });
161 return { pool, lb };
162 }),
163 );
164 expect(updated.lb.loadBalancerId).toEqual(initial.lb.loadBalancerId);
165 expect(updated.lb.proxied).toEqual(true);
166 expect(updated.lb.steeringPolicy).toEqual("random");
167
168 const synced = yield* getLoadBalancer(zoneId, updated.lb.loadBalancerId);
169 expect(synced.proxied).toEqual(true);
170 expect(synced.steeringPolicy).toEqual("random");
171 expect(synced.sessionAffinity).toEqual("cookie");
172
173 yield* stack.destroy();
174
175 yield* expectGone(zoneId, initial.lb.loadBalancerId);
176 }).pipe(logLevel),
177 {
178 tags: [
179 "provider:cloudflare",
180 "provider:cloudflare:loadbalancer",
181 "provider:cloudflare:zone",
182 "live",
183 ],
184 timeout: 120_000,
185 },
186 );
187
188 // Canonical `list()` test, ungated read-only half: load balancers are
189 // zone-scoped, so `list()` fans out over every zone and exhaustively
190 // paginates each zone's load balancers. The testing account's zones lack
191 // the Load Balancing subscription, so the per-zone list yields no rows
192 // (and any `Forbidden` zone is skipped) — assert a well-typed array whose
193 // elements (if any) match the `read` Attributes shape.
194 test.provider(
195 "list returns a well-typed array of load balancers",
196 (stack) =>
197 Effect.gen(function* () {
198 yield* stack.destroy();
199
200 const provider = yield* Provider.findProvider(Cloudflare.LoadBalancer.LoadBalancer);
201 const all = yield* provider.list();
202
203 expect(Array.isArray(all)).toBe(true);
204 for (const lb of all) {
205 expect(typeof lb.loadBalancerId).toBe("string");
206 expect(typeof lb.zoneId).toBe("string");
207 expect(typeof lb.name).toBe("string");
208 expect(typeof lb.enabled).toBe("boolean");
209 expect(typeof lb.proxied).toBe("boolean");
210 expect(typeof lb.steeringPolicy).toBe("string");
211 expect(Array.isArray(lb.defaultPools)).toBe(true);
212 expect(typeof lb.fallbackPool).toBe("string");
213 }
214
215 yield* stack.destroy();
216 }).pipe(logLevel),
217 {
218 tags: ["provider:cloudflare", "provider:cloudflare:loadbalancer", "live"],
219 timeout: 120_000,
220 },
221 );
222
223 // Entitlement-gated half: with the Load Balancing subscription enabled,
224 // deploy a real pool + load balancer and assert the deployed item appears
225 // in the exhaustively-paginated, fanned-out `list()` result.
226 test.provider.skipIf(!lbEnabled)(
227 "list enumerates the deployed load balancer",
228 (stack) =>
229 Effect.gen(function* () {
230 const zoneId = yield* resolveZoneId;
231
232 yield* stack.destroy();
233
234 const deployed = yield* stack.deploy(
235 Effect.gen(function* () {
236 const pool = yield* Cloudflare.LoadBalancer.Pool("Pool", {
237 name: NAME_POOL,
238 origins: [{ name: "origin-1", address: "203.0.113.10" }],
239 });
240 const lb = yield* Cloudflare.LoadBalancer.LoadBalancer("Lb", {
241 zoneId,
242 name: NAME_LIFECYCLE,
243 defaultPools: [pool.poolId],
244 fallbackPool: pool.poolId,
245 proxied: false,
246 ttl: 30,
247 });
248 return { pool, lb };
249 }),
250 );
251
252 const provider = yield* Provider.findProvider(Cloudflare.LoadBalancer.LoadBalancer);
253 const all = yield* provider.list();
254
255 const row = all.find((lb) => lb.loadBalancerId === deployed.lb.loadBalancerId);
256 expect(row).toBeDefined();
257 expect(row!.zoneId).toEqual(zoneId);
258 expect(row!.name).toEqual(NAME_LIFECYCLE);
259
260 yield* stack.destroy();
261
262 yield* expectGone(zoneId, deployed.lb.loadBalancerId);
263 }).pipe(logLevel),
264 {
265 tags: [
266 "provider:cloudflare",
267 "provider:cloudflare:loadbalancer",
268 "provider:cloudflare:zone",
269 "live",
270 ],
271 timeout: 120_000,
272 },
273 );