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

main
ts 248 lines 8.98 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 HttpClient from "effect/http/HttpClient";
7 import { MinimumLogLevel } from "effect/References";
8 import * as Schedule from "effect/Schedule";
9 import * as pathe from "pathe";
10 import { cloneFixture } from "../Utils/Fixture.ts";
11
12 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
13 // matching the process topology of the real `alchemy dev` command. The
14 // Worker and Consumer lifecycles (vite child, consumer wiring, worker
15 // restart hooks) all run in the sidecar process.
16 const { test } = Test.make({
17 providers: Cloudflare.providers(),
18 dev: true,
19 });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 const queueFixtureDir = pathe.resolve(import.meta.dirname, "vite-queue-fixture");
24 const cronFixtureDir = pathe.resolve(import.meta.dirname, "vite-cron-fixture");
25 const tailFixtureDir = pathe.resolve(import.meta.dirname, "vite-tail-fixture");
26 // Keep the temp clone under the workspace so Vite can express the project
27 // root relative to cwd (see the note on `tempRoot` in Vite.test.ts).
28 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
29 const fixtureEntries = ["index.html", "package.json", "vite.config.ts", "worker.ts"];
30
31 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
32 status: number;
33 }> {}
34
35 const getJsonReady = (url: string) =>
36 Effect.gen(function* () {
37 const client = yield* HttpClient.HttpClient;
38 const res = yield* client.get(url).pipe(
39 Effect.flatMap((res) =>
40 res.status === 200
41 ? Effect.succeed(res)
42 : Effect.fail(new WorkerNotReady({ status: res.status })),
43 ),
44 Effect.retry({
45 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
46 schedule: Schedule.max([
47 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
48 Schedule.recurs(15),
49 ]),
50 }),
51 );
52 return yield* res.json;
53 }).pipe(Effect.orDie);
54
55 /**
56 * Regression test for #1109: a `Queues.Consumer` registered against a
57 * `Website.Vite` worker in dev. The Consumer depends on the site's
58 * `workerName`, so the Vite child always boots before the consumer wiring
59 * lands in `LocalRuntimeState` — the consumer's reconcile must then restart
60 * the child through the `workerRestarts` hook (which `runVite` previously
61 * never registered). Pre-fix, the producer binding resolved to the dev
62 * registry's drop-and-warn stub: `queue()` never ran and `send()` hung.
63 */
64 test.provider(
65 "Vite dev: queue consumer on the site worker receives produced messages",
66 (stack) =>
67 Effect.gen(function* () {
68 yield* stack.destroy();
69
70 const rootDir = yield* cloneFixture(queueFixtureDir, {
71 prefix: "alchemy-vite-queue-",
72 tempRoot,
73 entries: fixtureEntries,
74 });
75
76 const deployed = yield* stack.deploy(
77 Effect.gen(function* () {
78 const queue = yield* Cloudflare.Queues.Queue("ViteJobsQueue");
79 const site = yield* Cloudflare.Website.Vite("ViteQueueSite", {
80 rootDir,
81 main: "worker.ts",
82 workersDev: true,
83 compatibility: {
84 date: "2024-09-23",
85 flags: ["nodejs_compat"],
86 },
87 memo: { include: fixtureEntries },
88 assets: { runWorkerFirst: true },
89 dev: { port: 0 },
90 env: { QUEUE: queue },
91 });
92 yield* Cloudflare.Queues.Consumer("ViteJobsConsumer", {
93 queueId: queue.queueId,
94 scriptName: site.workerName,
95 settings: { batchSize: 5, maxRetries: 2, maxWaitTimeMs: 500 },
96 });
97 return { queue, site };
98 }),
99 );
100
101 // The queue is emulated (`dev:` id — proof no cloud call ran) and the
102 // site serves from the local dev proxy.
103 expect(deployed.queue.queueId).toMatch(/^dev:/);
104 expect(deployed.site.url).toMatch(/^http:\/\/localhost:\d+$/);
105
106 // `send()` resolves (pre-fix it hung forever against the registry's
107 // drop stub)...
108 const sent = (yield* getJsonReady(`${deployed.site.url}/api/send?text=vite-queue-hello`).pipe(
109 Effect.timeout("60 seconds"),
110 )) as { sent: string };
111 expect(sent.sent).toBe("vite-queue-hello");
112
113 // ...and the broker delivers to the fixture's queue() handler.
114 const received = yield* getJsonReady(`${deployed.site.url}/api/received`).pipe(
115 Effect.map((body) => (body as { received: string[] }).received),
116 Effect.repeat({
117 schedule: Schedule.spaced("500 millis"),
118 until: (received) => received.includes("vite-queue-hello"),
119 times: 30,
120 }),
121 );
122 expect(received).toContain("vite-queue-hello");
123
124 yield* stack.destroy();
125 }).pipe(logLevel),
126 {
127 tags: [
128 "provider:cloudflare",
129 "provider:cloudflare:queue",
130 "provider:cloudflare:website",
131 "local",
132 ],
133 timeout: 240_000,
134 },
135 );
136
137 /** Regression test for cron configuration dropped by the Vite child path. */
138 test.provider(
139 "Vite dev: automatically invokes scheduled handlers",
140 (stack) =>
141 Effect.gen(function* () {
142 yield* stack.destroy();
143
144 const rootDir = yield* cloneFixture(cronFixtureDir, {
145 prefix: "alchemy-vite-cron-",
146 tempRoot,
147 entries: fixtureEntries,
148 });
149
150 const site = yield* stack.deploy(
151 Cloudflare.Website.Vite("ViteCronSite", {
152 rootDir,
153 main: "worker.ts",
154 workersDev: true,
155 compatibility: {
156 date: "2024-09-23",
157 flags: ["nodejs_compat"],
158 },
159 memo: { include: fixtureEntries },
160 assets: { runWorkerFirst: true },
161 dev: { port: 0 },
162 // Effect Cron supports seconds for fast local feedback; five-field
163 // production expressions use the same runtime path.
164 crons: ["* * * * * *"],
165 }),
166 );
167
168 const scheduledCount = yield* getJsonReady(`${site.url}/api/scheduled`).pipe(
169 Effect.map((body) => (body as { scheduledCount: number }).scheduledCount),
170 Effect.repeat({
171 schedule: Schedule.spaced("500 millis"),
172 until: (count) => count > 0,
173 times: 20,
174 }),
175 );
176 expect(scheduledCount).toBeGreaterThan(0);
177
178 yield* stack.destroy();
179 }).pipe(logLevel),
180 {
181 tags: ["provider:cloudflare", "provider:cloudflare:website", "local"],
182 timeout: 240_000,
183 },
184 );
185
186 /** Regression test for tail consumers dropped by the Vite child path (#2231). */
187 test.provider(
188 "Vite dev: tail and streaming tail consumers receive the site's events",
189 (stack) =>
190 Effect.gen(function* () {
191 yield* stack.destroy();
192
193 const rootDir = yield* cloneFixture(tailFixtureDir, {
194 prefix: "alchemy-vite-tail-",
195 tempRoot,
196 entries: fixtureEntries,
197 });
198
199 const { site, consumer } = yield* stack.deploy(
200 Effect.gen(function* () {
201 const events = yield* Cloudflare.KV.Namespace("ViteTailEvents");
202 const consumer = yield* Cloudflare.Worker("ViteTailConsumer", {
203 main: pathe.resolve(import.meta.dirname, "fixtures/tail-consumer.ts"),
204 env: { EVENTS: events },
205 dev: { port: 0 },
206 });
207 const site = yield* Cloudflare.Website.Vite("ViteTailSite", {
208 rootDir,
209 main: "worker.ts",
210 workersDev: true,
211 compatibility: { date: "2024-09-23" },
212 memo: { include: fixtureEntries },
213 assets: { runWorkerFirst: true },
214 dev: { port: 0 },
215 tailConsumers: [consumer],
216 streamingTailConsumers: [consumer],
217 });
218 return { site, consumer };
219 }),
220 );
221
222 // Each poll drives the site again: the consumer may register with the
223 // dev registry after the site's first requests.
224 const client = yield* HttpClient.HttpClient;
225 const recorded = yield* Effect.gen(function* () {
226 yield* client.get(`${site.url}/api/log`).pipe(Effect.flatMap((res) => res.text));
227 const res = yield* client.get(`${consumer.url}/events`);
228 return (yield* res.json) as { tail: string[]; stream: string[] };
229 }).pipe(
230 Effect.orDie,
231 Effect.repeat({
232 schedule: Schedule.spaced("1 second"),
233 until: ({ tail, stream }) =>
234 tail.some((batch) => batch.includes("vite-tail-marker")) &&
235 stream.some((session) => session.includes("vite-tail-marker")),
236 times: 30,
237 }),
238 );
239 expect(recorded.tail.some((batch) => batch.includes("vite-tail-marker"))).toBe(true);
240 expect(recorded.stream.some((session) => session.includes("vite-tail-marker"))).toBe(true);
241
242 yield* stack.destroy();
243 }).pipe(logLevel),
244 {
245 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:website", "local"],
246 timeout: 240_000,
247 },
248 );