@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 340 lines 13.3 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { WorkerVersionConfigError } from "@alchemy.run/cloudflare/Workers/WorkerProvider";
4 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
5 import { describe, expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
8 import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as HttpClientResponse from "effect/http/HttpClientResponse";
14 import { MinimumLogLevel } from "effect/References";
15 import * as Schedule from "effect/Schedule";
16 import * as Schema from "effect/Schema";
17 import { stageSuffix } from "../../names.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 // The worker echoes the version-key header the transform rule sets, so a
24 // plain fetch proves the rule rewrote the request end-to-end.
25 const script = `export default { fetch(request) { return new Response(request.headers.get("Cloudflare-Workers-Version-Key") ?? "no-key"); } };`;
26
27 const zoneName =
28 process.env.CLOUDFLARE_TEST_WORKER_DOMAIN_ZONE_NAME ??
29 process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ??
30 "alchemy-test-2.us";
31
32 // Deterministic per-run hostnames on the standing test zone (never derive
33 // names from Date.now()).
34 const suffix = stageSuffix();
35
36 const resolveZone = Effect.gen(function* () {
37 const { accountId } = yield* yield* CloudflareEnvironment;
38 const zone = yield* findZoneByName({ accountId, name: zoneName });
39 if (!zone) {
40 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
41 }
42 return zone;
43 });
44
45 /**
46 * Our affinity rules in the zone's late-transform phase entrypoint, as
47 * `{ description, expression, value }` (value = the header-value
48 * expression), sorted by description.
49 */
50 const listAffinityRules = Effect.fn(function* (zoneId: string, scriptName: string) {
51 const entrypoint = yield* rulesets
52 .getPhasForZone({ zoneId, rulesetPhase: "http_request_late_transform" })
53 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.succeed(undefined)));
54 return (entrypoint?.rules ?? [])
55 .flatMap((rule) => {
56 if (!(rule.description ?? "").startsWith(`alchemy:worker:${scriptName}:affinity`)) {
57 return [];
58 }
59 const headers =
60 "actionParameters" in rule
61 ? (
62 rule.actionParameters as
63 | { headers?: Record<string, unknown> | null }
64 | null
65 | undefined
66 )?.headers
67 : undefined;
68 const header = headers?.["Cloudflare-Workers-Version-Key"] as
69 | { expression?: unknown }
70 | undefined;
71 return [
72 {
73 description: rule.description as string,
74 expression: rule.expression ?? "",
75 value: typeof header?.expression === "string" ? header.expression : undefined,
76 },
77 ];
78 })
79 .sort((a, b) => a.description.localeCompare(b.description));
80 });
81
82 class DnsNotReady extends Data.TaggedError("DnsNotReady")<{ hostname: string }> {}
83
84 const DnsResponse = Schema.Struct({
85 Status: Schema.Number,
86 Answer: Schema.optional(
87 Schema.Array(Schema.Struct({ type: Schema.Number, data: Schema.String })),
88 ),
89 });
90
91 // Use public DNS answers for the socket lookup too: the OS can retain a
92 // negative answer from an earlier delete even after public DNS has converged.
93 const domainClient = Effect.fn(function* (hostname: string) {
94 const resolvers = ["https://1.1.1.1/dns-query", "https://dns.google/resolve"];
95 let attempt = 0;
96 const addresses = yield* Effect.suspend(() =>
97 HttpClient.get(resolvers[attempt++ % resolvers.length], {
98 headers: { accept: "application/dns-json" },
99 urlParams: { name: hostname, type: "A" },
100 }),
101 ).pipe(
102 Effect.flatMap(HttpClientResponse.schemaBodyJson(DnsResponse)),
103 Effect.flatMap((response) => {
104 const addresses = (response.Answer ?? [])
105 .filter((answer) => answer.type === 1)
106 .map((answer) => ({ address: answer.data, family: 4 }));
107 return response.Status === 0 && addresses.length > 0
108 ? Effect.succeed(addresses)
109 : Effect.fail(new DnsNotReady({ hostname }));
110 }),
111 Effect.retry({
112 while: (error) => error._tag === "DnsNotReady",
113 schedule: Schedule.spaced("5 seconds"),
114 times: 10,
115 }),
116 Effect.timeout("60 seconds"),
117 );
118 const agent = yield* NodeHttpClient.makeAgent({
119 lookup: (requestedHost, options, callback) => {
120 if (requestedHost !== hostname) {
121 callback(new Error(`Unexpected domain lookup: ${requestedHost}`), "");
122 } else if (options.all) {
123 callback(null, addresses);
124 } else {
125 callback(null, addresses[0].address, 4);
126 }
127 },
128 });
129 // Keep the hostname in the URL so TLS certificate and SNI checks stay intact.
130 return yield* NodeHttpClient.makeNodeHttp.pipe(
131 Effect.provideService(NodeHttpClient.HttpAgent, agent),
132 );
133 });
134
135 class BodyMismatch extends Data.TaggedError("BodyMismatch")<{ url: string; body: string }> {
136 override get message() {
137 return `unexpected body from ${this.url}: '${this.body}'`;
138 }
139 }
140
141 /**
142 * Fetch `url` (optionally with request headers) and assert the response
143 * body satisfies `check`, retried through DNS/certificate/edge propagation
144 * on a freshly attached custom domain.
145 */
146 const expectBody = Effect.fn(function* (
147 client: HttpClient.HttpClient,
148 url: string,
149 headers: Record<string, string>,
150 check: (body: string) => boolean,
151 retryDelay: Duration.Input = "1 second",
152 ) {
153 yield* client.get(url, { headers }).pipe(
154 Effect.flatMap((response) =>
155 response.text.pipe(
156 Effect.flatMap((body) =>
157 response.status === 200 && check(body)
158 ? Effect.void
159 : Effect.fail(new BodyMismatch({ url, body: `${response.status}: ${body}` })),
160 ),
161 ),
162 ),
163 Effect.timeout("5 seconds"),
164 Effect.retry({ schedule: Schedule.spaced(retryDelay), times: 10 }),
165 Effect.timeout("60 seconds"),
166 );
167 });
168
169 // These lifecycle tests mutate the same zone-level transform ruleset.
170 describe
171 .skipIf(!!process.env.FAST)
172 .sequential(
173 "Cloudflare.Worker version affinity",
174 { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"] },
175 () => {
176 test.provider(
177 "affinity rules converge across sources and clean up on destroy",
178 (stack) =>
179 Effect.gen(function* () {
180 const zone = yield* resolveZone;
181 const host = `wa-b-${suffix}.${zoneName}`;
182 const routeHost = `*.wa-rt-${suffix}.${zoneName}`;
183
184 yield* stack.destroy();
185
186 const deploy = (affinity: Cloudflare.WorkerVersionAffinity | undefined) =>
187 stack.deploy(
188 Effect.gen(function* () {
189 return yield* Cloudflare.Worker("AffinityWorker", {
190 script,
191 workersDev: false,
192 domain: host,
193 routes: [{ pattern: `${routeHost}/*` }],
194 version: { traffic: 50, affinity },
195 });
196 }),
197 );
198
199 // Sticky by session cookie, falling back to sticky IP: one rule
200 // per condition, scoped to this Worker's hostnames in the zone.
201 const v1 = yield* deploy({ cookie: "session_id", ip: true });
202 expect(v1.affinityZoneIds).toEqual([zone.id]);
203 const prefix = `alchemy:worker:${v1.workerName}:affinity`;
204 const hostExpr = `(http.host eq "${host}" or http.host wildcard "${routeHost}")`;
205 expect(yield* listAffinityRules(zone.id, v1.workerName)).toEqual([
206 {
207 description: `${prefix}:ip`,
208 expression: `${hostExpr} and not (len(http.request.cookies["session_id"]) > 0)`,
209 value: "to_string(ip.src)",
210 },
211 {
212 description: `${prefix}:key`,
213 expression: `${hostExpr} and len(http.request.cookies["session_id"]) > 0`,
214 value: `http.request.cookies["session_id"][0]`,
215 },
216 ]);
217
218 // The rule rewrites live zone traffic: the worker echoes the
219 // version-key header, so a request carrying the cookie echoes the
220 // cookie value and a bare request echoes the client IP.
221 const client = yield* domainClient(host);
222 yield* expectBody(
223 client,
224 `https://${host}`,
225 { cookie: "session_id=alchemy-test-key" },
226 (body) => body === "alchemy-test-key",
227 "5 seconds",
228 );
229 yield* expectBody(
230 client,
231 `https://${host}`,
232 {},
233 (body) => body !== "no-key" && /^[0-9a-fA-F.:]+$/.test(body),
234 );
235
236 // Switching the source converges in place: the header rule
237 // replaces the cookie rule and the IP fallback goes away.
238 const v2 = yield* deploy({ header: "X-User-Id" });
239 expect(v2.affinityZoneIds).toEqual([zone.id]);
240 expect(yield* listAffinityRules(zone.id, v2.workerName)).toEqual([
241 {
242 description: `${prefix}:key`,
243 expression: `${hostExpr} and len(http.request.headers["x-user-id"]) > 0`,
244 value: `http.request.headers["x-user-id"][0]`,
245 },
246 ]);
247
248 // Removing affinity removes the rules while the rollout continues.
249 const v3 = yield* deploy(undefined);
250 expect(v3.affinityZoneIds).toBeUndefined();
251 expect(yield* listAffinityRules(zone.id, v3.workerName)).toEqual([]);
252
253 // Re-add, then destroy — teardown must remove the rules too.
254 const v4 = yield* deploy({ cookie: "session_id" });
255 expect(yield* listAffinityRules(zone.id, v4.workerName)).toHaveLength(1);
256 yield* stack.destroy();
257 expect(yield* listAffinityRules(zone.id, v4.workerName)).toEqual([]);
258 }).pipe(logLevel),
259 { tags: ["provider:cloudflare:ruleset", "provider:cloudflare:zone"], timeout: 600_000 },
260 );
261
262 test.provider(
263 "rejects affinity on a workers.dev-only worker",
264 (stack) =>
265 Effect.gen(function* () {
266 yield* stack.destroy();
267
268 const error = yield* stack
269 .deploy(
270 Effect.gen(function* () {
271 return yield* Cloudflare.Worker("DevOnlyAffinity", {
272 script,
273 version: { traffic: 50, affinity: { cookie: "session_id" } },
274 });
275 }),
276 )
277 .pipe(Effect.flip);
278
279 expect(error).toBeInstanceOf(WorkerVersionConfigError);
280 expect(String(error)).toContain("zone Transform Rule");
281
282 yield* stack.destroy();
283 }).pipe(logLevel),
284 { timeout: 180_000 },
285 );
286
287 test.provider(
288 "a canary version worker pins users on the parent's zone",
289 (stack) =>
290 Effect.gen(function* () {
291 const zone = yield* resolveZone;
292 const host = `wa-p-${suffix}.${zoneName}`;
293
294 yield* stack.destroy();
295
296 const parentWorker = (marker: string) =>
297 Cloudflare.Worker("AffinityParent", {
298 script: `export default { fetch() { return new Response("${marker}"); } };`,
299 workersDev: false,
300 domain: host,
301 });
302
303 // Parent + canary in one stack: the canary carries the affinity,
304 // and the rule lands on the parent's zone under the parent's name.
305 const v1 = yield* stack.deploy(
306 Effect.gen(function* () {
307 const parent = yield* parentWorker("parent-v1");
308 const canary = yield* Cloudflare.Worker("AffinityCanary", {
309 script,
310 version: { parent, traffic: 25, affinity: { cookie: "session_id" } },
311 });
312 return { parent, canary };
313 }),
314 );
315 expect(v1.canary.affinityZoneIds).toEqual([zone.id]);
316 const rules = yield* listAffinityRules(zone.id, v1.parent.workerName);
317 expect(rules).toHaveLength(1);
318 expect(rules[0].description).toEqual(
319 `alchemy:worker:${v1.parent.workerName}:affinity:key`,
320 );
321 expect(rules[0].expression).toEqual(
322 `http.host eq "${host}" and len(http.request.cookies["session_id"]) > 0`,
323 );
324
325 // Releasing the canary deletes the version resource — its delete
326 // must also clear the rules it owned on the parent's zone.
327 const v2 = yield* stack.deploy(
328 Effect.gen(function* () {
329 const parent = yield* parentWorker("parent-v1");
330 return { parent };
331 }),
332 );
333 expect(yield* listAffinityRules(zone.id, v2.parent.workerName)).toEqual([]);
334
335 yield* stack.destroy();
336 }).pipe(logLevel),
337 { tags: ["provider:cloudflare:ruleset", "provider:cloudflare:zone"], timeout: 420_000 },
338 );
339 },
340 );