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

main
ts 183 lines 7.12 KB
Raw
1 import { randomBytes } from "node:crypto";
2 import * as Fly from "@alchemy.run/fly";
3 import { checksPassing, configuredCheckNames } from "@alchemy.run/fly/replicas";
4 import { expect } from "@alchemy.run/test";
5 import type { ScratchStack } from "@alchemy.run/test/Alchemy";
6 import * as machines from "@distilled.cloud/fly-io/machines";
7 import * as Retry from "@distilled.cloud/fly-io/Retry";
8 import * as Cause from "effect/Cause";
9 import * as Effect from "effect/Effect";
10 import { FileSystem } from "effect/FileSystem";
11 import * as FetchHttpClient from "effect/http/FetchHttpClient";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as HttpClientRequest from "effect/http/HttpClientRequest";
14 import * as Path from "effect/Path";
15 import * as Redacted from "effect/Redacted";
16 import * as Schedule from "effect/Schedule";
17 import * as Schema from "effect/Schema";
18
19 const Receipt = Schema.Struct({
20 machineId: Schema.String,
21 ready: Schema.Boolean,
22 });
23
24 // HTTP failures can retain the authenticated request, including on defects.
25 const privateFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
26 effect.pipe(
27 Effect.catchCause((cause) =>
28 Effect.failCause(
29 Cause.fromReasons(
30 cause.reasons.map((reason) =>
31 Cause.isFailReason(reason)
32 ? Cause.makeFailReason(new Error("Readiness control request failed"))
33 : Cause.isDieReason(reason)
34 ? Cause.makeDieReason(new Error("Readiness control request defect"))
35 : Cause.makeInterruptReason(reason.fiberId),
36 ),
37 ),
38 ),
39 ),
40 );
41
42 export const makeReadinessControl = () =>
43 Effect.gen(function* () {
44 const token = yield* Effect.sync(() =>
45 Redacted.make(
46 Array.from(randomBytes(32), (byte) => byte.toString(16).padStart(2, "0")).join(""),
47 ),
48 );
49 const fs = yield* FileSystem;
50 const path = yield* Path.Path;
51 const script = yield* fs.readFileString(
52 yield* path.fromFileUrl(new URL("./http-readiness-control.mjs", import.meta.url)),
53 );
54 const infrastructure = Effect.gen(function* () {
55 const app = yield* Fly.App("Site");
56 const secret = yield* Fly.Secret("ReadinessControl", {
57 app,
58 name: "READINESS_CONTROL_TOKEN",
59 value: token,
60 });
61 yield* Fly.IpAssignment("Public", { app, type: "shared_v4" });
62 return { app, secret };
63 });
64 const ready = {
65 type: "http" as const,
66 port: 3000,
67 path: "/ready",
68 interval: "2s",
69 timeout: "1s",
70 };
71 const deployApp = (stack: ScratchStack) =>
72 stack.deploy(infrastructure.pipe(Effect.map(({ app }) => app)));
73 const deployWorker = (stack: ScratchStack, version: string) =>
74 stack.deploy(
75 Effect.gen(function* () {
76 const { app, secret } = yield* infrastructure;
77 return yield* Fly.Machine("Worker", {
78 app,
79 image: "node:22-alpine",
80 init: { exec: ["node", "--input-type=module", "-e", script] },
81 env: {
82 VERSION: version,
83 READINESS_CONTROL_SECRET: secret.name,
84 },
85 checks: { ready },
86 services: [
87 {
88 protocol: "tcp",
89 internalPort: 3000,
90 ports: [{ port: 443, handlers: ["tls", "http"] }],
91 autostop: "off",
92 autostart: true,
93 checks: [ready],
94 },
95 ],
96 deploy: { strategy: "bluegreen", healthTimeout: "30 seconds" },
97 shutdown: { signal: "SIGTERM", timeout: "5 seconds" },
98 });
99 }),
100 );
101 const request = (appName: string, machineId: string, off: boolean) =>
102 Effect.gen(function* () {
103 const url = `https://${appName}.fly.dev`;
104 const response = yield* HttpClient.execute(
105 (off
106 ? HttpClientRequest.post(`${url}/readiness/off`)
107 : HttpClientRequest.get(`${url}/ready`)
108 ).pipe(
109 HttpClientRequest.bearerToken(token),
110 HttpClientRequest.setHeader("fly-force-instance-id", machineId),
111 HttpClientRequest.setHeader("x-readiness-machine-id", machineId),
112 ),
113 );
114 if (response.status !== 200)
115 return yield* Effect.fail(new Error("Unexpected readiness status"));
116 return yield* response.json.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Receipt)));
117 }).pipe(Effect.timeout("10 seconds"), Effect.provide(FetchHttpClient.layer), privateFailure);
118 const turnOff = (appName: string, machineId: string) =>
119 Effect.gen(function* () {
120 const observe = machines
121 .getMachine({ app_name: appName, machine_id: machineId })
122 .pipe(Retry.none, Effect.timeout("10 seconds"));
123 const before = yield* observe.pipe(
124 Effect.repeat({
125 until: (machine) => checksPassing(machine, machine.config),
126 times: 8,
127 schedule: Schedule.spaced("1 second"),
128 }),
129 Effect.timeout("10 seconds"),
130 );
131 expect(before.id).toBe(machineId);
132 expect(before.cordoned).toBe(false);
133 const checkNames = configuredCheckNames(before.config);
134 expect(checkNames).toEqual(["ready", "servicecheck-00-http-3000"]);
135 expect(checksPassing(before, before.config)).toBe(true);
136 const healthy = yield* request(appName, machineId, false).pipe(
137 Effect.retry({ times: 8, schedule: Schedule.spaced("1 second") }),
138 Effect.timeout("30 seconds"),
139 );
140 expect(healthy).toEqual({ machineId, ready: true });
141 const receipt = yield* request(appName, machineId, true);
142 expect(receipt).toEqual({ machineId, ready: false });
143 const failed = (machine: machines.Machine) =>
144 checkNames.every((name) =>
145 machine.checks?.some((check) => check.name === name && check.status === "critical"),
146 );
147 // Hold the provider barrier until Fly has observed the real file change.
148 const after = yield* observe.pipe(
149 Effect.repeat({
150 until: failed,
151 times: 8,
152 schedule: Schedule.spaced("1 second"),
153 }),
154 Effect.timeout("20 seconds"),
155 );
156 expect(after.id).toBe(machineId);
157 expect(after.cordoned).toBe(false);
158 expect(failed(after)).toBe(true);
159 }).pipe(Effect.provide(FetchHttpClient.layer), Effect.timeout("25 seconds"));
160 return { deployApp, deployWorker, turnOff };
161 });
162
163 export const repairReadiness = (appName: string, machineId: string) =>
164 Effect.gen(function* () {
165 const unleased = yield* machines
166 .getMachineLease({ app_name: appName, machine_id: machineId })
167 .pipe(
168 Retry.none,
169 Effect.timeout("15 seconds"),
170 Effect.as(false),
171 Effect.catchTag("NotFound", () => Effect.succeed(true)),
172 );
173 expect(unleased).toBe(true);
174 const repaired = yield* machines
175 .execMachine({
176 app_name: appName,
177 machine_id: machineId,
178 command: ["touch", "/tmp/ready"],
179 timeout: 5,
180 })
181 .pipe(Retry.none, Effect.timeout("15 seconds"));
182 expect(repaired.exit_code).toBe(0);
183 }).pipe(Effect.provide(FetchHttpClient.layer));