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

main
ts 169 lines 6.45 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 * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import * as pathe from "pathe";
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.
14 const { test } = Test.make({
15 providers: Cloudflare.providers(),
16 dev: true,
17 });
18
19 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
20
21 /**
22 * Mock video bytes — the same checked-in constant the runtime's own Stream
23 * binding test uses (adopted from Miniflare's stream plugin tests). The local
24 * simulator is a byte store: it accepts any payload and serves it unmodified.
25 */
26 const TEST_VIDEO_BYTES = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
27
28 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
29 status: number;
30 body: string;
31 }> {}
32
33 /**
34 * POST bytes to a fixture route, retrying until the worker serves a 200
35 * (fresh dev workers can briefly 503 while workerd boots). Non-200s carry the
36 * body so a persistent fixture error surfaces.
37 */
38 const postBytesReady = (url: string, bytes: Uint8Array) =>
39 Effect.gen(function* () {
40 const client = yield* HttpClient.HttpClient;
41 return yield* client
42 .execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyUint8Array(bytes)))
43 .pipe(
44 Effect.flatMap((res) =>
45 res.status === 200
46 ? Effect.succeed(res)
47 : res.text.pipe(
48 Effect.flatMap((body) =>
49 Effect.fail(new WorkerNotReady({ status: res.status, body })),
50 ),
51 ),
52 ),
53 Effect.retry({
54 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
55 schedule: Schedule.max([
56 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
57 Schedule.recurs(10),
58 ]),
59 }),
60 );
61 }).pipe(Effect.orDie);
62
63 const fixtureMain = pathe.resolve(import.meta.dirname, "fixtures/local-worker.ts");
64
65 interface VideoResponse {
66 id: string;
67 creator: string | null;
68 meta: Record<string, string>;
69 readyToStream: boolean;
70 status: { state: string };
71 size: number;
72 preview: string;
73 hlsPlaybackUrl?: string;
74 dashPlaybackUrl?: string;
75 }
76
77 interface ErrorEnvelope {
78 error: boolean;
79 code?: number;
80 statusCode?: number;
81 message: string;
82 }
83
84 /**
85 * Under `alchemy dev` the `stream` binding is emulated by cloudflare-runtime:
86 * uploads land in a local video store (shared across the runtime's workers,
87 * persisted with disk-backed storage) and each video's `preview` URL is
88 * served unmodified at `/__cf_local/stream/<id>/watch` — no Cloudflare
89 * credentials or preview session are involved for the binding. Fidelity
90 * limits (mirroring Miniflare): no transcoding/HLS ladder, no signed URLs,
91 * no direct creator uploads.
92 */
93 test.provider(
94 "stream binding round-trips against the local video-store simulator",
95 (stack) =>
96 Effect.gen(function* () {
97 yield* stack.destroy();
98
99 const deployed = yield* stack.deploy(
100 Effect.gen(function* () {
101 const worker = yield* Cloudflare.Worker("stream-local-worker", {
102 main: fixtureMain,
103 env: { STREAM: Cloudflare.Stream.Stream("STREAM") },
104 });
105 return { url: worker.url.as<string>() };
106 }),
107 );
108
109 // Served from the local dev proxy — proof the worker runs locally.
110 expect(deployed.url).toMatch(/^http:\/\/localhost:\d+$/);
111
112 const client = yield* HttpClient.HttpClient;
113
114 // Upload through the binding (the local simulator accepts the raw
115 // request body bytes in place of a URL, like Miniflare).
116 const uploadRes = yield* postBytesReady(`${deployed.url}/upload`, TEST_VIDEO_BYTES);
117 const video = (yield* uploadRes.json) as unknown as VideoResponse;
118 expect(video.id).toBeTruthy();
119 expect(video.readyToStream).toBe(true);
120 expect(video.status.state).toBe("ready");
121 expect(video.size).toBe(TEST_VIDEO_BYTES.byteLength);
122 expect(video.creator).toBe("alchemy");
123 expect(video.meta).toEqual({ title: "alchemy-local-test" });
124 // The preview URL is the local watch route on the Worker's own URL, as
125 // Miniflare builds it from its public URL.
126 expect(video.preview).toBe(
127 `${String(deployed.url).replace(/\/$/, "")}/__cf_local/stream/${video.id}/watch`,
128 );
129
130 // Read it back through the binding.
131 const detailsRes = yield* client.get(`${deployed.url}/details?id=${video.id}`);
132 const details = (yield* detailsRes.json) as unknown as VideoResponse;
133 expect(details.id).toBe(video.id);
134 expect(details.size).toBe(TEST_VIDEO_BYTES.byteLength);
135
136 // The stored bytes are served at the watch route, both through the
137 // dev URL (the stream router middleware in front of the user worker)…
138 const watchRes = yield* client.get(`${deployed.url}/__cf_local/stream/${video.id}/watch`);
139 expect(watchRes.status).toBe(200);
140 const watchBytes = new Uint8Array(yield* watchRes.arrayBuffer);
141 expect(Array.from(watchBytes)).toEqual(Array.from(TEST_VIDEO_BYTES));
142
143 // …and at the video's own preview URL.
144 const previewRes = yield* client.get(video.preview);
145 expect(previewRes.status).toBe(200);
146 const previewBytes = new Uint8Array(yield* previewRes.arrayBuffer);
147 expect(Array.from(previewBytes)).toEqual(Array.from(TEST_VIDEO_BYTES));
148
149 // Delete through the binding; details now surfaces the simulator's
150 // typed not-found error (code 10003).
151 const deleteRes = yield* client.get(`${deployed.url}/delete?id=${video.id}`);
152 expect(((yield* deleteRes.json) as { deleted: boolean }).deleted).toBe(true);
153 const goneRes = yield* client.get(`${deployed.url}/details?id=${video.id}`);
154 const gone = (yield* goneRes.json) as unknown as ErrorEnvelope;
155 expect(gone.error).toBe(true);
156 expect(gone.message).toContain("Video not found");
157
158 yield* stack.destroy();
159 }).pipe(logLevel),
160 {
161 tags: [
162 "provider:cloudflare",
163 "provider:cloudflare:stream",
164 "provider:cloudflare:worker",
165 "local",
166 ],
167 timeout: 180_000,
168 },
169 );