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

main
ts 233 lines 8.14 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 emailRouting from "@distilled.cloud/cloudflare/email-routing";
7 import * as Alchemy from "alchemy";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import EmailCatchAllWorker from "./fixtures/email-catchall-worker.ts";
13 import EmailTestWorker from "./fixtures/email-worker.ts";
14
15 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
16 providers: Cloudflare.providers(),
17 state: Cloudflare.state(),
18 });
19
20 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
21
22 const ZONE = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
23 const INBOX = process.env.CLOUDFLARE_TEST_EMAIL_INBOX || `inbox@${ZONE}`;
24 // The send→receive round trip additionally needs an outbound sender and a
25 // destination Cloudflare has verified; the deploy-time assertions below do
26 // not, so only the round trip is gated.
27 const skipRoundTrip = !process.env.CLOUDFLARE_TEST_EMAIL_FROM;
28
29 const Stack = Alchemy.Stack(
30 "EmailEventSourceStack",
31 {
32 providers: Cloudflare.providers(),
33 state: Cloudflare.state(),
34 },
35 Effect.gen(function* () {
36 const worker = yield* EmailTestWorker;
37 return {
38 url: worker.url.as<string>(),
39 workerName: worker.workerName,
40 };
41 }),
42 );
43
44 const stack = beforeAll(deploy(Stack));
45 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
46
47 // The scoped API token the test harness mints propagates eventually-
48 // consistently across Cloudflare's edge — a fresh token intermittently 403s.
49 const rideOutAuth = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
50 effect.pipe(
51 Effect.retry({
52 while: (e) => e._tag === "Forbidden" || e._tag === "Unauthorized",
53 schedule: Schedule.exponential("500 millis"),
54 times: 8,
55 }),
56 );
57
58 const resolveZoneId = Effect.gen(function* () {
59 const { accountId } = yield* yield* CloudflareEnvironment;
60 const zone = yield* findZoneByName({ accountId, name: ZONE });
61 if (!zone) {
62 return yield* Effect.die(new Error(`zone "${ZONE}" not found in account`));
63 }
64 return zone.id;
65 });
66
67 // The deploy-time half of the event source: `email({ zone, matchers })`
68 // yields an `Email.Routing` toggle and an `Email.Rule` whose action targets
69 // the host Worker. Neither needs mail to flow, so this runs everywhere.
70 test.provider(
71 "subscribe auto-creates Email.Routing and an Email.Rule targeting the worker",
72 () =>
73 Effect.gen(function* () {
74 const { workerName } = yield* stack;
75 const zoneId = yield* resolveZoneId;
76
77 const routing = yield* rideOutAuth(emailRouting.getEmailRouting({ zoneId }));
78 expect(routing.enabled).toBe(true);
79
80 const rules = yield* rideOutAuth(emailRouting.listRules({ zoneId }));
81 const ours = (rules.result ?? []).find((rule) =>
82 (rule.actions ?? []).some(
83 (a) => a.type === "worker" && (a.value ?? []).includes(workerName),
84 ),
85 );
86 expect(ours).toBeDefined();
87 expect(ours!.enabled).toBe(true);
88 expect(ours!.matchers).toEqual([{ type: "literal", field: "to", value: INBOX }]);
89 }).pipe(logLevel),
90 {
91 tags: [
92 "provider:cloudflare",
93 "provider:cloudflare:email",
94 "provider:cloudflare:worker",
95 "provider:cloudflare:zone",
96 "live",
97 ],
98 timeout: 180_000,
99 },
100 );
101
102 test.skipIf(skipRoundTrip)(
103 "deployed worker receives inbound mail routed by the auto-created Email.Rule",
104 Effect.gen(function* () {
105 const { url } = yield* stack;
106 const client = yield* HttpClient.HttpClient;
107
108 // Reset DO state and double as a readiness probe — fresh workers.dev
109 // URLs take a few seconds to start serving 200s.
110 yield* Effect.gen(function* () {
111 const res = yield* client.post(`${url}/reset`);
112 if (res.status !== 200) {
113 return yield* Effect.fail(new Error(`Worker not ready: ${res.status}`));
114 }
115 }).pipe(
116 Effect.retry({
117 schedule: Schedule.exponential("500 millis"),
118 times: 10,
119 }),
120 );
121 const resetAt = Date.now();
122
123 // Send a unique-subject message via the worker's send_email binding.
124 const subject = `alchemy email test ${resetAt}`;
125 const sendUrl = `${url}/send?subject=${encodeURIComponent(subject)}`;
126 yield* Effect.gen(function* () {
127 const res = yield* client.post(sendUrl);
128 if (res.status !== 200) {
129 return yield* Effect.fail(new Error(`/send failed: ${res.status}`));
130 }
131 const body = (yield* res.json) as { ok: boolean; message?: string };
132 if (!body.ok) {
133 return yield* Effect.fail(new Error(`send_email failed: ${body.message}`));
134 }
135 }).pipe(
136 Effect.retry({
137 schedule: Schedule.exponential("500 millis"),
138 times: 5,
139 }),
140 );
141
142 // Cloudflare's email pipeline is async — the inbound dispatch typically
143 // lands within ~30s but can take longer under load.
144 const received = yield* Effect.gen(function* () {
145 const res = yield* client.get(`${url}/received`);
146 if (res.status !== 200) return [];
147 const body = (yield* res.json) as { received?: unknown };
148 if (!Array.isArray(body.received)) return [];
149 return body.received.filter(
150 (r): r is { subject: string | null; receivedAt: number } =>
151 typeof r === "object" && r !== null && (r as { subject?: unknown }).subject === subject,
152 );
153 }).pipe(
154 Effect.catch(() => Effect.succeed([])),
155 Effect.repeat({
156 schedule: Schedule.spaced("5 seconds"),
157 until: (matches) => matches.length > 0,
158 times: 48,
159 }),
160 );
161
162 expect(received.length).toBeGreaterThan(0);
163 for (const msg of received) {
164 expect(msg.subject).toBe(subject);
165 expect(msg.receivedAt).toBeGreaterThanOrEqual(resetAt);
166 }
167 }).pipe(logLevel),
168 {
169 tags: [
170 "provider:cloudflare",
171 "provider:cloudflare:email",
172 "provider:cloudflare:worker",
173 "live",
174 ],
175 timeout: 360_000,
176 },
177 );
178
179 // The catch-all form: `email({ zone })` with no matchers. Cloudflare
180 // rejects a lone `{ type: "all" }` matcher on `createRule` with
181 // "Invalid rule operation", so this stack only deploys at all if the
182 // event source provisions `Email.CatchAll` instead of `Email.Rule`.
183 const CatchAllStack = Alchemy.Stack(
184 "EmailEventSourceCatchAllStack",
185 {
186 providers: Cloudflare.providers(),
187 state: Cloudflare.state(),
188 },
189 Effect.gen(function* () {
190 const worker = yield* EmailCatchAllWorker;
191 return { workerName: worker.workerName };
192 }),
193 );
194
195 const catchAllStack = beforeAll(deploy(CatchAllStack));
196 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(CatchAllStack));
197
198 test.provider(
199 "a catch-all subscription provisions Email.CatchAll, not an Email.Rule",
200 () =>
201 Effect.gen(function* () {
202 const { workerName } = yield* catchAllStack;
203 const zoneId = yield* resolveZoneId;
204
205 // The zone's catch-all singleton now points at the worker.
206 const catchAll = yield* rideOutAuth(emailRouting.getRuleCatchAll({ zoneId }));
207 expect(catchAll.enabled).toBe(true);
208 expect(catchAll.actions?.[0]?.type).toEqual("worker");
209 expect(catchAll.actions?.[0]?.value).toEqual([workerName]);
210
211 // ...and no ordinary rule was created for it. `listRules` surfaces
212 // the catch-all too, so exclude it by id rather than by matcher.
213 const rules = yield* rideOutAuth(emailRouting.listRules({ zoneId }));
214 const strays = (rules.result ?? [])
215 .filter((r) => r.id !== catchAll.id)
216 .filter((r) =>
217 (r.actions ?? []).some(
218 (a) => a.type === "worker" && (a.value ?? []).includes(workerName),
219 ),
220 );
221 expect(strays).toEqual([]);
222 }).pipe(logLevel),
223 {
224 tags: [
225 "provider:cloudflare",
226 "provider:cloudflare:email",
227 "provider:cloudflare:worker",
228 "provider:cloudflare:zone",
229 "live",
230 ],
231 timeout: 180_000,
232 },
233 );