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

main
ts 175 lines 7.3 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { CloudflareApiLive } from "@alchemy.run/cloudflare/Providers";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as durableObjects from "@distilled.cloud/cloudflare/durable-objects";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Fiber from "effect/Fiber";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import { requestWorker } from "../Utils/WorkerRequest.ts";
15 import WorkerV0 from "./fixtures/version/v0.ts";
16 import WorkerV1 from "./fixtures/version/v1.ts";
17
18 /** A route answered with something other than what the test waits for. */
19 class NotYet extends Data.TaggedError("NotYet")<{
20 readonly status: number;
21 readonly body: string;
22 }> {}
23
24 /** Call a route on a fresh connection, so the request reaches the latest deployment. */
25 const call = (url: string, method: "GET" | "POST", path: string) =>
26 requestWorker(
27 (method === "GET" ? HttpClientRequest.get : HttpClientRequest.post)(`${url}${path}`).pipe(
28 HttpClientRequest.setHeaders({ connection: "close", "cache-control": "no-cache" }),
29 ),
30 ).pipe(
31 Effect.retry({
32 while: (error) => error._tag === "HttpClientError",
33 schedule: Schedule.spaced("1 second"),
34 times: 5,
35 }),
36 Effect.flatMap((res) =>
37 res.text.pipe(
38 Effect.flatMap((body) =>
39 res.status === 200
40 ? Effect.succeed(body)
41 : Effect.fail(new NotYet({ status: res.status, body })),
42 ),
43 ),
44 ),
45 );
46
47 /** Wait until the Worker serves `version`: a redeploy takes a few seconds to roll out. */
48 const serving = (url: string, version: string) =>
49 call(url, "GET", "/version").pipe(
50 Effect.filterOrFail(
51 (body) => body === version,
52 (body) => new NotYet({ status: 200, body }),
53 ),
54 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 90 }),
55 );
56
57 /**
58 * Poll a view until an account's row is `expected`. An object keeps the code
59 * from before a deploy until it has been idle, so a row can answer from the
60 * old code for a while: allow a few minutes.
61 */
62 const row = (url: string, view: "summary" | "latest", account: string, net: number) =>
63 call(url, "GET", `/${view}/${account}`).pipe(
64 Effect.map((body) => JSON.parse(body) as { net: number } | null),
65 Effect.repeat({
66 schedule: Schedule.spaced("2 seconds"),
67 until: (value) => value?.net === net,
68 times: 150,
69 }),
70 );
71
72 /** Poll a view row like `row`, but within a minute. */
73 const soon = (url: string, view: "summary" | "latest", account: string, net: number) =>
74 call(url, "GET", `/${view}/${account}`).pipe(
75 Effect.map((body) => JSON.parse(body) as { net: number } | null),
76 Effect.repeat({
77 schedule: Schedule.spaced("2 seconds"),
78 until: (value) => value?.net === net,
79 times: 30,
80 }),
81 );
82
83 /** Read `path` every 250 ms, without retrying, until interrupted: every answer, in order. */
84 const watch = (url: string, path: string, answers: Array<{ status: number; body: string }>) =>
85 HttpClient.execute(
86 HttpClientRequest.get(`${url}${path}`).pipe(HttpClientRequest.setHeader("connection", "close")),
87 ).pipe(
88 Effect.flatMap((res) => Effect.map(res.text, (body) => ({ status: res.status, body }))),
89 Effect.catch((error) => Effect.succeed({ status: 0, body: String(error) })),
90 Effect.tap((answer) => Effect.sync(() => answers.push(answer))),
91 Effect.repeat(Schedule.spaced("250 millis")),
92 );
93
94 /** The model's Durable Object classes on the Worker, by class name. */
95 const classes = (scriptName: string) =>
96 Effect.gen(function* () {
97 const { accountId } = yield* yield* CloudflareEnvironment;
98 const namespaces = yield* durableObjects.listNamespaces
99 .items({ accountId })
100 .pipe(Stream.runCollect);
101 return Object.fromEntries(
102 namespaces.flatMap((namespace) =>
103 namespace.script === scriptName && namespace.class?.match(/^Bank\.(Summary|Latest)View/)
104 ? [[namespace.class, namespace.id]]
105 : [],
106 ),
107 );
108 }).pipe(Effect.provide(CloudflareApiLive()), Effect.scoped);
109
110 for (const dev of [true, false]) {
111 describe(dev ? "local view versions" : "live view versions", () => {
112 const { test } = Test.make({ providers: Cloudflare.providers(), dev });
113
114 test.provider(
115 `${dev ? "local" : "live"}: bumping a view's version rebuilds it in place, and what reads it from the history`,
116 (stack) =>
117 Effect.gen(function* () {
118 yield* stack.destroy();
119 const { worker } = yield* stack.deploy(
120 Effect.gen(function* () {
121 return { worker: yield* WorkerV0 };
122 }),
123 );
124 const url = worker.url!.replace(/\/+$/, "");
125 yield* serving(url, "v0");
126 yield* call(url, "POST", "/deposit/a-1/10");
127 yield* call(url, "POST", "/withdraw/a-1/4");
128 yield* call(url, "POST", "/deposit/a-2/3");
129 // Version 0 counts deposits only.
130 expect(yield* row(url, "summary", "a-1", 10)).toEqual({ net: 10 });
131 expect(yield* row(url, "latest", "a-1", 10)).toEqual({ net: 10 });
132 const before = dev ? {} : yield* classes(worker.workerName);
133
134 // Live, keep a-1's summary busy through the deploy, so its object stays on
135 // the code from before it (it moves once idle): every read must still answer.
136 const answers: Array<{ status: number; body: string }> = [];
137 const watcher = dev
138 ? undefined
139 : yield* Effect.forkChild(watch(url, "/summary/a-1", answers));
140 yield* stack.deploy(
141 Effect.gen(function* () {
142 return { worker: yield* WorkerV1 };
143 }),
144 );
145 yield* serving(url, "v1");
146 // The withdrawal, which the old rows never received, counts: at once, even
147 // while the busy object runs the old code.
148 expect(yield* soon(url, "summary", "a-1", 6)).toEqual({ net: 6 });
149 if (watcher) {
150 yield* Fiber.interrupt(watcher);
151 expect(answers.length).toBeGreaterThan(10);
152 expect(answers.filter((answer) => answer.status !== 200)).toEqual([]);
153 }
154 expect(yield* row(url, "summary", "a-2", 3)).toEqual({ net: 3 });
155 // The view built on it is rebuilt from the summary's new rows.
156 expect(yield* row(url, "latest", "a-1", 6)).toEqual({ net: 6 });
157 // And it keeps up afterwards.
158 yield* call(url, "POST", "/withdraw/a-1/1");
159 expect(yield* row(url, "summary", "a-1", 5)).toEqual({ net: 5 });
160 expect(yield* row(url, "latest", "a-1", 5)).toEqual({ net: 5 });
161
162 if (!dev) {
163 const after = yield* classes(worker.workerName);
164 // The summary was rebuilt in its own storage; the latest view in a new one.
165 expect(after["Bank.SummaryView"]).toBe(before["Bank.SummaryView"]);
166 expect(after["Bank.SummaryViewV1"]).toBeUndefined();
167 expect(after["Bank.LatestViewV1"]).toBeDefined();
168 }
169
170 yield* stack.destroy();
171 }),
172 { timeout: 900_000 },
173 );
174 });
175 }