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

main
ts 78 lines 2.72 KB
Raw
1 import { expect } from "@alchemy.run/test";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as HttpClientRequest from "effect/http/HttpClientRequest";
5 import * as Schedule from "effect/Schedule";
6 import { requestWorker, waitUntilStable } from "../../Utils/WorkerRequest.ts";
7
8 class NotReady extends Data.TaggedError("NotReady")<{
9 readonly url: string;
10 readonly status: number;
11 }> {}
12
13 class NotYet extends Data.TaggedError("NotYet")<{
14 readonly url: string;
15 readonly body: unknown;
16 }> {}
17
18 /** POST a counter route and return its JSON, retrying while the Worker starts. */
19 export const call = (url: string) =>
20 Effect.gen(function* () {
21 const response = yield* requestWorker(HttpClientRequest.post(url)).pipe(
22 Effect.flatMap((response) =>
23 response.status === 200
24 ? Effect.succeed(response)
25 : Effect.fail(new NotReady({ url, status: response.status })),
26 ),
27 Effect.retry({
28 while: (error) => error._tag === "NotReady" && error.status === 404,
29 schedule: Schedule.spaced("2 seconds"),
30 times: 10,
31 }),
32 );
33 return (yield* response.json) as unknown;
34 });
35
36 /** Poll a route until it answers `expected`: views and sagas catch up after the command. */
37 export const eventually = (url: string, expected: unknown) =>
38 call(url).pipe(
39 Effect.flatMap((body) =>
40 JSON.stringify(body) === JSON.stringify(expected)
41 ? Effect.succeed(body)
42 : Effect.fail(new NotYet({ url, body })),
43 ),
44 Effect.retry({
45 while: (error) => error._tag === "NotYet",
46 schedule: Schedule.spaced("1 second"),
47 times: 30,
48 }),
49 );
50
51 /**
52 * Two increments of `c-1` reach its aggregate, its view, and, through the
53 * policy and the saga, its Echo; `c-2` stays untouched.
54 */
55 export const roundTrip = (url: string) =>
56 Effect.gen(function* () {
57 expect(yield* call(`${url}/state/c-1`)).toEqual({ total: 0 });
58 expect(yield* call(`${url}/increment/c-1`)).toEqual({ total: 2 });
59 expect(yield* call(`${url}/increment/c-1`)).toEqual({ total: 4 });
60 yield* eventually(`${url}/total/c-1`, { total: 4 });
61 // The saga runs once per counter, with the first increment.
62 yield* eventually(`${url}/echo/c-1`, { total: 2 });
63 // A different key is a different instance.
64 expect(yield* call(`${url}/state/c-2`)).toEqual({ total: 0 });
65 });
66
67 /**
68 * Wait until every host serves the version deployed on `platform`: Cloudflare
69 * rolls a new version out host by host.
70 */
71 export const waitForPlatform = (url: string, platform: "eu" | "unrestricted") =>
72 waitUntilStable(
73 `${platform} platform at ${url}`,
74 Effect.map(
75 call(`${url}/platform`),
76 (body) => JSON.stringify(body) === JSON.stringify({ platform }),
77 ),
78 );