@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, 06:00 UTC

main
ts 329 lines 12.5 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 workers from "@distilled.cloud/cloudflare/workers";
6 import * as Drift from "alchemy/Drift";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import type * as HttpClientResponse from "effect/http/HttpClientResponse";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14 import ReadBindingWorker from "./fixtures/read-binding.ts";
15 import ReadHttpWorker from "./fixtures/read-http.ts";
16 import ReadWriteBindingWorker from "./fixtures/readwrite-binding.ts";
17 import ReadWriteHttpWorker from "./fixtures/readwrite-http.ts";
18 import WriteBindingWorker from "./fixtures/write-binding.ts";
19 import WriteHttpWorker from "./fixtures/write-http.ts";
20
21 const { test } = Test.make({ providers: Cloudflare.providers() });
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
26 status: number;
27 body: string;
28 }> {}
29
30 // Bounded spaced schedule — caps total wait so a genuine failure
31 // surfaces fast instead of an uncapped exponential blowing past the
32 // test timeout while riding out cold-start propagation.
33 const ready = Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(30)]);
34
35 const untilOk = <E, R>(eff: Effect.Effect<HttpClientResponse.HttpClientResponse, E, R>) =>
36 eff.pipe(
37 Effect.flatMap((res) =>
38 res.status === 200
39 ? Effect.succeed(res)
40 : res.text.pipe(
41 Effect.flatMap((body) => Effect.fail(new WorkerNotReady({ status: res.status, body }))),
42 ),
43 ),
44 Effect.retry({
45 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
46 schedule: ready,
47 }),
48 );
49
50 class ValueMismatch extends Data.TaggedError("ValueMismatch")<{
51 expected: string;
52 actual: string | null;
53 }> {}
54
55 // KV is eventually consistent — a fresh write can take a while to be
56 // visible to a read on a different binding/edge, so allow generous
57 // retries on the read-back.
58 const propagate = Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(45)]);
59
60 const enc = encodeURIComponent;
61
62 /** Retry a read-back until KV propagation makes it consistent. */
63 const retryMismatch = <A, E, R>(eff: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
64 eff.pipe(
65 Effect.retry({
66 while: (e: E) => e instanceof ValueMismatch,
67 schedule: propagate,
68 }),
69 );
70
71 /** `GET /get` (text) and retry until the value matches. */
72 const expectValue = (base: string, key: string, expected: string) =>
73 untilOk(HttpClient.get(`${base}/get?key=${enc(key)}`)).pipe(
74 Effect.flatMap((res) => res.json),
75 Effect.flatMap((body) => {
76 const actual = (body as { value: string | null }).value;
77 return actual === expected
78 ? Effect.succeed(actual)
79 : Effect.fail(new ValueMismatch({ expected, actual }));
80 }),
81 retryMismatch,
82 );
83
84 /** `GET /get-json` and retry until the parsed value deep-matches. */
85 const expectJson = (base: string, key: string, expected: unknown) =>
86 untilOk(HttpClient.get(`${base}/get-json?key=${enc(key)}`)).pipe(
87 Effect.flatMap((res) => res.json),
88 Effect.flatMap((body) => {
89 const actual = (body as { value: unknown }).value;
90 return JSON.stringify(actual) === JSON.stringify(expected)
91 ? Effect.succeed(actual)
92 : Effect.fail(
93 new ValueMismatch({
94 expected: JSON.stringify(expected),
95 actual: JSON.stringify(actual),
96 }),
97 );
98 }),
99 retryMismatch,
100 );
101
102 /** `GET /get-bulk` and retry until every key resolves to its expected value. */
103 const expectBulk = (base: string, expected: Record<string, string>) =>
104 untilOk(HttpClient.get(`${base}/get-bulk?keys=${enc(Object.keys(expected).join(","))}`)).pipe(
105 Effect.flatMap((res) => res.json),
106 Effect.flatMap((body) => {
107 const values = (body as { values: Record<string, string | null> }).values;
108 return Object.entries(expected).every(([k, v]) => values[k] === v)
109 ? Effect.succeed(values)
110 : Effect.fail(
111 new ValueMismatch({
112 expected: JSON.stringify(expected),
113 actual: JSON.stringify(values),
114 }),
115 );
116 }),
117 retryMismatch,
118 );
119
120 /** `GET /getWithMetadata` and retry until value + metadata are present. */
121 const expectMeta = (base: string, key: string, expectedValue: string) =>
122 untilOk(HttpClient.get(`${base}/getWithMetadata?key=${enc(key)}`)).pipe(
123 Effect.flatMap((res) => res.json),
124 Effect.flatMap((body) => {
125 const b = body as {
126 value: string | null;
127 metadata: { tag?: string } | null;
128 };
129 return b.value === expectedValue && b.metadata?.tag === "meta"
130 ? Effect.succeed(b)
131 : Effect.fail(
132 new ValueMismatch({
133 expected: `${expectedValue}+{tag:meta}`,
134 actual: JSON.stringify(b),
135 }),
136 );
137 }),
138 retryMismatch,
139 );
140
141 /** `GET /list?prefix=` and retry until `key` appears under `prefix`. */
142 const expectListed = (base: string, prefix: string, key: string) =>
143 untilOk(HttpClient.get(`${base}/list?prefix=${enc(prefix)}`)).pipe(
144 Effect.flatMap((res) => res.json),
145 Effect.flatMap((body) => {
146 const keys = (body as { keys: string[] }).keys;
147 return keys.includes(key)
148 ? Effect.succeed(keys)
149 : Effect.fail(new ValueMismatch({ expected: key, actual: keys.join(",") }));
150 }),
151 retryMismatch,
152 );
153
154 /** `GET /get` and retry until the object is gone (`value === null`). */
155 const expectMissing = (base: string, key: string) =>
156 untilOk(HttpClient.get(`${base}/get?key=${enc(key)}`)).pipe(
157 Effect.flatMap((res) => res.json),
158 Effect.flatMap((body) => {
159 const actual = (body as { value: string | null }).value;
160 return actual === null
161 ? Effect.succeed(null)
162 : Effect.fail(new ValueMismatch({ expected: "<missing>", actual }));
163 }),
164 retryMismatch,
165 );
166
167 const put = (base: string, key: string, value: string) =>
168 untilOk(
169 HttpClient.execute(
170 HttpClientRequest.put(`${base}/put?key=${enc(key)}`).pipe(HttpClientRequest.bodyText(value)),
171 ),
172 );
173
174 const putMeta = (base: string, key: string, value: string) =>
175 untilOk(
176 HttpClient.execute(
177 HttpClientRequest.put(`${base}/put-meta?key=${enc(key)}`).pipe(
178 HttpClientRequest.bodyText(value),
179 ),
180 ),
181 );
182
183 const del = (base: string, key: string) =>
184 untilOk(HttpClient.execute(HttpClientRequest.make("DELETE")(`${base}/del?key=${enc(key)}`)));
185
186 /**
187 * Drive the FULL {@link ReadWriteNamespaceClient} surface through one
188 * read-write worker: every write method (`put`, `put` with metadata/ttl,
189 * `delete`) and every read method (`get` text/json, bulk `get`,
190 * `getWithMetadata`, `list` with prefix). Keys are namespaced by `label`
191 * so the binding and http runs stay independent on the shared namespace.
192 */
193 const exercise = (label: string, base: string) =>
194 Effect.gen(function* () {
195 const prefix = `${label}/`;
196 const k = (s: string) => `${prefix}${s}`;
197
198 // put + get (text)
199 expect((yield* put(base, k("v"), `${label}-v`)).status).toBe(200);
200 expect(yield* expectValue(base, k("v"), `${label}-v`)).toBe(`${label}-v`);
201
202 // put with metadata + ttl → getWithMetadata round-trips value + metadata
203 yield* putMeta(base, k("m"), `${label}-m`);
204 yield* expectMeta(base, k("m"), `${label}-m`);
205
206 // put JSON string → get(key, "json") parses it
207 yield* put(base, k("j"), JSON.stringify({ n: 1, label }));
208 yield* expectJson(base, k("j"), { n: 1, label });
209
210 // bulk get → get([...], "text") returns every key
211 yield* put(base, k("b1"), "B1");
212 yield* put(base, k("b2"), "B2");
213 yield* expectBulk(base, { [k("b1")]: "B1", [k("b2")]: "B2" });
214
215 // list({ prefix }) surfaces a written key under its prefix
216 yield* expectListed(base, prefix, k("v"));
217
218 // delete → get reports it gone
219 yield* del(base, k("v"));
220 yield* expectMissing(base, k("v"));
221 });
222
223 /**
224 * Deploys six Workers that all bind one shared KV namespace — read /
225 * write / read-write, each over the native Worker binding
226 * (`*NamespaceBinding`) and over a scoped HTTP API token
227 * (`*NamespaceHttp`) — then drives them over `fetch`:
228 *
229 * - the read-write worker exercises the entire client surface by itself
230 * (every read + write method), once per transport;
231 * - the split Read/Write workers prove the separate bindings agree on
232 * the namespace: write through Write, read back through Read, delete
233 * through Write, observe gone through Read.
234 */
235 test.provider.skipIf(!!process.env.FAST)(
236 "KV read/write/read-write bindings over binding + http",
237 (stack) =>
238 Effect.gen(function* () {
239 yield* stack.destroy();
240
241 const out = yield* stack.deploy(
242 Effect.gen(function* () {
243 const readBinding = yield* ReadBindingWorker;
244 const writeBinding = yield* WriteBindingWorker;
245 const readWriteBinding = yield* ReadWriteBindingWorker;
246 const readHttp = yield* ReadHttpWorker;
247 const writeHttp = yield* WriteHttpWorker;
248 const readWriteHttp = yield* ReadWriteHttpWorker;
249 return {
250 readBinding: readBinding.url,
251 writeBinding: writeBinding.url,
252 readWriteBinding: readWriteBinding.url,
253 readHttp: readHttp.url,
254 writeHttp: writeHttp.url,
255 readWriteHttp: readWriteHttp.url,
256 };
257 }),
258 );
259
260 const url = (u: unknown) => {
261 expect(u).toBeTypeOf("string");
262 return u as string;
263 };
264
265 // ── Full client surface through a single read-write worker ──
266 yield* exercise("rw-bind", url(out.readWriteBinding));
267 yield* exercise("rw-http", url(out.readWriteHttp));
268
269 // ── Split Read/Write bindings agree on the shared namespace ──
270 const crossWorker = (label: string, writeBase: string, readBase: string) =>
271 Effect.gen(function* () {
272 const key = `${label}-key`;
273 expect((yield* put(writeBase, key, `${label}-value`)).status).toBe(200);
274 expect(yield* expectValue(readBase, key, `${label}-value`)).toBe(`${label}-value`);
275 yield* del(writeBase, key);
276 yield* expectMissing(readBase, key);
277 });
278
279 yield* crossWorker("bind", url(out.writeBinding), url(out.readBinding));
280 yield* crossWorker("http", url(out.writeHttp), url(out.readHttp));
281
282 yield* stack.destroy();
283 }).pipe(logLevel),
284 {
285 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
286 timeout: 300_000,
287 },
288 );
289
290 // #1536: drift recreates a deleted Worker without its bindings, then
291 // attaches them — the native KV binding works again afterwards.
292 test.provider(
293 "drift repair recreates a deleted worker and restores its KV binding",
294 (stack) =>
295 Effect.gen(function* () {
296 const { accountId } = yield* yield* CloudflareEnvironment;
297 yield* stack.destroy();
298
299 const out = yield* stack.deploy(
300 Effect.gen(function* () {
301 const worker = yield* ReadWriteBindingWorker;
302 return { url: worker.url, workerName: worker.workerName };
303 }),
304 );
305 const base = out.url as string;
306 expect((yield* put(base, "drift-key", "before")).status).toBe(200);
307
308 yield* workers.deleteScript({ accountId, scriptName: out.workerName, force: true });
309
310 const target = { name: stack.name, stage: stack.stage };
311 const detected = yield* Drift.detect(target).pipe(Effect.provide(stack.state));
312 expect(detected.resources.KVReadWriteBindingWorker?.action).toBe("missing");
313 expect(detected.resources.KVBindingTestNamespace?.action).toBe("unchanged");
314
315 const repaired = yield* Drift.repair(target).pipe(Effect.provide(stack.state));
316 expect(repaired.resources.KVReadWriteBindingWorker?.action).toBe("recreated");
317
318 // the recreated worker reads the value written before the delete
319 expect(yield* expectValue(base, "drift-key", "before")).toBe("before");
320 expect((yield* put(base, "drift-key", "after")).status).toBe(200);
321 expect(yield* expectValue(base, "drift-key", "after")).toBe("after");
322
323 yield* stack.destroy();
324 }).pipe(logLevel),
325 {
326 tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
327 timeout: 240_000,
328 },
329 );