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

main
ts 237 lines 8.86 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as r2 from "@distilled.cloud/cloudflare/r2";
6 import * as Alchemy from "alchemy";
7 import { Action } from "alchemy/Action";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as HttpClient from "effect/http/HttpClient";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import * as pathe from "pathe";
15
16 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
17 // matching the process topology of the real `alchemy dev` command (see
18 // MakeOptions.sidecar in Test/Core.ts).
19 const { test } = Test.make({
20 providers: Cloudflare.providers(),
21 dev: true,
22 });
23
24 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
25
26 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
27 status: number;
28 }> {}
29
30 const getJsonReady = (url: string) =>
31 Effect.gen(function* () {
32 const client = yield* HttpClient.HttpClient;
33 const res = yield* client.get(url).pipe(
34 Effect.flatMap((res) =>
35 res.status === 200
36 ? Effect.succeed(res)
37 : Effect.fail(new WorkerNotReady({ status: res.status })),
38 ),
39 Effect.retry({
40 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
41 // Cap the backoff: an uncapped exponential over 10 recurs sums to
42 // ~8.5 minutes and turns a persistent non-200 into an apparent hang.
43 schedule: Schedule.max([
44 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
45 Schedule.recurs(10),
46 ]),
47 }),
48 );
49 return yield* res.json;
50 }).pipe(Effect.orDie);
51
52 /**
53 * Under `alchemy dev` the R2 Bucket resource is emulated by the local
54 * provider (a `dev:`-prefixed bucket name, no cloud API calls) and the
55 * worker's `r2_bucket` binding is lowered onto the local workerd R2
56 * simulator. This exercises the full local roundtrip: put / get / head /
57 * list / delete through the native `env` binding.
58 */
59 test.provider(
60 "R2 bucket binding round-trips against the local simulator",
61 (stack) =>
62 Effect.gen(function* () {
63 yield* stack.destroy();
64
65 const deployed = yield* stack.deploy(
66 Effect.gen(function* () {
67 const bucket = yield* Cloudflare.R2.Bucket("LocalBucket", {
68 forceDestroy: true,
69 });
70 const worker = yield* Cloudflare.Worker("r2-local-worker", {
71 main: pathe.resolve(import.meta.dirname, "fixtures/r2-local-worker.ts"),
72 env: { BUCKET: bucket },
73 });
74 return { bucket, worker };
75 }),
76 );
77
78 // The local provider fabricates a `dev:` name — proof no cloud call
79 // ran — and the worker serves from the local dev proxy.
80 expect(deployed.bucket.bucketName).toMatch(/^dev:/);
81 expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
82
83 const body = (yield* getJsonReady(`${deployed.worker.url}/roundtrip`)) as {
84 text: string;
85 etag: string | null;
86 size: number | null;
87 keys: string[];
88 afterDelete: boolean;
89 };
90 expect(body.text).toBe("hello r2");
91 expect(body.etag).toBeTruthy();
92 expect(body.size).toBe("hello r2".length);
93 expect(body.keys).toEqual(["greeting.txt"]);
94 expect(body.afterDelete).toBe(true);
95
96 yield* stack.destroy();
97 }).pipe(logLevel),
98 {
99 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
100 timeout: 120_000,
101 },
102 );
103
104 /**
105 * The `*Local` R2 capability layers reach the local simulator through an
106 * ephemeral workerd gateway that emulates the R2 REST API over the native
107 * binding. An Action seeds (put/get/head/list/delete) a `dev:` bucket, and
108 * the worker's native binding then reads the same simulator storage —
109 * proving Node-side capability clients and worker bindings share one local
110 * data plane.
111 */
112 test.provider(
113 "ReadWriteBucketLocal Action seeds the local simulator in dev",
114 (stack) =>
115 Effect.gen(function* () {
116 yield* stack.destroy();
117
118 const deployed = yield* stack.deploy(
119 Effect.gen(function* () {
120 const bucket = yield* Cloudflare.R2.Bucket("ActionSeededBucket", {
121 forceDestroy: true,
122 });
123
124 const Seed = Action(
125 "Seed",
126 Effect.gen(function* () {
127 const client = yield* Cloudflare.R2.ReadWriteBucket(bucket);
128 return Effect.fn(function* () {
129 yield* client.put("seeded.txt", "from-action", {
130 httpMetadata: { contentType: "text/plain" },
131 });
132 yield* client.put("other.txt", "value");
133 const object = yield* client.get("seeded.txt");
134 const text = object === null ? null : yield* object.text();
135 const head = yield* client.head("seeded.txt");
136 const list = yield* client.list();
137 yield* client.delete("other.txt");
138 const afterDelete = yield* client.get("other.txt");
139 return {
140 text,
141 contentType: head?.httpMetadata?.contentType ?? null,
142 keys: list.objects.map((o) => o.key),
143 afterDelete: afterDelete === null,
144 };
145 });
146 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketLocal)),
147 );
148 const seeded = yield* Seed({});
149
150 const worker = yield* Cloudflare.Worker("r2-action-worker", {
151 main: pathe.resolve(import.meta.dirname, "fixtures/r2-local-worker.ts"),
152 env: { BUCKET: bucket },
153 });
154 return { bucket, worker, seeded };
155 }),
156 );
157
158 expect(deployed.bucket.bucketName).toMatch(/^dev:/);
159 expect(deployed.seeded.text).toBe("from-action");
160 expect(deployed.seeded.contentType).toBe("text/plain");
161 expect(deployed.seeded.keys.sort()).toEqual(["other.txt", "seeded.txt"]);
162 expect(deployed.seeded.afterDelete).toBe(true);
163
164 // The worker's native binding reads the same simulator storage the
165 // Action's gateway wrote to.
166 const body = (yield* getJsonReady(`${deployed.worker.url}/get?key=seeded.txt`)) as {
167 text: string | null;
168 };
169 expect(body.text).toBe("from-action");
170
171 yield* stack.destroy();
172 }).pipe(logLevel),
173 {
174 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
175 timeout: 120_000,
176 },
177 );
178
179 /**
180 * `Alchemy.remote()` opts the bucket OUT of local emulation: even under
181 * `alchemy dev` the bucket is created on real Cloudflare (a real bucket
182 * name, not `dev:`-prefixed) and the worker's `r2_bucket` binding proxies
183 * to it remotely. An out-of-band read through the cloud API proves the
184 * worker's write landed in the real bucket, and destroy removes it.
185 */
186 test.provider(
187 "Alchemy.remote() bucket runs live in dev",
188 (stack) =>
189 Effect.gen(function* () {
190 yield* stack.destroy();
191
192 const deployed = yield* stack.deploy(
193 Effect.gen(function* () {
194 const bucket = yield* Cloudflare.R2.Bucket("LiveDevBucket", {
195 forceDestroy: true,
196 }).pipe(Alchemy.remote());
197 const worker = yield* Cloudflare.Worker("r2-live-worker", {
198 main: pathe.resolve(import.meta.dirname, "fixtures/r2-local-worker.ts"),
199 env: { BUCKET: bucket },
200 });
201 return { bucket, worker };
202 }),
203 );
204
205 // A real bucket name — the live provider created it on Cloudflare.
206 expect(deployed.bucket.bucketName).not.toMatch(/^dev:/);
207
208 const seeded = (yield* getJsonReady(`${deployed.worker.url}/seed`)) as {
209 etag: string | null;
210 };
211 expect(seeded.etag).toBeTruthy();
212
213 // Out-of-band: the object is visible through the cloud API — the
214 // remote-proxied binding really hit the live bucket.
215 const { accountId } = yield* yield* CloudflareEnvironment;
216 const object = yield* r2.getObject({
217 accountId,
218 bucketName: deployed.bucket.bucketName,
219 objectName: "seed.txt",
220 });
221 const text = yield* object.body.pipe(Stream.decodeText, Stream.mkString);
222 expect(text).toBe("seeded by worker");
223
224 yield* stack.destroy();
225
226 // Destroy emptied and deleted the real bucket (stamped live mode).
227 const gone = yield* r2.getBucket({ accountId, bucketName: deployed.bucket.bucketName }).pipe(
228 Effect.as(false),
229 Effect.catchTag("NoSuchBucket", () => Effect.succeed(true)),
230 );
231 expect(gone).toBe(true);
232 }).pipe(logLevel),
233 {
234 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
235 timeout: 120_000,
236 },
237 );