Open History to see the last commit
1import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
10
11import * as ServerConfig from "../config.ts";
12import { signalProcessGroup } from "../process/processGroup.ts";
13
14const ProcessIdentity = Schema.Struct({ pid: Schema.Int, startTime: Schema.String });
15type ProcessIdentity = typeof ProcessIdentity.Type;
16
17const OpenCodeServerEntry = Schema.Struct({
18 version: Schema.Literal(1),
19 /** The spawned group. Its id is the pid T3 spawned, which also names the entry file. */
20 pgid: Schema.Int,
21 /**
22 * A group member seen at spawn: the spawned process, or a process it left in
23 * the group if it had already exited. Its pid, start time, and command line
24 * must all still match before the group is signalled.
25 */
26 pid: Schema.Int,
27 /** Linux `/proc/<pid>/stat` start ticks, or macOS `ps` lstart (whole seconds). */
28 startTime: Schema.String,
29 command: Schema.String,
30 port: Schema.Int,
31 /** Entries copied along with a state directory are dropped, never acted on. */
32 stateDir: Schema.String,
33 /** The T3 server that spawned it. Entries of a live owner are never touched. */
34 owner: ProcessIdentity,
35});
36type OpenCodeServerEntry = typeof OpenCodeServerEntry.Type;
37const OpenCodeServerEntryJson = Schema.fromJsonString(OpenCodeServerEntry);
38const decodeEntry = Schema.decodeUnknownOption(OpenCodeServerEntryJson);
39const encodeEntry = Schema.encodeEffect(OpenCodeServerEntryJson);
40
41/**
42 * Local `opencode serve` processes run in their own process group so T3 can
43 * stop the whole group, which also means they outlive a T3 server that is
44 * SIGKILLed or crashes. Each spawn is recorded under the state directory and
45 * removed on a graceful stop; the next server start stops whatever a dead
46 * server left behind.
47 */
48export class OpenCodeServerLedger extends Context.Service<
49 OpenCodeServerLedger,
50 {
51 /** Records a spawned server group and returns the effect that forgets it after a graceful stop. */
52 readonly track: (server: {
53 readonly pid: number;
54 readonly port: number;
55 /** The argv after the binary, e.g. `["serve", "--hostname=127.0.0.1", "--port=4096"]`. */
56 readonly args: ReadonlyArray<string>;
57 }) => Effect.Effect<Effect.Effect<void>>;
58 }
59>()("t3/provider/OpenCodeServerLedger") {}
60
61const ENTRY_DIRECTORY = "opencode-servers";
62const ENTRY_FILE = /^\d+\.json$/;
63const STOP_POLL_INTERVAL = "50 millis";
64const STOP_POLL_ATTEMPTS = 40;
65
66interface ObservedProcess {
67 readonly pid: number;
68 readonly pgid: number;
69 readonly startTime: string;
70 readonly command: string;
71 readonly zombie: boolean;
72}
73
74// `ps -o lstart` prints e.g. `Sat Sep 6 20:51:57 2026`; C locale and UTC keep it stable.
75const DARWIN_PS_LINE =
76 /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s+(.*)$/;
77
78const parseDarwinPs = (output: string): ReadonlyArray<ObservedProcess> =>
79 output.split("\n").flatMap((line) => {
80 const match = DARWIN_PS_LINE.exec(line);
81 if (match === null) return [];
82 return [
83 {
84 pid: Number(match[1]),
85 pgid: Number(match[2]),
86 zombie: match[3]!.startsWith("Z"),
87 startTime: match[4]!,
88 command: match[5]!.trimEnd(),
89 },
90 ];
91 });
92
93const signalGroup = (pgid: number, signal: NodeJS.Signals) => {
94 try {
95 signalProcessGroup(pgid, signal);
96 } catch {
97 // The group may already be gone.
98 }
99};
100
101const groupExists = (pgid: number) => {
102 try {
103 signalProcessGroup(pgid, 0);
104 return true;
105 } catch (cause) {
106 return (cause as NodeJS.ErrnoException | undefined)?.code !== "ESRCH";
107 }
108};
109
110/**
111 * Builds a ledger for one state directory. `ownerPid` is the T3 server that
112 * owns the servers it tracks; it defaults to this process.
113 */
114export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {
115 readonly stateDir: string;
116 readonly ownerPid?: number;
117}) {
118 const fs = yield* FileSystem.FileSystem;
119 const path = yield* Path.Path;
120 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
121 const platform = yield* HostProcessPlatform;
122 const directory = path.join(input.stateDir, ENTRY_DIRECTORY);
123 // Windows servers are not detached and are never recorded.
124 const recordable = platform === "linux" || platform === "darwin";
125
126 /** Observes `pid`, or nothing when it is not in `group` (if given). */
127 const observeLinux = (pid: number, group?: number) =>
128 Effect.gen(function* () {
129 const stat = yield* fs.readFileString(`/proc/${pid}/stat`);
130 // After the parenthesized comm: state, ppid, pgrp, session, … starttime (index 19).
131 const fields = stat
132 .slice(stat.lastIndexOf(")") + 2)
133 .trim()
134 .split(/\s+/);
135 const pgid = Number(fields[2]);
136 const startTime = fields[19];
137 if (!Number.isSafeInteger(pgid) || startTime === undefined) return undefined;
138 if (group !== undefined && pgid !== group) return undefined;
139 const cmdline = yield* fs.readFileString(`/proc/${pid}/cmdline`);
140 return {
141 pid,
142 pgid,
143 startTime,
144 command: cmdline.replace(/\0$/, "").replaceAll("\0", " "),
145 zombie: fields[0] === "Z",
146 } satisfies ObservedProcess;
147 });
148
149 const psDarwin = (selection: ReadonlyArray<string>) =>
150 spawner
151 .string(
152 ChildProcess.make(
153 "/bin/ps",
154 ["-ww", "-o", "pid=,pgid=,stat=,lstart=,args=", ...selection],
155 {
156 env: { LC_ALL: "C", TZ: "UTC" },
157 extendEnv: true,
158 stdin: "ignore",
159 stderr: "ignore",
160 },
161 ),
162 )
163 .pipe(Effect.timeout("5 seconds"), Effect.map(parseDarwinPs));
164
165 const observe = (pid: number): Effect.Effect<ObservedProcess | undefined> => {
166 if (platform === "linux") return observeLinux(pid).pipe(Effect.orElseSucceed(() => undefined));
167 if (platform === "darwin") {
168 return psDarwin(["-p", String(pid)]).pipe(
169 Effect.map((found) => found.find((candidate) => candidate.pid === pid)),
170 Effect.orElseSucceed(() => undefined),
171 );
172 }
173 return Effect.succeed(undefined);
174 };
175
176 // Scans every process, so it is only used when the spawned process is gone.
177 const observeGroup = (pgid: number): Effect.Effect<ReadonlyArray<ObservedProcess>> => {
178 if (platform === "linux") {
179 return fs.readDirectory("/proc").pipe(
180 Effect.flatMap((names) =>
181 Effect.forEach(
182 names.filter((name) => /^\d+$/.test(name)),
183 (name) => observeLinux(Number(name), pgid).pipe(Effect.orElseSucceed(() => undefined)),
184 { concurrency: 16 },
185 ),
186 ),
187 Effect.map((found) => found.filter((candidate) => candidate !== undefined)),
188 Effect.orElseSucceed(() => []),
189 );
190 }
191 if (platform === "darwin") {
192 return psDarwin(["-A"]).pipe(
193 Effect.map((found) => found.filter((candidate) => candidate.pgid === pgid)),
194 Effect.orElseSucceed(() => []),
195 );
196 }
197 return Effect.succeed([]);
198 };
199
200 const isRunning = (identity: ProcessIdentity) =>
201 observe(identity.pid).pipe(
202 Effect.map(
203 (observed) =>
204 observed !== undefined && !observed.zombie && observed.startTime === identity.startTime,
205 ),
206 );
207
208 const ownerPid = input.ownerPid ?? process.pid;
209 const ownerProcess = yield* observe(ownerPid);
210 const owner =
211 ownerProcess === undefined ? undefined : { pid: ownerPid, startTime: ownerProcess.startTime };
212
213 const track: OpenCodeServerLedger["Service"]["track"] = (server) =>
214 Effect.gen(function* () {
215 if (!recordable) return Effect.void;
216 const pgid = server.pid;
217 // The spawned process leads the group. If it already exited (a wrapper
218 // that left the server running), any live member identifies the group:
219 // a group id is not reused while the group has members.
220 const leader = yield* observe(pgid);
221 const members =
222 leader !== undefined && !leader.zombie && leader.pgid === pgid
223 ? [leader]
224 : (yield* observeGroup(pgid)).filter((candidate) => !candidate.zombie);
225 const member =
226 members.find((candidate) => candidate.command.endsWith(` ${server.args.join(" ")}`)) ??
227 members[0];
228 if (owner === undefined || member === undefined) {
229 if (groupExists(pgid)) {
230 yield* Effect.logWarning(
231 "Could not record an OpenCode server; it will keep running if this server crashes",
232 { pid: pgid, port: server.port },
233 );
234 }
235 return Effect.void;
236 }
237 const entryPath = path.join(directory, `${pgid}.json`);
238 const entry: OpenCodeServerEntry = {
239 version: 1,
240 pgid,
241 pid: member.pid,
242 startTime: member.startTime,
243 command: member.command,
244 port: server.port,
245 stateDir: input.stateDir,
246 owner,
247 };
248 yield* fs.makeDirectory(directory, { recursive: true });
249 yield* fs.writeFileString(entryPath, yield* encodeEntry(entry));
250 return fs
251 .remove(entryPath, { force: true })
252 .pipe(
253 Effect.catchCause((cause) =>
254 Effect.logWarning("Could not forget a stopped OpenCode server", { cause }),
255 ),
256 );
257 }).pipe(
258 Effect.catchCause((cause) =>
259 Effect.logWarning("Could not record an OpenCode server process", { cause }).pipe(
260 Effect.as(Effect.void),
261 ),
262 ),
263 );
264
265 // Signals only a group whose recorded member still has the same pid, start
266 // time, group, and full command line, so a recycled pid is never touched.
267 const stopOrphan = (entry: OpenCodeServerEntry) =>
268 Effect.gen(function* () {
269 const observed = yield* observe(entry.pid);
270 if (
271 observed === undefined ||
272 observed.zombie ||
273 observed.startTime !== entry.startTime ||
274 observed.pgid !== entry.pgid ||
275 observed.command !== entry.command
276 ) {
277 return;
278 }
279 yield* Effect.logInfo("Stopping an OpenCode server left by a previous T3 Code server", {
280 pid: entry.pgid,
281 port: entry.port,
282 });
283 signalGroup(entry.pgid, "SIGTERM");
284 for (let attempt = 0; attempt < STOP_POLL_ATTEMPTS && groupExists(entry.pgid); attempt++) {
285 yield* Effect.sleep(STOP_POLL_INTERVAL);
286 }
287 // The group never emptied, so its pgid cannot have been reused.
288 if (groupExists(entry.pgid)) signalGroup(entry.pgid, "SIGKILL");
289 });
290
291 const reapEntry = (entryPath: string) =>
292 Effect.gen(function* () {
293 const entry = decodeEntry(yield* fs.readFileString(entryPath));
294 if (Option.isSome(entry) && entry.value.stateDir === input.stateDir) {
295 if (yield* isRunning(entry.value.owner)) return;
296 yield* stopOrphan(entry.value);
297 }
298 yield* fs.remove(entryPath, { force: true });
299 }).pipe(
300 Effect.catchCause((cause) =>
301 Effect.logWarning("Could not clean up a recorded OpenCode server", { entryPath, cause }),
302 ),
303 );
304
305 /** Stops recorded servers whose owning T3 server is gone and drops stale entries. */
306 const reapOrphans = Effect.gen(function* () {
307 const names = yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
308 yield* Effect.forEach(
309 names.filter((name) => ENTRY_FILE.test(name)),
310 (name) => reapEntry(path.join(directory, name)),
311 { concurrency: "unbounded", discard: true },
312 );
313 });
314
315 return { track, reapOrphans };
316});
317
318export const layer = Layer.effect(
319 OpenCodeServerLedger,
320 Effect.gen(function* () {
321 const config = yield* ServerConfig.ServerConfig;
322 const ledger = yield* make({ stateDir: config.stateDir });
323 // Reaping waits for orphans to exit, so it must not hold up startup.
324 yield* ledger.reapOrphans.pipe(Effect.forkScoped);
325 return OpenCodeServerLedger.of({ track: ledger.track });
326 }),
327);
328
329/** Records nothing. For tests that start OpenCode servers without a state directory. */
330export const layerTest = Layer.succeed(
331 OpenCodeServerLedger,
332 OpenCodeServerLedger.of({ track: () => Effect.succeed(Effect.void) }),
333);