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

main
ts 225 lines 8.36 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Path from "effect/Path";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as pathe from "pathe";
13
14 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
15 // matching the process topology of the real `alchemy dev` command (see
16 // MakeOptions.sidecar in Test/Core.ts).
17 const { test } = Test.make({
18 providers: Cloudflare.providers(),
19 dev: true,
20 });
21
22 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
23
24 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
25 status: number;
26 }> {}
27
28 const getReady = (url: string) =>
29 Effect.gen(function* () {
30 const client = yield* HttpClient.HttpClient;
31 return yield* client.get(url).pipe(
32 Effect.flatMap((res) =>
33 res.status === 200
34 ? Effect.succeed(res)
35 : Effect.fail(new WorkerNotReady({ status: res.status })),
36 ),
37 Effect.retry({
38 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
39 // Cap the backoff: an uncapped exponential over 10 recurs sums to
40 // ~8.5 minutes and turns a persistent non-200 into an apparent hang.
41 schedule: Schedule.max([
42 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
43 Schedule.recurs(10),
44 ]),
45 }),
46 );
47 }).pipe(Effect.orDie);
48
49 // -----------------------------------------------------------------------------
50 // MIME fixtures — hard-coded constants mirroring the runtime's own inbound
51 // email tests (\n line endings; the parser accepts both \n and \r\n).
52 // -----------------------------------------------------------------------------
53
54 const FROM = "someone@example.com";
55 const TO = "someone-else@example.com";
56
57 const emailFixture = (headers: Array<string>) =>
58 [
59 ...headers,
60 "MIME-Version: 1.0",
61 "Content-Type: text/plain",
62 "",
63 "This is a random email body.",
64 ].join("\n");
65
66 const incomingEmail = (subject: string, messageId: string) =>
67 emailFixture([
68 `From: someone <${FROM}>`,
69 `To: someone else <${TO}>`,
70 `Subject: ${subject}`,
71 `Message-ID: ${messageId}`,
72 ]);
73
74 const emailTriggerPath = (workerUrl: string) =>
75 `${workerUrl}/cdn-cgi/handler/email?from=${encodeURIComponent(FROM)}&to=${encodeURIComponent(TO)}`;
76
77 /** POST a raw MIME message to the worker's inbound email trigger route. */
78 const postEmail = (workerUrl: string, raw: string) =>
79 Effect.gen(function* () {
80 const client = yield* HttpClient.HttpClient;
81 return yield* client.execute(
82 HttpClientRequest.post(emailTriggerPath(workerUrl)).pipe(HttpClientRequest.bodyText(raw)),
83 );
84 });
85
86 interface ReceivedEmail {
87 from: string;
88 to: string;
89 rawSize: number;
90 raw: string;
91 subject: string;
92 messageIdHeader: string | null;
93 }
94
95 class EmlNotFound extends Data.TaggedError("EmlNotFound")<{
96 directory: string;
97 }> {}
98
99 /**
100 * Find the persisted reply `.eml` under the local runtime storage directory
101 * (`.alchemy/local/email`) whose content carries `marker`. Bounded poll: the
102 * write happens before `reply()` resolves, but the simulator runs in the
103 * sidecar process, so allow a few refresh rounds.
104 */
105 const findEmlWithMarker = (marker: string) =>
106 Effect.gen(function* () {
107 const fs = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const cwd = yield* Effect.sync(() => process.cwd());
110 const emailDir = path.join(cwd, ".alchemy", "local", "email");
111 const files = yield* fs
112 .readDirectory(emailDir)
113 .pipe(Effect.orElseSucceed(() => [] as Array<string>));
114 for (const name of files) {
115 if (!name.endsWith(".eml")) continue;
116 const content = yield* fs
117 .readFileString(path.join(emailDir, name))
118 .pipe(Effect.orElseSucceed(() => ""));
119 if (content.includes(`reply-marker:${marker}`)) {
120 return content;
121 }
122 }
123 return yield* new EmlNotFound({ directory: emailDir });
124 }).pipe(
125 Effect.retry({
126 while: (e): e is EmlNotFound => e instanceof EmlNotFound,
127 schedule: Schedule.spaced("500 millis"),
128 times: 10,
129 }),
130 );
131
132 /**
133 * Under `alchemy dev` the local runtime dispatches
134 * `POST {workerUrl}/cdn-cgi/handler/email?from=X&to=Y` (raw MIME body) to
135 * the worker's `email()` handler — mirroring Miniflare's inbound email
136 * trigger route. This exercises the full local roundtrip: dispatch (200),
137 * `setReject` (400 with the reason), and `message.reply(...)` persisting the
138 * reply `.eml` under the local storage's `email/` dir.
139 */
140 test.provider(
141 "inbound email trigger dispatches to the worker's email() handler",
142 (stack) =>
143 Effect.gen(function* () {
144 yield* stack.destroy();
145
146 const deployed = yield* stack.deploy(
147 Effect.gen(function* () {
148 const kv = yield* Cloudflare.KV.Namespace("EmailHandlerKV");
149 const worker = yield* Cloudflare.Worker("email-handler-worker", {
150 main: pathe.resolve(import.meta.dirname, "fixtures/email-handler-worker.ts"),
151 env: { KV: kv },
152 });
153 return { worker };
154 }),
155 );
156
157 // The worker serves from the local dev proxy — proof no deployment to
158 // Cloudflare happened.
159 expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
160
161 // Wait for the local worker to serve before driving the trigger route.
162 yield* getReady(deployed.worker.url!);
163
164 const marker = yield* Effect.sync(() => crypto.randomUUID());
165
166 // 1. Accepted email → 200, and the handler observed the envelope
167 // addresses, the raw MIME content, and the parsed headers.
168 const okRaw = incomingEmail(`accept-me:${marker}`, `<incoming-${marker}@example.com>`);
169 const okRes = yield* postEmail(deployed.worker.url!, okRaw);
170 expect(okRes.status).toBe(200);
171 expect(yield* okRes.text).toBe("Worker successfully processed email");
172
173 const received = (yield* (yield* getReady(`${deployed.worker.url}/received`))
174 .json) as unknown as Array<ReceivedEmail>;
175 expect(received).toHaveLength(1);
176 const message = received[0];
177 // Envelope addresses come from the URL parameters, the raw MIME body
178 // and parsed headers from the request body.
179 expect(message.from).toBe(FROM);
180 expect(message.to).toBe(TO);
181 expect(message.subject).toBe(`accept-me:${marker}`);
182 expect(message.raw).toBe(okRaw);
183 expect(message.rawSize).toBe(new TextEncoder().encode(okRaw).byteLength);
184 expect(message.messageIdHeader).toBe(`<incoming-${marker}@example.com>`);
185
186 // 2. `setReject(reason)` → 400 carrying the reject reason.
187 const rejectRes = yield* postEmail(
188 deployed.worker.url!,
189 incomingEmail("reject-me", `<reject-${marker}@example.com>`),
190 );
191 expect(rejectRes.status).toBe(400);
192 expect(yield* rejectRes.text).toBe(
193 "Worker rejected email with the following reason: I don't like this email",
194 );
195
196 // 3. `message.reply(new EmailMessage(...))` → 200, and the reply `.eml`
197 // is persisted under the local storage's `email/` dir with the
198 // generated `References` header pointing at the incoming message.
199 const replyRes = yield* postEmail(
200 deployed.worker.url!,
201 incomingEmail(`reply-me:${marker}`, `<parent-${marker}@example.com>`),
202 );
203 expect(replyRes.status).toBe(200);
204 expect(yield* replyRes.text).toBe("Worker successfully processed email");
205
206 const eml = yield* findEmlWithMarker(marker);
207 // The reply had no References header, so the runtime prepends one
208 // referencing the incoming message before persisting.
209 expect(eml).toContain(`References: <parent-${marker}@example.com>`);
210 expect(eml).toContain(`In-Reply-To: <parent-${marker}@example.com>`);
211 expect(eml).toContain(`Message-ID: <reply-${marker}@example.com>`);
212
213 yield* stack.destroy();
214 }).pipe(logLevel),
215 {
216 tags: [
217 "provider:cloudflare",
218 "provider:cloudflare:email",
219 "provider:cloudflare:kv",
220 "provider:cloudflare:worker",
221 "local",
222 ],
223 timeout: 180_000,
224 },
225 );