@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 252 lines 9.35 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 kv from "@distilled.cloud/cloudflare/kv";
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 KV Namespace resource is emulated by the local
54 * provider (a `dev:` id, no cloud API calls) and the worker's `kv_namespace`
55 * binding is lowered onto the local workerd KV simulator. This exercises the
56 * full local roundtrip: put / get / list / delete through the native `env`
57 * binding.
58 */
59 test.provider(
60 "KV namespace 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 kv = yield* Cloudflare.KV.Namespace("LocalKV");
68 const worker = yield* Cloudflare.Worker("kv-local-worker", {
69 main: pathe.resolve(import.meta.dirname, "fixtures/kv-local-worker.ts"),
70 env: { KV: kv },
71 });
72 return { kv, worker };
73 }),
74 );
75
76 // The local provider fabricates a `dev:` id — proof no cloud call ran
77 // — and the worker serves from the local dev proxy.
78 expect(deployed.kv.namespaceId).toMatch(/^dev:/);
79 expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/);
80
81 const body = (yield* getJsonReady(`${deployed.worker.url}/roundtrip`)) as {
82 value: string;
83 value2: string;
84 metadata: { hello: string };
85 keys: string[];
86 afterDelete: string | null;
87 };
88 expect(body.value).toBe("value1");
89 expect(body.value2).toBe("value2");
90 expect(body.metadata).toEqual({ hello: "world" });
91 expect(body.keys.sort()).toEqual(["key1", "key2"]);
92 expect(body.afterDelete).toBeNull();
93
94 yield* stack.destroy();
95 }).pipe(logLevel),
96 {
97 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "local"],
98 timeout: 120_000,
99 },
100 );
101
102 /**
103 * The `*Local` KV capability layers reach the local simulator through an
104 * ephemeral workerd gateway that emulates the KV REST API over the native
105 * binding. An Action seeds (put/get/getWithMetadata/list/delete) a `dev:`
106 * namespace, and the worker's native binding then reads the same simulator
107 * storage — proving Node-side capability clients and worker bindings share
108 * one local data plane.
109 */
110 test.provider(
111 "ReadWriteNamespaceLocal Action seeds the local simulator in dev",
112 (stack) =>
113 Effect.gen(function* () {
114 yield* stack.destroy();
115
116 const deployed = yield* stack.deploy(
117 Effect.gen(function* () {
118 const ns = yield* Cloudflare.KV.Namespace("ActionSeededKV");
119
120 const Seed = Action(
121 "Seed",
122 Effect.gen(function* () {
123 const client = yield* Cloudflare.KV.ReadWriteNamespace(ns);
124 return Effect.fn(function* () {
125 yield* client.put("seeded", "from-action", {
126 metadata: { source: "action" },
127 });
128 yield* client.put("other", "value");
129 const value = yield* client.get("seeded");
130 const withMetadata = yield* client.getWithMetadata("seeded");
131 const list = yield* client.list();
132 yield* client.delete("other");
133 const afterDelete = yield* client.get("other");
134 return {
135 value,
136 metadata: withMetadata.metadata,
137 keys: list.keys.map((k) => k.name),
138 afterDelete,
139 };
140 });
141 }).pipe(Effect.provide(Cloudflare.KV.ReadWriteNamespaceLocal)),
142 );
143 const seeded = yield* Seed({});
144
145 const worker = yield* Cloudflare.Worker("kv-action-worker", {
146 main: pathe.resolve(import.meta.dirname, "fixtures/kv-local-worker.ts"),
147 env: { KV: ns },
148 });
149 return { ns, worker, seeded };
150 }),
151 );
152
153 expect(deployed.ns.namespaceId).toMatch(/^dev:/);
154 expect(deployed.seeded.value).toBe("from-action");
155 expect(deployed.seeded.metadata).toEqual({ source: "action" });
156 expect(deployed.seeded.keys.sort()).toEqual(["other", "seeded"]);
157 expect(deployed.seeded.afterDelete).toBeNull();
158
159 // The worker's native binding reads the same simulator storage the
160 // Action's gateway wrote to.
161 const body = (yield* getJsonReady(`${deployed.worker.url}/get?key=seeded`)) as {
162 value: string | null;
163 };
164 expect(body.value).toBe("from-action");
165
166 yield* stack.destroy();
167 }).pipe(logLevel),
168 {
169 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "local"],
170 timeout: 120_000,
171 },
172 );
173
174 /**
175 * `Alchemy.remote()` opts a resource OUT of local emulation: even under
176 * `alchemy dev` the namespace is created on real Cloudflare (live provider)
177 * and the worker's binding proxies to it remotely, while a sibling default
178 * namespace in the same stack stays fully local. Out-of-band reads through
179 * the cloud API prove the worker's writes landed in the real namespace.
180 */
181 test.provider(
182 "Alchemy.remote() namespace runs live in dev alongside a local one",
183 (stack) =>
184 Effect.gen(function* () {
185 yield* stack.destroy();
186
187 const deployed = yield* stack.deploy(
188 Effect.gen(function* () {
189 const localKv = yield* Cloudflare.KV.Namespace("MixedLocalKV");
190 const liveKv = yield* Cloudflare.KV.Namespace("MixedLiveKV").pipe(Alchemy.remote());
191 const worker = yield* Cloudflare.Worker("kv-mixed-worker", {
192 main: pathe.resolve(import.meta.dirname, "fixtures/kv-local-worker.ts"),
193 env: { KV: localKv, KV_LIVE: liveKv },
194 });
195 return { localKv, liveKv, worker };
196 }),
197 );
198
199 // The default namespace is emulated; the remote() one is real.
200 expect(deployed.localKv.namespaceId).toMatch(/^dev:/);
201 expect(deployed.liveKv.namespaceId).not.toMatch(/^dev:/);
202
203 // Both bindings round-trip through the same locally-served worker.
204 const local = (yield* getJsonReady(`${deployed.worker.url}/roundtrip`)) as { value: string };
205 expect(local.value).toBe("value1");
206
207 const live = (yield* getJsonReady(`${deployed.worker.url}/roundtrip?binding=KV_LIVE`)) as {
208 value: string;
209 value2: string;
210 };
211 expect(live.value).toBe("value1");
212 expect(live.value2).toBe("value2");
213
214 // Out-of-band: the worker's write is visible through the cloud API —
215 // the remote-proxied binding really hit the live namespace.
216 const { accountId } = yield* yield* CloudflareEnvironment;
217 const value = yield* kv
218 .getNamespaceValue({
219 accountId,
220 namespaceId: deployed.liveKv.namespaceId,
221 keyName: "key2",
222 })
223 .pipe(
224 Effect.flatMap((res) =>
225 Effect.tryPromise(() =>
226 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
227 ),
228 ),
229 );
230 expect(value).toBe("value2");
231
232 yield* stack.destroy();
233
234 // The live namespace was deleted from the cloud on destroy (its state
235 // row is stamped live, so the live provider handles the delete even
236 // in a dev run).
237 const gone = yield* kv
238 .getNamespace({
239 accountId,
240 namespaceId: deployed.liveKv.namespaceId,
241 })
242 .pipe(
243 Effect.as(false),
244 Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)),
245 );
246 expect(gone).toBe(true);
247 }).pipe(logLevel),
248 {
249 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
250 timeout: 120_000,
251 },
252 );