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