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

OpenCodeServerLedger.test.ts

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