@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 257 lines 9.4 KB
Raw
1 import { execFile } from "node:child_process";
2 import * as Floci from "@alchemy.run/aws/Local/Floci";
3 import { describe, expect, it } from "@alchemy.run/test";
4 import * as Effect from "effect/Effect";
5 /**
6 * Lifecycle tests for `ensureFloci`, the manager that owns the floci
7 * emulator container.
8 *
9 * Runs against the real Docker daemon. The bugs this suite pins are Docker
10 * behaviors (a `docker start` that no-ops on a running-but-unbound
11 * container, a run that leaves nothing published), so a mocked `docker`
12 * would only encode assumptions.
13 *
14 * Every case gets its own container name and gateway port and publishes no
15 * opportunistic ELB/CloudFront edge ports, so the suite never touches the
16 * shared `alchemy-floci` container or competes with it for host ports.
17 */
18
19 const docker = (args: ReadonlyArray<string>) =>
20 Effect.callback<string, Error>((resume) => {
21 const child = execFile("docker", args as Array<string>, (error, stdout, stderr) =>
22 resume(
23 error
24 ? Effect.fail(new Error(`docker ${args.join(" ")}: ${stderr.trim() || error.message}`))
25 : Effect.succeed(stdout.trim()),
26 ),
27 );
28 return Effect.sync(() => child.kill());
29 });
30
31 const containerId = (name: string) => docker(["inspect", "--format", "{{.Id}}", name]);
32
33 const isRunning = (name: string) =>
34 docker(["inspect", "--format", "{{.State.Running}}", name]).pipe(
35 Effect.map((out) => out === "true"),
36 Effect.orElseSucceed(() => false),
37 );
38
39 /**
40 * A config for an isolated test container: its own name and gateway port,
41 * no ELB/CloudFront edge ports. `external: false` keeps the suite on the
42 * managed-container path even when the runner exports
43 * `ALCHEMY_FLOCI_EXTERNAL=1` for the shared gateway.
44 */
45 const isolated = (name: string, port: number, overrides?: Floci.FlociConfig) =>
46 Effect.gen(function* () {
47 const containerName = `floci-lifecycle-${name}`;
48 yield* Floci.destroyFloci(containerName).pipe(Effect.ignore);
49 yield* Effect.addFinalizer(() => Floci.destroyFloci(containerName).pipe(Effect.ignore));
50 return {
51 external: false,
52 containerName,
53 port,
54 elbListenerPorts: [],
55 cloudfrontEdgePorts: [],
56 readinessTimeout: "90 seconds",
57 ...overrides,
58 } satisfies Floci.FlociConfig;
59 });
60
61 const timed = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
62 Effect.gen(function* () {
63 const start = yield* Effect.sync(() => Date.now());
64 const value = yield* effect;
65 const elapsed = (yield* Effect.sync(() => Date.now())) - start;
66 return { value, elapsed };
67 });
68
69 /**
70 * Publish `port` from a throwaway container for the scope. Docker refuses
71 * to publish it again ("port is already allocated") on every platform,
72 * while the manager's host-side probe may or may not see it (it does behind
73 * Linux's docker-proxy, it doesn't on Docker Desktop) — the probe-invisible
74 * conflict #2214 reported for rootless Docker and Tailscale listeners.
75 */
76 const holdPort = (name: string, port: number) =>
77 Effect.acquireRelease(
78 docker(["rm", "-f", name]).pipe(
79 Effect.ignore,
80 Effect.andThen(
81 docker(["run", "-d", "--name", name, "-p", `${port}:${port}`, Floci.DEFAULT_FLOCI_IMAGE]),
82 ),
83 ),
84 () => docker(["rm", "-f", name]).pipe(Effect.ignore),
85 );
86
87 describe.sequential("FlociLifecycle", { tags: ["provider:aws", "local"] }, () => {
88 it.live(
89 "starts a fresh container and publishes the gateway",
90 () =>
91 Effect.gen(function* () {
92 const config = yield* isolated("fresh", 4591);
93
94 const instance = yield* Floci.ensureFloci(config);
95
96 expect(instance).toEqual({
97 endpoint: "http://localhost:4591",
98 managed: true,
99 containerName: config.containerName,
100 });
101 expect(yield* docker(["port", config.containerName, "4566/tcp"])).toContain(":4591");
102 yield* Floci.checkHealth(instance.endpoint);
103 }),
104 { timeout: 180_000 },
105 );
106
107 it.live(
108 "reattaches to a serving container without recreating it",
109 () =>
110 Effect.gen(function* () {
111 const config = yield* isolated("reattach", 4592);
112 yield* Floci.ensureFloci(config);
113 const id = yield* containerId(config.containerName);
114
115 const { value: instance, elapsed } = yield* timed(Floci.ensureFloci(config));
116
117 expect(instance.endpoint).toBe("http://localhost:4592");
118 expect(yield* containerId(config.containerName)).toBe(id);
119 expect(elapsed).toBeLessThan(2_000);
120 }),
121 { timeout: 180_000 },
122 );
123
124 it.live(
125 "revives a stopped container",
126 () =>
127 Effect.gen(function* () {
128 const config = yield* isolated("revive", 4593);
129 yield* Floci.ensureFloci(config);
130 const id = yield* containerId(config.containerName);
131 yield* Floci.stopFloci(config.containerName);
132 expect(yield* isRunning(config.containerName)).toBe(false);
133
134 const instance = yield* Floci.ensureFloci(config);
135
136 expect(instance.managed).toBe(true);
137 expect(yield* containerId(config.containerName)).toBe(id);
138 yield* Floci.checkHealth(instance.endpoint);
139 }),
140 { timeout: 180_000 },
141 );
142
143 // #2214: a failed port setup left the container RUNNING with nothing
144 // published. `docker start` on it is a no-op success, so the manager
145 // reused it and polled an unreachable endpoint for the whole readiness
146 // timeout (300s × 4 attempts by default).
147 it.live(
148 "replaces a running container whose gateway is not published",
149 () =>
150 Effect.gen(function* () {
151 const config = yield* isolated("unbound", 4594);
152 const image = yield* Floci.resolveImage(config);
153 yield* docker(["run", "-d", "--name", config.containerName, image]);
154 const staleId = yield* containerId(config.containerName);
155
156 const { value: instance, elapsed } = yield* timed(Floci.ensureFloci(config));
157
158 expect(instance.managed).toBe(true);
159 expect(yield* containerId(config.containerName)).not.toBe(staleId);
160 expect(yield* docker(["port", config.containerName, "4566/tcp"])).toContain(":4594");
161 // Far below the 90s readiness timeout the old code waited out.
162 expect(elapsed).toBeLessThan(60_000);
163 }),
164 { timeout: 180_000 },
165 );
166
167 // #2214: a port Docker refuses to publish (rootless Docker and 80/443, a
168 // port held elsewhere) must be dropped, not leave an unreachable
169 // container behind — and the dropped port must not make every later
170 // ensure recreate (and wipe) the container.
171 it.live(
172 "starts without a port Docker cannot publish, and keeps the container",
173 () =>
174 Effect.gen(function* () {
175 yield* holdPort("floci-lifecycle-holder", 9595);
176 const config = yield* isolated("conflict", 4595, { elbListenerPorts: [9595] });
177
178 const { value: instance, elapsed } = yield* timed(Floci.ensureFloci(config));
179
180 expect(instance.managed).toBe(true);
181 const ports = yield* docker(["port", config.containerName]);
182 expect(ports).toContain(":4595");
183 expect(ports).not.toContain("9595");
184 // A fast fallback, not a readiness timeout (90s here).
185 expect(elapsed).toBeLessThan(60_000);
186 yield* Floci.checkHealth(instance.endpoint);
187
188 const id = yield* containerId(config.containerName);
189 yield* Floci.ensureFloci(config);
190 expect(yield* containerId(config.containerName)).toBe(id);
191 }),
192 { timeout: 180_000 },
193 );
194
195 it.live(
196 "recreates the container when the requested ports change",
197 () =>
198 Effect.gen(function* () {
199 const config = yield* isolated("ports", 4598);
200 yield* Floci.ensureFloci(config);
201 const id = yield* containerId(config.containerName);
202
203 yield* Floci.ensureFloci({ ...config, elbListenerPorts: [9598] });
204
205 expect(yield* containerId(config.containerName)).not.toBe(id);
206 expect(yield* docker(["port", config.containerName])).toContain(":9598");
207 }),
208 { timeout: 180_000 },
209 );
210
211 it.live.skipIf(!!process.env.ALCHEMY_FLOCI_IMAGE)(
212 "recreates the container when the image changes",
213 () =>
214 Effect.gen(function* () {
215 const alias = "alchemy-floci-lifecycle:drift";
216 const config = yield* isolated("drift", 4596);
217 yield* Floci.ensureFloci(config);
218 const id = yield* containerId(config.containerName);
219 // A local tag of the same image: a different reference without a pull.
220 yield* docker(["tag", Floci.DEFAULT_FLOCI_IMAGE, alias]);
221 yield* Effect.addFinalizer(() => docker(["rmi", alias]).pipe(Effect.ignore));
222
223 yield* Floci.ensureFloci({ ...config, image: alias });
224
225 expect(yield* containerId(config.containerName)).not.toBe(id);
226 expect(
227 yield* docker(["inspect", "--format", "{{.Config.Image}}", config.containerName]),
228 ).toBe(alias);
229 }),
230 { timeout: 180_000 },
231 );
232
233 it.live(
234 "converges concurrent ensures onto one container",
235 () =>
236 Effect.gen(function* () {
237 const config = yield* isolated("concurrent", 4597);
238
239 const [a, b] = yield* Effect.all([Floci.ensureFloci(config), Floci.ensureFloci(config)], {
240 concurrency: 2,
241 });
242
243 expect(a.endpoint).toBe(b.endpoint);
244 const ids = yield* docker([
245 "ps",
246 "-a",
247 "--filter",
248 `name=^${config.containerName}$`,
249 "--format",
250 "{{.ID}}",
251 ]);
252 expect(ids.split("\n").filter(Boolean)).toHaveLength(1);
253 yield* Floci.checkHealth(a.endpoint);
254 }),
255 { timeout: 180_000 },
256 );
257 });