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

main
ts 268 lines 11.3 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { isLocalId } from "@alchemy.run/cloudflare/LocalRuntime";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as kv from "@distilled.cloud/cloudflare/kv";
7 import * as Alchemy from "alchemy";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Path from "effect/Path";
13 import { MinimumLogLevel } from "effect/References";
14 import * as Schedule from "effect/Schedule";
15 import * as Stream from "effect/Stream";
16 import * as pathe from "pathe";
17 import { cloneFixture } from "../Utils/Fixture.ts";
18 import { expectUrlContains } from "../Utils/Http.ts";
19
20 const { test } = Test.make({ providers: Cloudflare.providers(), dev: true });
21
22 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
23
24 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "waku-app");
25 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
26
27 const fixtureEntries = [".gitignore", "package.json", "tsconfig.json", "public", "src"];
28
29 /**
30 * Execute `request` until it answers 200 with a JSON body — the dev server
31 * compiles routes lazily and briefly answers non-200 mid-rebuild.
32 */
33 const requestJsonReady = <T>(request: HttpClientRequest.HttpClientRequest) =>
34 Effect.gen(function* () {
35 const client = yield* HttpClient.HttpClient;
36 return yield* client.execute(request).pipe(
37 Effect.flatMap((res) =>
38 res.status === 200
39 ? Effect.flatMap(res.text, (body) =>
40 Effect.try({
41 try: () => JSON.parse(body) as T,
42 catch: () => new Error(`non-json body: ${body}`),
43 }),
44 )
45 : Effect.flatMap(res.text, (body) =>
46 Effect.fail(new Error(`dev server not ready: ${res.status} ${body.slice(0, 300)}`)),
47 ),
48 ),
49 Effect.retry({
50 schedule: Schedule.max([
51 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
52 Schedule.recurs(15),
53 ]),
54 }),
55 );
56 });
57
58 /** PUT then GET `key` through the fixture's `/api/kv` route. */
59 const kvRoundTrip = Effect.fn(function* (baseUrl: string, key: string, value: string) {
60 yield* requestJsonReady<{ ok: boolean }>(
61 HttpClientRequest.put(`${baseUrl}/api/kv`).pipe(
62 HttpClientRequest.bodyJsonUnsafe({ key, value }),
63 ),
64 );
65 return yield* requestJsonReady<{ key: string; value: string | null }>(
66 HttpClientRequest.get(`${baseUrl}/api/kv?key=${encodeURIComponent(key)}`),
67 );
68 });
69
70 /**
71 * Under `alchemy dev` the whole site runs locally: the KV Namespace is
72 * emulated by the local provider (a `dev:` id, no cloud API calls) and
73 * waku's own dev server serves the app behind the alchemy dev proxy, with
74 * the `kv_namespace` binding lowered onto the local workerd simulator.
75 */
76 // Concurrent like the other Website suites: the Waku build runs in a
77 // child process with cwd = project root (core/BuildChild.ts), and the
78 // dev server only chdirs briefly inside the RPC sidecar during startup.
79 describe.concurrent(
80 "Waku dev",
81 { tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:website"] },
82 () => {
83 test.provider(
84 "Waku dev: local dev server renders RSC SSR with bindings, local KV, and HMR",
85 (stack) =>
86 Effect.gen(function* () {
87 const fs = yield* FileSystem.FileSystem;
88 const path = yield* Path.Path;
89
90 yield* stack.destroy();
91
92 const rootDir = yield* cloneFixture(fixtureDir, {
93 prefix: "alchemy-waku-dev-",
94 tempRoot,
95 entries: fixtureEntries,
96 });
97
98 const bindingMarker = "waku-dev-binding-marker";
99
100 const { site, siteKv } = yield* stack.deploy(
101 Effect.gen(function* () {
102 const siteKv = yield* Cloudflare.KV.Namespace("WakuLocalKV");
103 const site = yield* Cloudflare.Website.Waku("WakuLocal", {
104 rootDir,
105 dev: { port: 0 },
106 memo: { include: ["src/**", "public/**", "package.json", "tsconfig.json"] },
107 env: { MESSAGE: bindingMarker, SITE_KV: siteKv },
108 });
109 return { site, siteKv };
110 }),
111 );
112
113 // Local identity: the url points at the alchemy dev proxy — no
114 // cloud Worker exists — and the namespace id carries the `dev:`
115 // marker, proof the KV provider never called the cloud.
116 expect(site.url).toBeDefined();
117 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
118 expect(isLocalId(siteKv.namespaceId)).toBe(true);
119
120 // Dynamic RSC page rendered by waku's dev server (rsc environment
121 // runs in workerd behind the proxy). Waku's cold first compile
122 // (RSC + vite dep optimization) can exceed 120s when the whole
123 // suite's builds and dev servers contend for the CPU.
124 yield* expectUrlContains(`${site.url!}/`, "WAKU_PAGE_MARKER", {
125 timeout: "180 seconds",
126 label: "waku dev dynamic home page",
127 });
128
129 // The page reads the `MESSAGE` binding from `cloudflare:workers`
130 // env — proves alchemy-managed bindings reach the dev RSC server.
131 yield* expectUrlContains(`${site.url!}/`, `MESSAGE=${bindingMarker}`, {
132 timeout: "60 seconds",
133 label: "waku dev env binding in SSR output",
134 });
135
136 // Static asset from `public/` through the dev server.
137 yield* expectUrlContains(`${site.url!}/hello.txt`, "hello from public/", {
138 timeout: "60 seconds",
139 label: "waku dev static asset",
140 });
141 // The same file read by a server route through the `ASSETS` binding.
142 yield* expectUrlContains(`${site.url!}/asset`, "hello from public/", {
143 timeout: "60 seconds",
144 label: "waku ASSETS binding",
145 });
146
147 // The KV binding round-trips through the `/api/kv` route against the
148 // local simulator.
149 const roundTrip = yield* kvRoundTrip(site.url!, "waku-dev-key", "kv-dev-value");
150 expect(roundTrip.value).toBe("kv-dev-value");
151
152 // ── HMR: edit the page in place; the dev server rebuilds and serves
153 // the new marker at the same URL without a redeploy ─────────────────
154 const indexPath = path.join(rootDir, "src/pages/index.tsx");
155 const index = yield* fs.readFileString(indexPath);
156 yield* fs.writeFileString(
157 indexPath,
158 index.replace("WAKU_PAGE_MARKER", "WAKU_PAGE_MARKER_V2"),
159 );
160
161 // Bounded poll; transient non-200s mid-rebuild are retried inside
162 // expectUrlContains' budget.
163 yield* expectUrlContains(`${site.url!}/`, "WAKU_PAGE_MARKER_V2", {
164 timeout: "120 seconds",
165 label: "waku dev page after HMR edit",
166 });
167
168 // The KV binding survives the rebuild: the previous write is still
169 // readable and new writes land.
170 const afterHmr = yield* kvRoundTrip(site.url!, "waku-dev-key-2", "kv-dev-value-2");
171 expect(afterHmr.value).toBe("kv-dev-value-2");
172 const stillThere = yield* requestJsonReady<{ value: string | null }>(
173 HttpClientRequest.get(`${site.url!}/api/kv?key=waku-dev-key`),
174 );
175 expect(stillThere.value).toBe("kv-dev-value");
176
177 yield* stack.destroy();
178 }).pipe(logLevel),
179 { tags: ["local"], timeout: 300_000 },
180 );
181
182 /**
183 * `Alchemy.remote()` opts the namespace OUT of local emulation: even under
184 * `alchemy dev` it is created on real Cloudflare and the dev worker's
185 * binding proxies to it remotely. Out-of-band reads through the cloud API
186 * prove the local site's writes landed in the real namespace, and destroy
187 * (stamped-mode delete path) removes it from the cloud.
188 */
189 test.provider(
190 "Waku dev: Alchemy.remote() KV namespace runs live behind the local site",
191 (stack) =>
192 Effect.gen(function* () {
193 yield* stack.destroy();
194
195 const rootDir = yield* cloneFixture(fixtureDir, {
196 prefix: "alchemy-waku-dev-remote-",
197 tempRoot,
198 entries: fixtureEntries,
199 });
200
201 const { site, liveKv } = yield* stack.deploy(
202 Effect.gen(function* () {
203 const liveKv = yield* Cloudflare.KV.Namespace("WakuRemoteKV").pipe(Alchemy.remote());
204 const site = yield* Cloudflare.Website.Waku("WakuLocalRemoteKV", {
205 rootDir,
206 dev: { port: 0 },
207 memo: { include: ["src/**", "public/**", "package.json", "tsconfig.json"] },
208 env: { MESSAGE: "waku-dev-remote-marker", SITE_KV: liveKv },
209 });
210 return { site, liveKv };
211 }),
212 );
213
214 // The site is local, the namespace is REAL: a non-`dev:` id proves
215 // the live provider ran even in a dev deploy.
216 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
217 expect(isLocalId(liveKv.namespaceId)).toBe(false);
218
219 // Write through the locally-served site into the remote-proxied
220 // binding.
221 const roundTrip = yield* kvRoundTrip(site.url!, "waku-remote-key", "kv-remote-value");
222 expect(roundTrip.value).toBe("kv-remote-value");
223
224 // Out-of-band: the write is visible through the cloud API — the
225 // remote-proxied binding really hit the live namespace.
226 const { accountId } = yield* yield* CloudflareEnvironment;
227 const rawValue = yield* kv
228 .getNamespaceValue({
229 accountId,
230 namespaceId: liveKv.namespaceId,
231 keyName: "waku-remote-key",
232 })
233 .pipe(
234 Effect.flatMap((res) =>
235 Effect.tryPromise(() =>
236 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
237 ),
238 ),
239 // The KV REST read can lag the proxied write — propagation is
240 // documented at up to 60s and runs longer under account load
241 // (a fully concurrent suite), so budget ~91s: exponential ramp
242 // capped at 10s spacing.
243 Effect.retry({
244 while: (e) => e._tag === "KeyNotFound",
245 schedule: Schedule.min([
246 Schedule.exponential("1 second", 1.5),
247 Schedule.spaced("10 seconds"),
248 ]),
249 times: 13,
250 }),
251 );
252 expect(rawValue).toBe("kv-remote-value");
253
254 yield* stack.destroy();
255
256 // The live namespace was deleted from the cloud on destroy (its
257 // state row is stamped live, so the live provider handles the delete
258 // even in a dev run).
259 const gone = yield* kv.getNamespace({ accountId, namespaceId: liveKv.namespaceId }).pipe(
260 Effect.as(false),
261 Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)),
262 );
263 expect(gone).toBe(true);
264 }).pipe(logLevel),
265 { tags: ["live"], timeout: 300_000 },
266 );
267 },
268 );