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

main
ts 151 lines 5 KB
Raw
1 import * as fs from "node:fs/promises";
2 import * as path from "node:path";
3 import * as vite from "vite";
4 import { afterEach, describe, expect, test } from "vitest";
5 import * as Queue from "../../core/bindings/queue/Queue.ts";
6 import cloudflareVitePlugin from "../plugin.ts";
7
8 /**
9 * A Worker that both produces to and consumes from one queue.
10 *
11 * `POST /send` enqueues a message. `GET /received` reports what the `queue()`
12 * handler has seen. The handler accumulates on `globalThis` — the dev server
13 * runs one Worker instance, so the producer request, the delivery and the
14 * readback all share an isolate.
15 */
16 const workerSource = `
17 export default {
18 async fetch(request, env) {
19 const url = new URL(request.url);
20 if (url.pathname === "/send") {
21 await env.QUEUE.send({ id: url.searchParams.get("id") });
22 return new Response("sent");
23 }
24 return Response.json(globalThis.__received ?? []);
25 },
26
27 async queue(batch) {
28 globalThis.__received ??= [];
29 for (const message of batch.messages) {
30 globalThis.__received.push(message.body.id);
31 message.ack();
32 }
33 },
34 };
35 `;
36
37 const QUEUE_NAME = "vite-plugin-queue-consumer-test";
38
39 /** Under `.cache` so a crashed run cannot leave untracked files behind. */
40 const TMP_ROOT = path.resolve(import.meta.dirname, "../.cache/test-roots");
41
42 const cleanups: Array<() => Promise<void>> = [];
43
44 afterEach(async () => {
45 for (const cleanup of cleanups.splice(0).reverse()) {
46 await cleanup();
47 }
48 });
49
50 async function startDevServer() {
51 await fs.mkdir(TMP_ROOT, { recursive: true });
52 const root = await fs.mkdtemp(path.join(TMP_ROOT, "queue-consumer-"));
53 cleanups.push(() => fs.rm(root, { recursive: true, force: true }));
54
55 const entry = path.join(root, "worker.js");
56 await fs.writeFile(entry, workerSource);
57
58 const server = await vite.createServer({
59 root,
60 configFile: false,
61 cacheDir: path.join(root, ".vite"),
62 logLevel: "silent",
63 server: { port: 0 },
64 plugins: [
65 cloudflareVitePlugin({
66 main: entry,
67 compatibilityDate: "2026-03-10",
68 worker: {
69 name: "vite-plugin-queue-consumer-test",
70 bindings: [Queue.local({ binding: "QUEUE", queueName: QUEUE_NAME })],
71 // The worker consumes the same queue it produces to, so the producer
72 // binding must resolve to a local broker rather than the dev-registry
73 // proxy. That only happens if this option reaches `runtime.start`.
74 queueConsumers: [{ queueName: QUEUE_NAME, maxBatchSize: 1, maxBatchTimeout: 0 }],
75 },
76 }),
77 ],
78 });
79 cleanups.push(() => server.close());
80 await server.listen();
81
82 const url = server.resolvedUrls?.local[0];
83 if (!url) {
84 throw new Error("Dev server did not report a local URL");
85 }
86
87 return {
88 send: (id: string) =>
89 fetch(new URL(`/send?id=${id}`, url), {
90 method: "POST",
91 signal: AbortSignal.timeout(10_000),
92 }),
93 received: async (): Promise<Array<string>> => {
94 const response = await fetch(new URL("/received", url), {
95 signal: AbortSignal.timeout(10_000),
96 });
97 return (await response.json()) as Array<string>;
98 },
99 };
100 }
101
102 /** Delivery is asynchronous, so poll rather than assert on the first read. */
103 async function receivedEventually(
104 received: () => Promise<Array<string>>,
105 count: number,
106 ): Promise<Array<string>> {
107 const deadline = Date.now() + 30_000;
108 let last = await received();
109 while (last.length < count && Date.now() < deadline) {
110 await new Promise((resolve) => setTimeout(resolve, 250));
111 last = await received();
112 }
113 return last;
114 }
115
116 describe("queue consumers in dev", () => {
117 /**
118 * Regression test for a dropped option: `serve()` built its `runtime.start`
119 * call by listing worker options one at a time and omitted `queueConsumers`.
120 * The type allowed it, so callers passed it and it was silently discarded.
121 *
122 * The worker then started with no consumers, its producer binding resolved to
123 * the dev-registry `ExternalQueueConsumer` instead of a local broker, and that
124 * accepts-and-drops:
125 *
126 * [registry] No consumer registered for queue "…". Accepting and dropping message.
127 *
128 * Two things failed, and this test covers both: `queue()` never ran, and
129 * `send()` never settled — so the request hung rather than erroring.
130 */
131 test("delivers a message to the queue() handler of the worker that produced it", async () => {
132 const { send, received } = await startDevServer();
133
134 // `send()` not settling was half the fault, so await the producer request
135 // rather than fire-and-forget. The AbortSignal turns a hang into a failure.
136 const response = await send("first");
137 expect(response.status).toBe(200);
138
139 expect(await receivedEventually(received, 1)).toEqual(["first"]);
140 });
141
142 test("delivers every message when several are produced", async () => {
143 const { send, received } = await startDevServer();
144
145 await send("a");
146 await send("b");
147 await send("c");
148
149 expect((await receivedEventually(received, 3)).sort()).toEqual(["a", "b", "c"]);
150 });
151 });