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

main
ts 955 lines 33.4 KB
Raw
1 import { expect } from "bun:test";
2 import assert from "node:assert";
3 import * as fs from "node:fs";
4 import * as path from "node:path";
5 import * as Cloudflare from "@alchemy.run/cloudflare";
6 import * as Test from "@alchemy.run/test/Bun";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { cast } from "effect/Function";
10 import * as HttpBody from "effect/http/HttpBody";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as HttpClientResponse from "effect/http/HttpClientResponse";
13 import * as Schedule from "effect/Schedule";
14 import * as Schema from "effect/Schema";
15 import Stack, { SECRETS_STORE_VALUE } from "../alchemy.run.ts";
16 import type { Message } from "../src/AsyncWorker.ts";
17 import { WORKFLOW_SECRET_VALUE } from "../src/NotifyWorkflow.ts";
18
19 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
20 providers: Cloudflare.providers(),
21 state: Cloudflare.state(),
22 dev: true,
23 });
24
25 const stack = beforeAll(
26 deploy(Stack).pipe(
27 Effect.flatMap(
28 Effect.fn(function* (outputs) {
29 const {
30 asyncWorker,
31 effectWorker,
32 mediaWorker,
33 tailWorker,
34 inboxWorker,
35 liveKvNamespaceId,
36 secretsStoreId,
37 secretsSecretId,
38 } = outputs;
39 assert(typeof asyncWorker === "string");
40 assert(typeof effectWorker === "string");
41 assert(typeof mediaWorker === "string");
42 assert(typeof tailWorker === "string");
43 assert(typeof inboxWorker === "string");
44 assert(typeof liveKvNamespaceId === "string");
45 assert(typeof secretsStoreId === "string");
46 assert(typeof secretsSecretId === "string");
47 const hyperdrive = (outputs as { hyperdrive?: string }).hyperdrive;
48 yield* Effect.forEach(
49 [asyncWorker, effectWorker, mediaWorker, tailWorker, inboxWorker],
50 (url) =>
51 HttpClient.get(url).pipe(
52 Effect.flatMap(HttpClientResponse.filterStatusOk),
53 Effect.retry({
54 schedule: Schedule.max([Schedule.spaced("250 millis"), Schedule.recurs(40)]),
55 }),
56 ),
57 );
58 return {
59 asyncWorker,
60 effectWorker,
61 mediaWorker,
62 tailWorker,
63 inboxWorker,
64 liveKvNamespaceId,
65 secretsStoreId,
66 secretsSecretId,
67 hyperdrive,
68 };
69 }),
70 ),
71 ),
72 { timeout: 300_000 },
73 );
74
75 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
76
77 class NotYet extends Data.TaggedError("NotYet")<{ status?: number }> {}
78
79 /**
80 * GET a route, retrying while it serves a non-200 — used for routes whose
81 * first request does heavy lazy work (launching Chrome, warming sharp).
82 */
83 const getJsonReady = (
84 url: string | URL,
85 {
86 times = 10,
87 spaced = "2 seconds",
88 }: { times?: number; spaced?: `${number} ${"millis" | "seconds"}` } = {},
89 ) =>
90 Effect.gen(function* () {
91 const res = yield* HttpClient.get(url);
92 if (res.status !== 200) {
93 return yield* Effect.fail(new NotYet({ status: res.status }));
94 }
95 return yield* res.json;
96 }).pipe(
97 Effect.retry({
98 while: (e) => e._tag === "NotYet",
99 schedule: Schedule.max([Schedule.spaced(spaced), Schedule.recurs(times)]),
100 }),
101 );
102
103 /** 8x4 solid red PNG (checked-in fixture — never generated at test time). */
104 const PNG_RED_8X4 = Uint8Array.from(
105 Buffer.from(
106 "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAECAIAAAA8r+mnAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAEklEQVR4nGP4z8CAFWEXJUsCAFpeH+EeQoQoAAAAAElFTkSuQmCC",
107 "base64",
108 ),
109 );
110
111 /**
112 * Find a persisted `.eml` under the local email storage dir whose content
113 * carries `needle`. The simulator writes relative to the process cwd, so
114 * check both the example dir and the current cwd.
115 */
116 class EmlNotFound extends Data.TaggedError("EmlNotFound")<{}> {}
117 const findEmlContaining = (needle: string) =>
118 Effect.sync(() => {
119 const candidates = [
120 path.resolve(import.meta.dirname, "..", ".alchemy", "local", "email"),
121 path.resolve(process.cwd(), ".alchemy", "local", "email"),
122 ];
123 for (const dir of candidates) {
124 let files: string[];
125 try {
126 files = fs.readdirSync(dir);
127 } catch {
128 continue;
129 }
130 for (const name of files) {
131 if (!name.endsWith(".eml")) continue;
132 const content = fs.readFileSync(path.join(dir, name), "utf8");
133 if (content.includes(needle)) return content;
134 }
135 }
136 return undefined;
137 }).pipe(
138 Effect.flatMap((content) =>
139 content === undefined ? Effect.fail(new EmlNotFound({})) : Effect.succeed(content),
140 ),
141 Effect.retry({
142 while: (e) => e._tag === "EmlNotFound",
143 schedule: Schedule.max([Schedule.spaced("500 millis"), Schedule.recurs(20)]),
144 }),
145 );
146
147 test(
148 "deploys all workers with URLs",
149 Effect.gen(function* () {
150 const { asyncWorker, effectWorker, mediaWorker, tailWorker, inboxWorker } = yield* stack;
151
152 // Local dev proxy URLs — proof no cloud deploy ran for the workers.
153 for (const url of [asyncWorker, effectWorker, mediaWorker, tailWorker, inboxWorker]) {
154 expect(url).toBeString();
155 expect(url).toMatch(/^http:\/\/localhost:\d+/);
156 }
157 }),
158 );
159
160 /**
161 * AsyncWorker exports a default fetch handler that calls the `Counter`
162 * Durable Object's `increment()` and returns `Hello, world! <n>`.
163 *
164 * Hitting the worker twice exercises the DO end-to-end and proves
165 * persistent state across requests — if the DO binding is missing or
166 * the class export is wrong, the first request fails outright.
167 */
168 test(
169 "AsyncWorker increments the Counter Durable Object across requests",
170 Effect.gen(function* () {
171 const { asyncWorker } = yield* stack;
172
173 const first = yield* HttpClient.get(new URL("/counter", asyncWorker));
174 expect(first.status).toBe(200);
175 const firstBody = yield* first.text;
176 const firstMatch = firstBody.match(/^Hello, world! (\d+)$/);
177 expect(firstMatch).not.toBeNull();
178 const firstCount = Number(firstMatch![1]);
179
180 const second = yield* HttpClient.get(new URL("/counter", asyncWorker));
181 expect(second.status).toBe(200);
182 const secondBody = yield* second.text;
183 const secondMatch = secondBody.match(/^Hello, world! (\d+)$/);
184 expect(secondMatch).not.toBeNull();
185 const secondCount = Number(secondMatch![1]);
186
187 expect(secondCount).toBe(firstCount + 1);
188 }),
189 );
190
191 /**
192 * Under `dev: true` the R2 bucket is emulated by the local provider and the
193 * `r2_bucket` binding is served by the local workerd R2 simulator — no cloud
194 * bucket is ever created.
195 */
196 test(
197 "AsyncWorker reads and writes the local R2 bucket",
198 Effect.gen(function* () {
199 const { asyncWorker } = yield* stack;
200 const response = yield* HttpClient.get(new URL("/r2", asyncWorker));
201 expect(response.status).toBe(200);
202 const body = (yield* response.json) as { text: string; keys: string[] };
203 expect(body.text).toBe("hello from r2");
204 expect(body.keys).toContain("hello.txt");
205 }),
206 );
207
208 /**
209 * Same for D1: the database is a local `dev:` row and queries run against
210 * the local workerd D1 simulator (DO SQLite).
211 */
212 test(
213 "AsyncWorker queries the local D1 database",
214 Effect.gen(function* () {
215 const { asyncWorker } = yield* stack;
216 const response = yield* HttpClient.get(new URL("/d1", asyncWorker));
217 expect(response.status).toBe(200);
218 const body = (yield* response.json) as { text: string | null };
219 expect(body.text).toBe("hello from d1");
220 }),
221 );
222
223 test(
224 "AsyncWorker serves assets",
225 Effect.gen(function* () {
226 const { asyncWorker } = yield* stack;
227 const response = yield* HttpClient.get(new URL("/", asyncWorker));
228 expect(response.status).toBe(200);
229 const body = yield* response.text;
230 expect(body).toMatch("<h1>Hello, world!</h1>");
231 }),
232 );
233
234 test(
235 "AsyncWorker receives bindings, including variables and secrets",
236 Effect.gen(function* () {
237 const { asyncWorker } = yield* stack;
238 const response = yield* HttpClient.get(new URL("/env", asyncWorker));
239 expect(response.status).toBe(200);
240 const body = yield* response.json;
241 expect(body).toMatchObject({
242 MY_SECRET: "my-secret-abc123",
243 MY_VARIABLE: "my-variable-abc123",
244 COUNTER: {},
245 });
246 }),
247 );
248
249 /**
250 * `env: { PUBLIC_URL: Cloudflare.Worker.URL }` lowers the `self_url`
251 * sentinel to a plain-text binding holding the worker's own URL. Under the
252 * local provider (this suite runs with `dev: true`) that URL is the dev
253 * proxy's address, resolved before workerd starts. The binding value has no
254 * trailing slash; the stack's URL output does — normalize before comparing.
255 */
256 test(
257 "AsyncWorker receives its own URL via env: { PUBLIC_URL: Worker.URL }",
258 Effect.gen(function* () {
259 const { asyncWorker } = yield* stack;
260 const response = yield* HttpClient.get(new URL("/env", asyncWorker));
261 expect(response.status).toBe(200);
262 const body = (yield* response.json) as { PUBLIC_URL: string };
263 expect(body.PUBLIC_URL).toBe(asyncWorker.replace(/\/$/, ""));
264 }),
265 );
266
267 /**
268 * The Effect-native form: `yield* Cloudflare.Worker.URL` at init attaches
269 * the `self_url` binding and returns a deferred accessor the handler reads
270 * at request time.
271 */
272 test(
273 "EffectWorker reads its own URL via yield* Worker.URL",
274 Effect.gen(function* () {
275 const { effectWorker } = yield* stack;
276 const response = yield* HttpClient.get(new URL("/url", effectWorker));
277 expect(response.status).toBe(200);
278 const body = (yield* response.json) as { url: string };
279 expect(body.url).toBe(effectWorker.replace(/\/$/, ""));
280 }),
281 );
282
283 test(
284 "AsyncWorker sends and receives messages on the queue",
285 Effect.gen(function* () {
286 const { asyncWorker } = yield* stack;
287 const body = { text: "hello", sentAt: Date.now() };
288 yield* HttpClient.post(new URL("/queue/send", asyncWorker), {
289 body: yield* HttpBody.json(body),
290 }).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
291 const message = yield* HttpClient.get(new URL("/queue/messages", asyncWorker)).pipe(
292 Effect.flatMap(HttpClientResponse.filterStatusOk),
293 Effect.flatMap((res) => res.json),
294 Effect.map(cast<Schema.Json, Array<Message>>),
295 Effect.map((messages) => messages.find((m) => m.body.sentAt === body.sentAt)),
296 Effect.filterOrFail(
297 (message) => message !== undefined,
298 () => ({ _tag: "MessageNotFound" }) as const,
299 ),
300 Effect.retry({
301 while: (error) => error._tag === "MessageNotFound",
302 schedule: Schedule.max([Schedule.spaced("250 millis"), Schedule.recurs(25)]),
303 }),
304 );
305 expect(message).toMatchObject({
306 id: expect.any(String),
307 body,
308 });
309 }),
310 { timeout: 10_000 },
311 );
312
313 /**
314 * EffectWorker binds a KV namespace via `Cloudflare.KV.ReadWriteNamespace(KV)`
315 * and returns the result of `kv.list()` as JSON. A successful response
316 * proves the Effect-style binding wired the runtime SDK and the
317 * `WorkerEnvironment` service was provisioned for the fetch handler.
318 */
319 test(
320 "EffectWorker returns a KV list result via the Effect KV binding",
321 Effect.gen(function* () {
322 const { effectWorker } = yield* stack;
323
324 const response = yield* HttpClient.get(effectWorker);
325 expect(response.status).toBe(200);
326
327 const body = (yield* response.json) as {
328 keys: Array<{ name: string }>;
329 list_complete: boolean;
330 };
331 expect(Array.isArray(body.keys)).toBe(true);
332 expect(typeof body.list_complete).toBe("boolean");
333 }),
334 );
335
336 test(
337 "EffectWorker sends and receives messages on the queue",
338 Effect.gen(function* () {
339 const { effectWorker } = yield* stack;
340 const body = { text: "hello", sentAt: Date.now() };
341 yield* HttpClient.post(new URL("/queue/send", effectWorker), {
342 body: yield* HttpBody.json(body),
343 }).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
344 const message = yield* HttpClient.get(new URL("/queue/messages", effectWorker)).pipe(
345 Effect.flatMap(HttpClientResponse.filterStatusOk),
346 Effect.flatMap((res) => res.json),
347 Effect.map(cast<Schema.Json, Array<Message>>),
348 Effect.map((messages) => messages.find((m) => m.body.sentAt === body.sentAt)),
349 Effect.filterOrFail(
350 (message) => message !== undefined,
351 () => ({ _tag: "MessageNotFound" }) as const,
352 ),
353 Effect.retry({
354 while: (error) => error._tag === "MessageNotFound",
355 schedule: Schedule.max([Schedule.spaced("250 millis"), Schedule.recurs(25)]),
356 }),
357 );
358 expect(message).toMatchObject({
359 id: expect.any(String),
360 body,
361 });
362 }),
363 { timeout: 10_000 },
364 );
365
366 /**
367 * Both workers import `./modules/wasm-example.wasm`, which exports a
368 * single `add(a: number, b: number): number` function. Hitting `/wasm`
369 * instantiates the module and returns `add(3, 4)` as JSON, proving that
370 * the bundler ships the wasm asset to workerd and that runtime
371 * `WebAssembly.instantiate` works for both the raw async-handler and
372 * Effect-style entrypoints.
373 */
374 test(
375 "AsyncWorker /wasm instantiates the wasm module and returns add(3, 4)",
376 Effect.gen(function* () {
377 const { asyncWorker } = yield* stack;
378
379 const response = yield* HttpClient.get(new URL("/wasm", asyncWorker));
380 expect(response.status).toBe(200);
381 const body = (yield* response.json) as { result: number };
382 expect(body.result).toBe(7);
383 }),
384 );
385
386 test(
387 "EffectWorker /wasm instantiates the wasm module and returns add(3, 4)",
388 Effect.gen(function* () {
389 const { effectWorker } = yield* stack;
390
391 const response = yield* HttpClient.get(new URL("/wasm", effectWorker));
392 expect(response.status).toBe(200);
393 const body = (yield* response.json) as { result: number };
394 expect(body.result).toBe(7);
395 }),
396 );
397
398 /**
399 * Cache API: the local runtime ships an always-on `caches.default`
400 * simulator persisted under `.alchemy/local`. A per-run key keeps the
401 * first request a deterministic miss even though the storage survives
402 * across runs.
403 */
404 test(
405 "AsyncWorker caches responses with the Cache API (miss then hit)",
406 Effect.gen(function* () {
407 const { asyncWorker } = yield* stack;
408 const key = crypto.randomUUID();
409
410 const first = (yield* (yield* HttpClient.get(new URL(`/cache?key=${key}`, asyncWorker)))
411 .json) as { hit: boolean; body: string };
412 expect(first.hit).toBe(false);
413 expect(first.body).toBe("cached-body");
414
415 const second = (yield* (yield* HttpClient.get(new URL(`/cache?key=${key}`, asyncWorker)))
416 .json) as { hit: boolean; body: string };
417 expect(second.hit).toBe(true);
418 expect(second.body).toBe("cached-body");
419 }),
420 );
421
422 /**
423 * Rate limit binding: THROTTLE allows 2 requests per 10s per key. The local
424 * runtime implements real throttling (not a stub), so the third call with
425 * the same (per-run) key observes `success: false`.
426 */
427 test(
428 "AsyncWorker rate limit binding throttles the third call",
429 Effect.gen(function* () {
430 const { asyncWorker } = yield* stack;
431 const key = crypto.randomUUID();
432 const url = new URL(`/ratelimit?key=${key}`, asyncWorker);
433
434 const outcomes: boolean[] = [];
435 for (let i = 0; i < 3; i++) {
436 const res = yield* HttpClient.get(url);
437 expect(res.status).toBe(200);
438 const body = (yield* res.json) as { success: boolean };
439 outcomes.push(body.success);
440 }
441 expect(outcomes).toEqual([true, true, false]);
442 }),
443 );
444
445 /**
446 * Version metadata binding: locally stubbed with a random `id` (and empty
447 * `tag`), matching the production binding's shape.
448 */
449 test(
450 "AsyncWorker exposes version metadata",
451 Effect.gen(function* () {
452 const { asyncWorker } = yield* stack;
453 const response = yield* HttpClient.get(new URL("/version", asyncWorker));
454 expect(response.status).toBe(200);
455 const body = (yield* response.json) as { id: string };
456 expect(typeof body.id).toBe("string");
457 expect(body.id.length).toBeGreaterThan(0);
458 }),
459 );
460
461 /**
462 * Service binding (worker → worker): AsyncWorker's `/service` route calls
463 * the Effect-native worker's `/url` route through `env.SERVICE.fetch` — no
464 * public hop. In local dev this resolves through the dev registry, which
465 * may pick a fresh peer up asynchronously — hence the bounded retry.
466 */
467 test(
468 "AsyncWorker calls EffectWorker through a service binding",
469 Effect.gen(function* () {
470 const { asyncWorker, effectWorker } = yield* stack;
471 const body = (yield* getJsonReady(new URL("/service", asyncWorker))) as {
472 url: string;
473 };
474 expect(body.url).toBe(effectWorker.replace(/\/$/, ""));
475 }),
476 { timeout: 60_000 },
477 );
478
479 /**
480 * tailConsumers: AsyncWorker lists TailWorker as a tail consumer, so every
481 * invocation delivers a trace batch (outcome + console logs) to its `tail()`
482 * handler, which records into KV. Each poll re-invokes the producer so an
483 * early dropped batch (registry still warming) doesn't strand the test.
484 */
485 test(
486 "TailWorker receives AsyncWorker's trace batches",
487 Effect.gen(function* () {
488 const { asyncWorker, tailWorker } = yield* stack;
489
490 const batches = yield* Effect.gen(function* () {
491 yield* HttpClient.get(new URL("/tail-ping", asyncWorker)).pipe(
492 Effect.flatMap((res) => res.text),
493 Effect.orDie,
494 );
495 const res = yield* HttpClient.get(new URL("/events", tailWorker));
496 if (res.status !== 200) return [] as string[];
497 const body = (yield* res.json) as { batches?: unknown };
498 return Array.isArray(body.batches) ? (body.batches as string[]) : [];
499 }).pipe(
500 Effect.repeat({
501 schedule: Schedule.spaced("1 second"),
502 until: (batches): boolean =>
503 batches.some((batch) => batch.includes("cloudflare-dev-tail-marker")),
504 times: 20,
505 }),
506 );
507
508 const batch = batches.find((b) => b.includes("cloudflare-dev-tail-marker"));
509 expect(batch).toBeDefined();
510 const items = JSON.parse(batch!) as {
511 logs?: { message?: unknown[] }[];
512 }[];
513 expect(
514 items.some((item) =>
515 item.logs?.some((log) => log.message?.includes("cloudflare-dev-tail-marker")),
516 ),
517 ).toBe(true);
518 }),
519 { timeout: 60_000 },
520 );
521
522 /**
523 * Cron trigger: EffectWorker registers `cron("* * * * *", ...)` at init.
524 * Locally the fire is driven on demand via the `/cdn-cgi/handler/scheduled`
525 * trigger route (never wait for the minute boundary); the handler records
526 * `controller.scheduledTime` into a DO which `/cron/times` exposes.
527 */
528 test(
529 "EffectWorker cron handler fires via the scheduled trigger route",
530 Effect.gen(function* () {
531 const { effectWorker } = yield* stack;
532
533 const scheduledTime = Date.now();
534 const trigger = yield* HttpClient.post(
535 new URL(
536 `/cdn-cgi/handler/scheduled?cron=${encodeURIComponent("* * * * *")}&time=${scheduledTime}`,
537 effectWorker,
538 ),
539 );
540 expect(trigger.status).toBe(200);
541 expect(yield* trigger.text).toBe("ok");
542
543 const times = yield* Effect.gen(function* () {
544 const res = yield* HttpClient.get(new URL("/cron/times", effectWorker));
545 if (res.status !== 200) return [] as number[];
546 const body = (yield* res.json) as { times?: unknown };
547 return Array.isArray(body.times) ? (body.times as number[]) : [];
548 }).pipe(
549 Effect.repeat({
550 schedule: Schedule.spaced("500 millis"),
551 until: (times): boolean => times.includes(scheduledTime),
552 times: 20,
553 }),
554 );
555 expect(times).toContain(scheduledTime);
556 }),
557 { timeout: 60_000 },
558 );
559
560 /**
561 * secret_key binding: workerd imports the checked-in HMAC material as a
562 * non-extractable CryptoKey; the route signs and verifies a message with it.
563 */
564 test(
565 "EffectWorker signs and verifies with the secret_key binding",
566 Effect.gen(function* () {
567 const { effectWorker } = yield* stack;
568 const response = yield* HttpClient.get(new URL("/secret-key?message=hello", effectWorker));
569 expect(response.status).toBe(200);
570 const body = (yield* response.json) as {
571 verified: boolean;
572 algorithm: string;
573 extractable: boolean;
574 signatureBase64: string;
575 };
576 expect(body.verified).toBe(true);
577 expect(body.algorithm).toBe("HMAC");
578 // Bound keys are never extractable; the local lowering matches.
579 expect(body.extractable).toBe(false);
580 expect(body.signatureBase64.length).toBeGreaterThan(0);
581 }),
582 );
583
584 /**
585 * Analytics Engine: `writeDataPoint` is accepted and discarded in local dev
586 * (Miniflare parity) — succeeding without a throw IS the documented local
587 * behavior.
588 */
589 test(
590 "EffectWorker writes an Analytics Engine data point (local no-op)",
591 Effect.gen(function* () {
592 const { effectWorker } = yield* stack;
593 const response = yield* HttpClient.get(new URL("/analytics", effectWorker));
594 expect(response.status).toBe(200);
595 expect((yield* response.json) as { ok: boolean }).toEqual({ ok: true });
596 }),
597 );
598
599 /**
600 * Secrets Store: the store + secret are local `dev:` rows and the
601 * `secrets_store_secret` binding round-trips the exact seeded value.
602 */
603 test(
604 "MediaWorker reads the Secrets Store secret",
605 Effect.gen(function* () {
606 const { mediaWorker, secretsStoreId, secretsSecretId } = yield* stack;
607
608 // Locally emulated — no cloud store/secret was created.
609 expect(secretsStoreId).toMatch(/^dev:/);
610 expect(secretsSecretId).toMatch(/^dev:/);
611
612 const body = (yield* (yield* HttpClient.get(new URL("/secret", mediaWorker))).json) as {
613 value: string;
614 };
615 expect(body.value).toBe(SECRETS_STORE_VALUE);
616 }),
617 );
618
619 /**
620 * send_email: locally the message is persisted as an `.eml` under
621 * `.alchemy/local/email` instead of being delivered; the simulator
622 * synthesizes a production-shaped Message-ID.
623 */
624 test(
625 "MediaWorker sends email; the .eml lands in local storage",
626 Effect.gen(function* () {
627 const { mediaWorker } = yield* stack;
628 const marker = crypto.randomUUID();
629
630 const res = yield* HttpClient.get(new URL(`/email/send?marker=${marker}`, mediaWorker));
631 expect(res.status).toBe(200);
632 const body = (yield* res.json) as { ok: boolean; messageId: string };
633 expect(body.ok).toBe(true);
634 expect(body.messageId).toMatch(/^<[A-Za-z0-9]{36}@example\.com>$/);
635
636 const eml = yield* findEmlContaining(`marker:${marker}`);
637 expect(eml).toContain("From: sender <sender@example.com>");
638 expect(eml).toContain(`Message-ID: <${marker}@example.com>`);
639 }),
640 { timeout: 60_000 },
641 );
642
643 /**
644 * Inbound email: POST a raw MIME message to the worker's
645 * `/cdn-cgi/handler/email` trigger route. The `email()` handler records it
646 * into KV (asserted via `/email/received`); a `reject-me` subject calls
647 * `setReject`, which the sender observes as a 400.
648 */
649 test(
650 "InboxWorker email() handler accepts and rejects inbound email",
651 Effect.gen(function* () {
652 const { inboxWorker } = yield* stack;
653 const marker = crypto.randomUUID();
654 const from = "someone@example.com";
655 const to = "someone-else@example.com";
656 const triggerUrl = new URL(
657 `/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,
658 inboxWorker,
659 );
660 const mime = (subject: string) =>
661 [
662 `From: someone <${from}>`,
663 `To: someone else <${to}>`,
664 `Subject: ${subject}`,
665 `Message-ID: <incoming-${marker}@example.com>`,
666 "MIME-Version: 1.0",
667 "Content-Type: text/plain",
668 "",
669 "This is a random email body.",
670 ].join("\n");
671
672 // Accepted.
673 const okRes = yield* HttpClient.post(triggerUrl, {
674 body: HttpBody.text(mime(`accept-me:${marker}`)),
675 });
676 const okText = yield* okRes.text;
677 if (okRes.status !== 200) {
678 // The trigger route surfaces handler errors as a 500 with the stack.
679 throw new Error(`email trigger failed (${okRes.status}): ${okText}`);
680 }
681 expect(okText).toBe("Worker successfully processed email");
682
683 const received = (yield* (yield* HttpClient.get(new URL("/email/received", inboxWorker)))
684 .json) as Array<{ from: string; to: string; subject: string }>;
685 const record = received.find((r) => r.subject === `accept-me:${marker}`);
686 expect(record).toMatchObject({ from, to });
687
688 // Rejected via setReject → the sender sees a 400 with the reason.
689 const rejectRes = yield* HttpClient.post(triggerUrl, {
690 body: HttpBody.text(mime(`reject-me:${marker}`)),
691 });
692 expect(rejectRes.status).toBe(400);
693 expect(yield* rejectRes.text).toBe(
694 "Worker rejected email with the following reason: I don't like this email",
695 );
696 }),
697 { timeout: 60_000 },
698 );
699
700 /**
701 * Browser Rendering: renders an inline HTML page through
702 * `@cloudflare/puppeteer` against the locally launched Chrome. The FIRST
703 * run on a machine downloads Chrome into the shared wrangler cache, which
704 * can take minutes — hence the generous bounded retry + timeout.
705 */
706 test(
707 "MediaWorker renders a page through the browser binding",
708 Effect.gen(function* () {
709 const { mediaWorker } = yield* stack;
710 const body = (yield* getJsonReady(new URL("/browser/title", mediaWorker), {
711 times: 30,
712 spaced: "5 seconds",
713 })) as { title: string; heading: string };
714 expect(body.title).toBe("Cloudflare Dev");
715 expect(body.heading).toBe("Hello from the local browser");
716 }),
717 { timeout: 240_000 },
718 );
719
720 /**
721 * Images: `info()` + `transform().output()` served locally by sharp.
722 * The transform result is re-inspected through `info()` to prove real pixel
723 * work happened (8x4 contain-fit to width 4 → 4x2).
724 */
725 test(
726 "MediaWorker transforms an image through the images binding",
727 Effect.gen(function* () {
728 const { mediaWorker } = yield* stack;
729
730 const info = (yield* (yield* HttpClient.post(new URL("/images/info", mediaWorker), {
731 body: HttpBody.uint8Array(PNG_RED_8X4),
732 })).json) as { format: string; width: number; height: number };
733 expect(info.format).toBe("image/png");
734 expect(info.width).toBe(8);
735 expect(info.height).toBe(4);
736
737 const transformRes = yield* HttpClient.post(new URL("/images/transform?width=4", mediaWorker), {
738 body: HttpBody.uint8Array(PNG_RED_8X4),
739 });
740 expect(transformRes.status).toBe(200);
741 const outputBytes = new Uint8Array(yield* transformRes.arrayBuffer);
742 // PNG magic bytes.
743 expect(Array.from(outputBytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);
744
745 const outputInfo = (yield* (yield* HttpClient.post(new URL("/images/info", mediaWorker), {
746 body: HttpBody.uint8Array(outputBytes),
747 })).json) as { format: string; width: number; height: number };
748 expect(outputInfo.width).toBe(4);
749 expect(outputInfo.height).toBe(2);
750 }),
751 { timeout: 60_000 },
752 );
753
754 /**
755 * HYBRID — per-binding `Alchemy.remote()`: `IMAGES_REMOTE` proxies to
756 * the REAL Images service while the worker (and every other binding) stays
757 * local. Requires real Cloudflare credentials, which this suite already has
758 * (the state store is remote).
759 */
760 test(
761 "MediaWorker images binding with Alchemy.remote() hits the real service",
762 Effect.gen(function* () {
763 const { mediaWorker } = yield* stack;
764 const info = (yield* Effect.gen(function* () {
765 const res = yield* HttpClient.post(new URL("/images/info-remote", mediaWorker), {
766 body: HttpBody.uint8Array(PNG_RED_8X4),
767 });
768 if (res.status !== 200) {
769 return yield* Effect.fail(new NotYet({ status: res.status }));
770 }
771 return yield* res.json;
772 }).pipe(
773 Effect.retry({
774 while: (e) => e._tag === "NotYet",
775 schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(10)]),
776 }),
777 )) as { format: string; width: number; height: number };
778 expect(info.format).toBe("image/png");
779 expect(info.width).toBe(8);
780 expect(info.height).toBe(4);
781 }),
782 { timeout: 120_000 },
783 );
784
785 /**
786 * Stream: upload video bytes through the binding, read details back, then
787 * fetch the watch URL served by the local stream router middleware.
788 */
789 test(
790 "MediaWorker uploads and watches a video through the stream binding",
791 Effect.gen(function* () {
792 const { mediaWorker } = yield* stack;
793 const videoBytes = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
794
795 const video = (yield* (yield* HttpClient.post(new URL("/stream/upload", mediaWorker), {
796 body: HttpBody.uint8Array(videoBytes),
797 })).json) as {
798 id: string;
799 readyToStream: boolean;
800 status: { state: string };
801 size: number;
802 creator: string | null;
803 };
804 expect(video.id).toBeTruthy();
805 expect(video.readyToStream).toBe(true);
806 expect(video.status.state).toBe("ready");
807 expect(video.size).toBe(videoBytes.byteLength);
808 expect(video.creator).toBe("alchemy");
809
810 const details = (yield* (yield* HttpClient.get(
811 new URL(`/stream/details?id=${video.id}`, mediaWorker),
812 )).json) as { id: string; size: number };
813 expect(details.id).toBe(video.id);
814 expect(details.size).toBe(videoBytes.byteLength);
815
816 // The watch route is served by the stream router middleware in front of
817 // the worker.
818 const watchRes = yield* HttpClient.get(
819 new URL(`/cdn-cgi/mf/stream/${video.id}/watch`, mediaWorker),
820 );
821 expect(watchRes.status).toBe(200);
822 const watched = new Uint8Array(yield* watchRes.arrayBuffer);
823 expect(Array.from(watched)).toEqual(Array.from(videoBytes));
824
825 // Clean up so re-runs stay tidy.
826 const deleted = (yield* (yield* HttpClient.get(
827 new URL(`/stream/delete?id=${video.id}`, mediaWorker),
828 )).json) as { deleted: boolean };
829 expect(deleted.deleted).toBe(true);
830 }),
831 { timeout: 60_000 },
832 );
833
834 /**
835 * HYBRID — `Alchemy.remote()`: LiveKV opted out of local emulation, so its
836 * id is a REAL namespace id (no `dev:` marker) and the binding round-trip
837 * from the local worker lands in the real cloud namespace.
838 */
839 test(
840 "Alchemy.remote() KV namespace is live while the worker stays local",
841 Effect.gen(function* () {
842 const { asyncWorker, liveKvNamespaceId } = yield* stack;
843
844 // A real cloud namespace id — the `dev:` marker means "emulated" and
845 // must be absent here.
846 expect(liveKvNamespaceId).not.toMatch(/^dev:/);
847
848 const key = crypto.randomUUID();
849 const value = crypto.randomUUID();
850 const put = (yield* getJsonReady(new URL(`/kv-live?key=${key}&value=${value}`, asyncWorker), {
851 times: 10,
852 spaced: "2 seconds",
853 })) as { value: string | null };
854 expect(put.value).toBe(value);
855
856 const got = (yield* (yield* HttpClient.get(new URL(`/kv-live?key=${key}`, asyncWorker)))
857 .json) as { value: string | null };
858 expect(got.value).toBe(value);
859 }),
860 { timeout: 60_000 },
861 );
862
863 interface WorkflowStatus {
864 status: string;
865 output?: { text?: string; secret?: string; ts?: number };
866 error?: { name: string; message: string } | null;
867 }
868
869 /**
870 * Start a `NotifyWorkflow` instance through `workerUrl` and poll its status
871 * until the instance reaches a terminal state. Asserts the workflow ran the
872 * KV roundtrip task (`Processed: <message>`) and resolved the plantime-bound
873 * `Alchemy.Secret` at runtime (`output.secret === WORKFLOW_SECRET_VALUE`).
874 */
875 const exerciseWorkflow = (workerUrl: string, label: string) =>
876 Effect.gen(function* () {
877 const roomId = `${label}-${Math.random().toString(36).slice(2, 10)}`;
878
879 const startResponse = yield* HttpClient.post(new URL(`/workflow/start/${roomId}`, workerUrl));
880 expect(startResponse.status).toBe(200);
881 const { instanceId } = (yield* startResponse.json) as {
882 instanceId: string;
883 };
884 expect(instanceId).toBeString();
885
886 const statusUrl = new URL(`/workflow/status/${instanceId}`, workerUrl);
887 const fetchStatus = HttpClient.get(statusUrl).pipe(
888 Effect.flatMap((res) => res.json),
889 Effect.map((json) => json as unknown as WorkflowStatus),
890 );
891 const status = yield* fetchStatus.pipe(
892 Effect.repeat({
893 schedule: Schedule.spaced("2 seconds"),
894 until: (s: WorkflowStatus) => s.status === "complete" || s.status === "errored",
895 times: 60,
896 }),
897 );
898
899 expect(status.error).toBeFalsy();
900 expect(status.status).toBe("complete");
901 expect(status.output?.secret).toBe(WORKFLOW_SECRET_VALUE);
902 expect(status.output?.text).toBe("Processed: hello from workflow");
903 });
904
905 /**
906 * EffectWorker `/workflow/start/:roomId` kicks off `NotifyWorkflow`, which
907 * does a KV roundtrip task and resolves the `WORKFLOW_SECRET` `Alchemy.Secret`
908 * at runtime. The status route surfaces the workflow output so we can assert
909 * the workflow actually executed end-to-end (not just that it was scheduled).
910 */
911 test(
912 "EffectWorker drives NotifyWorkflow to completion with secret + KV roundtrip",
913 Effect.gen(function* () {
914 const { effectWorker } = yield* stack;
915 yield* exerciseWorkflow(effectWorker, "effect");
916 }),
917 { timeout: 60_000 },
918 );
919
920 test(
921 "EffectWorker fetches a URL in a sandbox",
922 Effect.gen(function* () {
923 const { effectWorker } = yield* stack;
924 const response = yield* HttpClient.get(new URL("/sandbox", effectWorker));
925 expect(response.status).toBe(200);
926 const body = yield* response.text;
927 // The container echoes its `GREETING` env var, proving env vars flow
928 // through to the container (via the application config on a live deploy,
929 // and via `ctx.container.start({ env })` in local dev).
930 expect(body).toBe("Hello from Sandbox container! GREETING=hello-from-env");
931 }),
932 { timeout: 60_000 },
933 );
934
935 /**
936 * Hyperdrive: local dev is a passthrough to the Connection's `dev` origin,
937 * which must be a REAL reachable Postgres. Gated behind
938 * `HYPERDRIVE_DEV_URL` (see src/HyperdriveWorker.ts for a one-liner Docker
939 * setup); without it the stack omits the worker and this test skips.
940 */
941 test.skipIf(!process.env.HYPERDRIVE_DEV_URL)(
942 "HyperdriveWorker queries Postgres through the hyperdrive binding",
943 Effect.gen(function* () {
944 const { hyperdrive } = yield* stack;
945 assert(typeof hyperdrive === "string");
946
947 const body = (yield* getJsonReady(new URL("/query", hyperdrive), {
948 times: 15,
949 spaced: "2 seconds",
950 })) as { row: { sum: number; db: string } };
951 expect(body.row.sum).toBe(2);
952 expect(body.row.db.length).toBeGreaterThan(0);
953 }),
954 { timeout: 120_000 },
955 );