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

main
ts 111 lines 3.88 KB
Raw
1 import { expect } from "bun:test";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import * as Test from "@alchemy.run/test/Bun";
4 import * as Effect from "effect/Effect";
5 import * as HttpClient from "effect/http/HttpClient";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import * as Schedule from "effect/Schedule";
8 import Stack from "../alchemy.run.ts";
9
10 // A fresh workers.dev URL transiently 404s/5xxs while the edge converges.
11 // `Test.getWhenReady` / `Test.executeWhenReady` retry through that window and
12 // return the first non-cold-start response to assert on.
13 const { getWhenReady, executeWhenReady } = Test;
14
15 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
16 providers: Cloudflare.providers(),
17 state: Cloudflare.state(),
18 });
19
20 const stack = beforeAll(deploy(Stack));
21 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
22
23 test(
24 "deploys and exposes a url",
25 Effect.gen(function* () {
26 const { url } = yield* stack;
27 expect(url).toBeString();
28 }),
29 );
30
31 test(
32 "echoes env.API_KEY",
33 Effect.gen(function* () {
34 const { url } = yield* stack;
35
36 const response = yield* getWhenReady(`${url}/api-key`);
37 expect(response.status).toBe(200);
38 const body = yield* response.text;
39 expect(body).toBe("SOME_API_KEY");
40 }),
41 // `getWhenReady` rides out the edge cold-start window with exponential
42 // backoff (up to 20 attempts), which routinely exceeds bun's default 5s
43 // test timeout on a fresh workers.dev URL. Match the other HTTP cases.
44 { timeout: 120_000 },
45 );
46
47 /**
48 * Native (async) queue handler round-trip. The async worker exports
49 * a plain `queue(batch, env)` handler that writes each message body
50 * to R2 at `/queue/<id>`. POST /queue/send enqueues a message;
51 * GET /<path> reads from R2, so we read /queue/<id> back.
52 *
53 * Pairs with the cloudflare-worker example, which exercises the
54 * Effect-style `Cloudflare.Queues.consumeQueueMessages(Queue, handler)` path
55 * against the same producer/consumer round-trip.
56 */
57 test(
58 "native queue() handler round-trip",
59 Effect.gen(function* () {
60 const { url } = yield* stack;
61 const text = `hello-${Date.now()}`;
62 type Message = { id: string; text: string; sentAt: number };
63
64 const send = Effect.gen(function* () {
65 const sendResponse = yield* executeWhenReady(
66 HttpClientRequest.post(`${url}/queue/send?text=${encodeURIComponent(text)}`),
67 );
68 expect(sendResponse.status).toBe(202);
69 const { sent } = (yield* sendResponse.json) as { sent: Message };
70 expect(sent.id).toBeTypeOf("string");
71 return sent;
72 });
73
74 const sent: Message[] = [yield* send];
75
76 // First delivery on a freshly created queue+consumer can lag well past
77 // the settled steady state (consumer attachment propagates through
78 // Cloudflare's queue subsystem asynchronously). Poll for ANY of the
79 // messages we sent, re-sending every ~20s in case an early message was
80 // published into the propagation window; the consumer persists each
81 // message to R2 keyed by its id, so the first one to land wins.
82 let polls = 0;
83 const findConsumed = Effect.gen(function* () {
84 polls++;
85 if (polls % 10 === 0 && sent.length < 5) {
86 sent.push(yield* send);
87 }
88 for (const message of sent) {
89 const resultResponse = yield* HttpClient.get(`${url}/queue/${message.id}`);
90 if (resultResponse.status === 200) {
91 const body = yield* resultResponse.text;
92 if (body) return JSON.parse(body) as Message;
93 }
94 }
95 return undefined;
96 });
97
98 const consumed = yield* findConsumed.pipe(
99 Effect.repeat({
100 schedule: Schedule.spaced("2 seconds"),
101 until: (message) => message !== undefined,
102 times: 75,
103 }),
104 );
105
106 expect(consumed).toBeDefined();
107 expect(sent.map((message) => message.id)).toContain(consumed!.id);
108 expect(consumed!.text).toBe(text);
109 }),
110 { timeout: 180_000 },
111 );