Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeServerLedger.test.ts

243 lines9.8 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3​
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { describe, expect, it } from "@effect/vitest";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16​
17import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
18import * as OpenCodeServerLedger from "./OpenCodeServerLedger.ts";
19​
20const SERVE_ARGS = ["serve", "--hostname=127.0.0.1", "--port=4096"];
21​
22const groupExists = (pgid: number) => {
23 try {
24 process.kill(-pgid, 0);
25 return true;
26 } catch {
27 return false;
28 }
29};
30​
31// A group can empty between any check and the kill, so ESRCH means done.
32const killGroup = (pgid: number) =>
33 Effect.sync(() => {
34 try {
35 process.kill(-pgid, "SIGKILL");
36 } catch (cause) {
37 if ((cause as NodeJS.ErrnoException).code !== "ESRCH") throw cause;
38 }
39 });
40​
41const spawnGroup = (args: ReadonlyArray<string>, script = "sleep 600 & wait") =>
42 Effect.acquireRelease(
43 Effect.gen(function* () {
44 const child = NodeChildProcess.spawn("/bin/sh", ["-c", script, ...args], {
45 detached: true,
46 stdio: "ignore",
47 });
48 const exited = yield* Deferred.make<NodeJS.Signals | null>();
49 child.once("exit", (_code, signal) => Deferred.doneUnsafe(exited, Effect.succeed(signal)));
50 const pid = child.pid;
51 if (pid === undefined) return yield* Effect.die("spawn failed");
52 return { pid, exited: Deferred.await(exited) };
53 }),
54 ({ pid }) => killGroup(pid),
55 );
56​
57const recordFromDeadServer = (stateDir: string, server: { readonly pid: number }) =>
58 Effect.gen(function* () {
59 const previousServer = yield* spawnGroup([]);
60 const previousLedger = yield* OpenCodeServerLedger.make({
61 stateDir,
62 ownerPid: previousServer.pid,
63 });
64 yield* Effect.asVoid(previousLedger.track({ pid: server.pid, port: 4096, args: SERVE_ARGS }));
65 process.kill(-previousServer.pid, "SIGKILL");
66 yield* previousServer.exited;
67 });
68​
69const hostPlatform = HostProcess.Platform.defaultValue();
70// procps accepts the same `ps` flags as macOS, so Linux also covers the macOS path.
71const observedPlatforms: ReadonlyArray<NodeJS.Platform> =
72 hostPlatform === "linux" ? ["linux", "darwin"] : hostPlatform === "darwin" ? ["darwin"] : [];
73​
74describe.each(observedPlatforms)("OpenCodeServerLedger observing as %s", (platform) => {
75 const provideHost = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
76 effect.pipe(
77 Effect.provideService(HostProcess.Platform, platform),
78 Effect.provide(NodeServices.layer),
79 );
80​
81 it.live("stops an OpenCode server group left by a server that died", () =>
82 Effect.gen(function* () {
83 const fs = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
86 const orphan = yield* spawnGroup(SERVE_ARGS);
87 yield* recordFromDeadServer(stateDir, orphan);
88 expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toHaveLength(1);
89​
90 const restarted = yield* OpenCodeServerLedger.make({ stateDir });
91 yield* restarted.reapOrphans;
92​
93 expect(yield* orphan.exited).toBe("SIGTERM");
94 expect(groupExists(orphan.pid)).toBe(false);
95 expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]);
96 }).pipe(provideHost),
97 );
98​
99 it.live("records a group whose spawned wrapper already exited", () =>
100 Effect.gen(function* () {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
104 const gate = path.join(stateDir, "gate");
105 const ready = path.join(stateDir, "ready");
106 NodeChildProcess.execFileSync("mkfifo", [gate, ready]);
107 // The wrapper's child is recorded before it execs and stopped after.
108 const wrapper = yield* spawnGroup(
109 SERVE_ARGS,
110 `(read _ < '${gate}'; exec /bin/sh -c 'echo > "${ready}"; sleep 600 & wait' "$0" "$@") & exit 0`,
111 );
112 yield* wrapper.exited;
113 expect(groupExists(wrapper.pid)).toBe(true);
114​
115 yield* recordFromDeadServer(stateDir, wrapper);
116 expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toHaveLength(1);
117 yield* fs.writeFileString(gate, "\n");
118 yield* fs.readFileString(ready);
119​
120 const restarted = yield* OpenCodeServerLedger.make({ stateDir });
121 yield* restarted.reapOrphans;
122​
123 expect(groupExists(wrapper.pid)).toBe(false);
124 expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]);
125 }).pipe(provideHost),
126 );
127​
128 it.live("leaves a recycled pid alone when its start time does not match", () =>
129 Effect.gen(function* () {
130 const fs = yield* FileSystem.FileSystem;
131 const path = yield* Path.Path;
132 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
133 const unrelated = yield* spawnGroup(SERVE_ARGS);
134 yield* recordFromDeadServer(stateDir, unrelated);
135 const entryPath = path.join(stateDir, "opencode-servers", `${unrelated.pid}.json`);
136 const entry = yield* fs.readFileString(entryPath);
137 yield* fs.writeFileString(entryPath, entry.replace(/"startTime":"[^"]+"/, '"startTime":"1"'));
138​
139 const restarted = yield* OpenCodeServerLedger.make({ stateDir });
140 yield* restarted.reapOrphans;
141​
142 expect(groupExists(unrelated.pid)).toBe(true);
143 expect(yield* fs.exists(entryPath)).toBe(false);
144 }).pipe(provideHost),
145 );
146​
147 it.live("leaves a serve process on another port alone", () =>
148 Effect.gen(function* () {
149 const fs = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
152 const unrelated = yield* spawnGroup(SERVE_ARGS);
153 yield* recordFromDeadServer(stateDir, unrelated);
154 const entryPath = path.join(stateDir, "opencode-servers", `${unrelated.pid}.json`);
155 const entry = yield* fs.readFileString(entryPath);
156 yield* fs.writeFileString(entryPath, entry.replace("--port=4096", "--port=4097"));
157​
158 const restarted = yield* OpenCodeServerLedger.make({ stateDir });
159 yield* restarted.reapOrphans;
160​
161 expect(groupExists(unrelated.pid)).toBe(true);
162 expect(yield* fs.exists(entryPath)).toBe(false);
163 }).pipe(provideHost),
164 );
165​
166 it.live("leaves the servers of a running T3 server alone", () =>
167 Effect.gen(function* () {
168 const fs = yield* FileSystem.FileSystem;
169 const path = yield* Path.Path;
170 const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-ledger-" });
171 const running = yield* OpenCodeServerLedger.make({ stateDir });
172 const server = yield* spawnGroup(SERVE_ARGS);
173 const forget = yield* running.track({ pid: server.pid, port: 4096, args: SERVE_ARGS });
174​
175 const other = yield* OpenCodeServerLedger.make({ stateDir });
176 yield* other.reapOrphans;
177 expect(groupExists(server.pid)).toBe(true);
178​
179 yield* forget;
180 expect(yield* fs.readDirectory(path.join(stateDir, "opencode-servers"))).toEqual([]);
181 }).pipe(provideHost),
182 );
183});
184​
185describe.skipIf(observedPlatforms.length === 0)("OpenCode server startup", () => {
186 it.live("stops the group when interrupted while the server is being recorded", () =>
187 Effect.gen(function* () {
188 const fs = yield* FileSystem.FileSystem;
189 const path = yield* Path.Path;
190 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode-startup-" });
191 const binaryPath = path.join(tempDir, "opencode");
192 yield* fs.writeFileString(binaryPath, "#!/bin/sh\nsleep 600 &\nexit 0\n");
193 yield* fs.chmod(binaryPath, 0o755);
194​
195 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
196 const recording = yield* Deferred.make<number>();
197 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
198 const layerRuntime = OpenCodeRuntime.layer.pipe(
199 Layer.provide(
200 Layer.succeed(
201 ChildProcessSpawner.ChildProcessSpawner,
202 ChildProcessSpawner.make((command) =>
203 spawner
204 .spawn(command)
205 .pipe(Effect.tap((handle) => Deferred.succeed(spawned, handle))),
206 ),
207 ),
208 ),
209 Layer.provide(
210 Layer.succeed(
211 OpenCodeServerLedger.OpenCodeServerLedger,
212 OpenCodeServerLedger.OpenCodeServerLedger.of({
213 track: (server) =>
214 Effect.gen(function* () {
215 yield* (yield* Deferred.await(spawned)).exitCode.pipe(Effect.ignore);
216 yield* Deferred.succeed(recording, server.pid);
217 return yield* Effect.never;
218 }),
219 }),
220 ),
221 ),
222 );
223​
224 const serverScope = yield* Scope.make();
225 const starting = yield* OpenCodeRuntime.OpenCodeRuntime.pipe(
226 Effect.flatMap((runtime) =>
227 runtime.startOpenCodeServerProcess({ binaryPath, directory: tempDir, port: 4096 }),
228 ),
229 Effect.provideService(Scope.Scope, serverScope),
230 Effect.provide(layerRuntime),
231 Effect.forkChild,
232 );
233 const pgid = yield* Deferred.await(recording);
234 yield* Effect.addFinalizer(() => killGroup(pgid));
235 expect(groupExists(pgid)).toBe(true);
236​
237 yield* Fiber.interrupt(starting);
238 yield* Scope.close(serverScope, Exit.void);
239​
240 expect(groupExists(pgid)).toBe(false);
241 }).pipe(Effect.provide(NodeServices.layer)),
242 );
243});