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

main
ts 311 lines 12 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import * as KV from "@alchemy.run/cloudflare/KV";
4 import { 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 { Action } from "alchemy/Action";
8 import * as Provider from "alchemy/Provider";
9 import { State } from "alchemy/State";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 test.provider(
20 "create and delete namespace with default props",
21 (stack) =>
22 Effect.gen(function* () {
23 const { accountId } = yield* yield* CloudflareEnvironment;
24
25 yield* stack.destroy();
26
27 const namespace = yield* stack.deploy(
28 Effect.gen(function* () {
29 return yield* KV.InstantNamespace("DefaultNamespace");
30 }),
31 );
32
33 expect(namespace.title).toBeDefined();
34 expect(namespace.namespaceId).toBeDefined();
35
36 const actualNamespace = yield* kv.getNamespace({
37 accountId,
38 namespaceId: namespace.namespaceId,
39 });
40 expect(actualNamespace.id).toEqual(namespace.namespaceId);
41 expect(actualNamespace.mode).toEqual("instant");
42
43 yield* stack.destroy();
44
45 yield* waitForNamespaceToBeDeleted(namespace.namespaceId, accountId);
46 }).pipe(logLevel),
47 { retry: 0, timeout: 120_000, tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"] },
48 );
49
50 test.provider(
51 "create, update, delete namespace",
52 (stack) =>
53 Effect.gen(function* () {
54 const { accountId } = yield* yield* CloudflareEnvironment;
55
56 yield* stack.destroy();
57
58 const namespace = yield* stack.deploy(
59 Effect.gen(function* () {
60 return yield* KV.InstantNamespace("TestNamespace");
61 }),
62 );
63
64 const actualNamespace = yield* kv.getNamespace({
65 accountId,
66 namespaceId: namespace.namespaceId,
67 });
68 expect(actualNamespace.id).toEqual(namespace.namespaceId);
69 expect(actualNamespace.mode).toEqual("instant");
70 expect(actualNamespace.title).toEqual(namespace.title);
71
72 const updatedNamespace = yield* stack.deploy(
73 Effect.gen(function* () {
74 return yield* KV.InstantNamespace("TestNamespace", {
75 title: namespace.title + "-updated",
76 });
77 }),
78 );
79
80 const actualUpdatedNamespace = yield* kv.getNamespace({
81 accountId,
82 namespaceId: updatedNamespace.namespaceId,
83 });
84 expect(actualUpdatedNamespace.mode).toEqual("instant");
85 expect(updatedNamespace.namespaceId).toEqual(namespace.namespaceId);
86 expect(actualUpdatedNamespace.title).toEqual(namespace.title + "-updated");
87 expect(actualUpdatedNamespace.id).toEqual(updatedNamespace.namespaceId);
88
89 yield* stack.destroy();
90
91 yield* waitForNamespaceToBeDeleted(namespace.namespaceId, accountId);
92 }).pipe(logLevel),
93 { retry: 0, timeout: 120_000, tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"] },
94 );
95
96 // Canonical `list()` test (account-scoped collection): deploy a real
97 // namespace, resolve the provider from context via `findProviderByType`,
98 // call `list()`, and assert the deployed namespace appears in the
99 // exhaustively-paginated result.
100 test.provider(
101 "list separates classic and instant namespaces",
102 (stack) =>
103 Effect.gen(function* () {
104 yield* stack.destroy();
105 const { instant, classic } = yield* stack.deploy(
106 Effect.gen(function* () {
107 return {
108 instant: yield* KV.InstantNamespace("Instant"),
109 classic: yield* KV.Namespace("Classic"),
110 };
111 }),
112 );
113 const instantProvider = yield* Provider.findProvider(KV.InstantNamespace);
114 const classicProvider = yield* Provider.findProvider(KV.Namespace);
115 const instantNamespaces = yield* instantProvider.list();
116 const classicNamespaces = yield* classicProvider.list();
117 expect(instantNamespaces.some((ns) => ns.namespaceId === instant.namespaceId)).toBe(true);
118 expect(instantNamespaces.some((ns) => ns.namespaceId === classic.namespaceId)).toBe(false);
119 expect(classicNamespaces.some((ns) => ns.namespaceId === classic.namespaceId)).toBe(true);
120 expect(classicNamespaces.some((ns) => ns.namespaceId === instant.namespaceId)).toBe(false);
121 yield* stack.destroy();
122 }).pipe(logLevel),
123 { retry: 0, timeout: 120_000, tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"] },
124 );
125
126 // Engine-level adoption: KV namespaces have no ownership signal (Cloudflare
127 // doesn't expose tags on KV), so a name match in `read` is treated as silent
128 // adoption. The test wipes local state mid-run while leaving the namespace
129 // on Cloudflare — this simulates a fresh state store seeing an existing
130 // resource with the same physical name.
131 test.provider(
132 "existing namespace (matching title) is silently adopted without --adopt",
133 (stack) =>
134 Effect.gen(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136
137 yield* stack.destroy();
138
139 // Phase 1: deploy normally so a real KV namespace exists on
140 // Cloudflare. No explicit `title` — the engine generates a
141 // random-suffixed physical name (collision-free across concurrent
142 // runs); the deploy output hands back the real title, which pins the
143 // namespace's identity for the adoption phase below.
144 const initial = yield* stack.deploy(
145 Effect.gen(function* () {
146 return yield* KV.InstantNamespace("AdoptableNamespace");
147 }),
148 );
149 const title = initial.title;
150 const initialId = initial.namespaceId;
151 expect(initialId).toBeDefined();
152
153 // Phase 2: wipe local state — the namespace stays on Cloudflare.
154 yield* Effect.gen(function* () {
155 const state = yield* yield* State;
156 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "AdoptableNamespace" });
157 }).pipe(Effect.provide(stack.state));
158
159 // Phase 3: redeploy without `adopt(true)`. The engine calls
160 // `provider.read`, which lists namespaces, matches by title, and
161 // returns plain attrs — silent adoption.
162 const adopted = yield* stack.deploy(
163 Effect.gen(function* () {
164 return yield* KV.InstantNamespace("AdoptableNamespace", { title });
165 }),
166 );
167
168 // Same physical namespace — adoption, not re-creation.
169 expect(adopted.namespaceId).toEqual(initialId);
170 expect(adopted.title).toEqual(title);
171
172 const persisted = yield* Effect.gen(function* () {
173 const state = yield* yield* State;
174 return yield* state.get({
175 stack: stack.name,
176 stage: stack.stage,
177 fqn: "AdoptableNamespace",
178 });
179 }).pipe(Effect.provide(stack.state));
180
181 expect((persisted as any)?.attr).toMatchObject({ namespaceId: initialId, title });
182
183 yield* stack.destroy();
184 yield* waitForNamespaceToBeDeleted(initialId, accountId);
185 }).pipe(logLevel),
186 { retry: 0, timeout: 120_000, tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"] },
187 );
188
189 const waitForNamespaceToBeDeleted = Effect.fn(function* (namespaceId: string, accountId: string) {
190 yield* kv.getNamespace({ accountId, namespaceId }).pipe(
191 Effect.flatMap(() => Effect.fail(new NamespaceStillExists())),
192 Effect.retry({
193 while: (e): e is NamespaceStillExists => e instanceof NamespaceStillExists,
194 schedule: Schedule.exponential(100),
195 times: 8,
196 }),
197 Effect.catchTag("NamespaceNotFound", () => Effect.void),
198 );
199 });
200
201 class NamespaceStillExists extends Data.TaggedError("NamespaceStillExists") {}
202
203 // One successful execution performs 1 put + 1 list + 1 delete ($0.30), plus reads/storage.
204 // Never reuse the 1,001-key local fixture here. Do not retry this whole test.
205 test.provider(
206 "Instant client: put, get, list all keys, and delete from an Action",
207 (stack) =>
208 Effect.gen(function* () {
209 yield* stack.destroy();
210
211 const out = yield* stack.deploy(
212 Effect.gen(function* () {
213 const namespace = yield* Cloudflare.KV.InstantNamespace("SeedNamespace");
214
215 const Seed = Action(
216 "Seed",
217 Effect.gen(function* () {
218 const kv = yield* Cloudflare.KV.ReadWriteNamespace(namespace);
219 // Accessor — resolved at apply time against the tracker.
220 const namespaceId = yield* namespace.namespaceId;
221
222 return Effect.fn(function* () {
223 yield* kv.put("greeting", "hello world");
224
225 // Retry only propagation mismatches; surface API errors immediately.
226 const value = yield* kv.get("greeting").pipe(
227 Effect.flatMap((v) =>
228 v === "hello world"
229 ? Effect.succeed(v)
230 : Effect.fail("not yet propagated" as const),
231 ),
232 Effect.retry({
233 schedule: Schedule.spaced("1 second"),
234 while: (error) => error === "not yet propagated",
235 times: 10,
236 }),
237 );
238
239 const listed = yield* kv.list();
240 expect(listed.list_complete).toBe(true);
241 const names = listed.keys.map((k) => k.name);
242
243 // Instant allows only one write per namespace per second.
244 yield* Effect.sleep("1 second");
245 yield* kv.delete("greeting");
246
247 const afterDelete = yield* kv.get("greeting").pipe(
248 Effect.flatMap((v) =>
249 v === null ? Effect.succeed(v) : Effect.fail("not yet deleted" as const),
250 ),
251 Effect.retry({
252 schedule: Schedule.spaced("1 second"),
253 while: (error) => error === "not yet deleted",
254 times: 10,
255 }),
256 );
257
258 return {
259 namespaceId: yield* namespaceId,
260 value,
261 names,
262 afterDelete,
263 };
264 });
265 }).pipe(Effect.provide(Cloudflare.KV.ReadWriteNamespaceLocal)),
266 );
267
268 return yield* Seed({});
269 }),
270 );
271
272 expect(out.namespaceId).toBeTruthy();
273 expect(out.value).toBe("hello world");
274 expect(out.names).toContain("greeting");
275 expect(out.afterDelete).toBeNull();
276
277 yield* stack.destroy();
278 }).pipe(logLevel),
279 {
280 tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"],
281 retry: 0,
282 timeout: 120_000,
283 },
284 );
285
286 test.provider(
287 "switching namespace modes replaces storage while reusing an explicit title",
288 (stack) =>
289 Effect.gen(function* () {
290 yield* stack.destroy();
291 const { accountId } = yield* yield* CloudflareEnvironment;
292 const classic = yield* stack.deploy(KV.Namespace("Config"));
293 const instant = yield* stack.deploy(KV.InstantNamespace("Config", { title: classic.title }));
294 expect(instant.namespaceId).not.toBe(classic.namespaceId);
295 expect(instant.title).toBe(classic.title);
296 expect((yield* kv.getNamespace({ accountId, namespaceId: instant.namespaceId })).mode).toBe(
297 "instant",
298 );
299 yield* waitForNamespaceToBeDeleted(classic.namespaceId, accountId);
300 const restored = yield* stack.deploy(KV.Namespace("Config", { title: classic.title }));
301 expect(restored.namespaceId).not.toBe(instant.namespaceId);
302 expect(restored.title).toBe(classic.title);
303 expect(
304 (yield* kv.getNamespace({ accountId, namespaceId: restored.namespaceId })).mode,
305 ).not.toBe("instant");
306 yield* waitForNamespaceToBeDeleted(instant.namespaceId, accountId);
307 yield* stack.destroy();
308 yield* waitForNamespaceToBeDeleted(restored.namespaceId, accountId);
309 }).pipe(logLevel),
310 { retry: 0, timeout: 120_000, tags: ["provider:cloudflare", "provider:cloudflare:kv", "live"] },
311 );