Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- the SDK's synchronous spawn callback must record ownership before releasing the child.
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13
14import * as ServerConfig from "../config.ts";
15import * as ProcessLauncher from "./ProcessLauncher.ts";
16
17const ProcessIdentity = Schema.Struct({
18 pid: Schema.Int.check(Schema.isBetween({ minimum: 2, maximum: Number.MAX_SAFE_INTEGER })),
19 startTime: Schema.String,
20});
21const OwnershipRecord = Schema.Struct({
22 version: Schema.Literal(1),
23 instanceId: Schema.String,
24 hostname: Schema.String,
25 stateDir: Schema.String,
26 owner: ProcessIdentity,
27 processes: Schema.Array(Schema.Struct({ ...ProcessIdentity.fields, pgid: Schema.Int })),
28});
29const decodeRecord = Schema.decodeUnknownSync(Schema.fromJsonString(OwnershipRecord));
30
31// A concurrent exit can remove the record. Incomplete/unknown records never authorize a signal.
32const readRecord = (recordPath: string) => {
33 try {
34 return decodeRecord(NodeFS.readFileSync(recordPath, "utf8"));
35 } catch {
36 return undefined;
37 }
38};
39
40export const ProviderProcesses = Context.Reference<{
41 readonly register?: (pid: number) => () => void;
42 readonly hasOtherLiveOwner: boolean;
43}>("t3/process/ProviderProcesses", { defaultValue: () => ({ hasOtherLiveOwner: false }) });
44
45const make = Effect.gen(function* () {
46 const platform = yield* HostProcess.Platform;
47 if (platform !== "linux") return { hasOtherLiveOwner: false };
48 const { stateDir } = yield* ServerConfig.ServerConfig;
49 const processLauncher = yield* ProcessLauncher.ProcessLauncher;
50 const runSync = Effect.runSyncWith(yield* Effect.context<never>());
51 const directory = NodePath.join(stateDir, "provider-processes");
52 const hostname = NodeOS.hostname();
53 const boot = NodeFS.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
54 const controller = AcpSessionRuntime.makePosixProcessTreeController(platform);
55 const identity = (pid: number) => {
56 const observed = controller.identity(pid);
57 if (observed === undefined || AcpSessionRuntime.posixProcessIsZombie(observed))
58 return undefined;
59 return { ...observed, startTime: `${boot}:${observed.startTime}` };
60 };
61 const matches = (expected: typeof ProcessIdentity.Type) =>
62 identity(expected.pid)?.startTime === expected.startTime;
63 const kill = (survivor: typeof ProcessIdentity.Type) => {
64 try {
65 controller.signalProcess(survivor.pid, "SIGKILL");
66 } catch {}
67 };
68 const owner = identity(process.pid);
69 if (owner === undefined) return yield* Effect.die(new Error("Cannot identify provider owner"));
70 NodeFS.mkdirSync(directory, { recursive: true });
71
72 const writeRecord = (processes: (typeof OwnershipRecord.Type)["processes"]) => {
73 const instanceId = NodeCrypto.randomUUID();
74 const recordPath = NodePath.join(directory, `${instanceId}.json`);
75 const pendingPath = `${recordPath}.pending`;
76 NodeFS.writeFileSync(
77 pendingPath,
78 JSON.stringify({
79 version: 1,
80 instanceId,
81 hostname,
82 stateDir,
83 owner: { pid: owner.pid, startTime: owner.startTime },
84 processes,
85 } satisfies typeof OwnershipRecord.Type),
86 );
87 NodeFS.renameSync(pendingPath, recordPath);
88 return () => NodeFS.rmSync(recordPath, { force: true });
89 };
90 // Publish the server identity even before its first provider. Another server
91 // using this home must not stop the shared systemd slice while we are alive.
92 const forgetOwner = writeRecord([]);
93 yield* Effect.addFinalizer(() => Effect.sync(forgetOwner));
94 let hasOtherLiveOwner = false;
95
96 // Only immutable per-launch records are shared between server instances. A
97 // live owner's records belong to that server, even when it uses this home.
98 for (const file of NodeFS.readdirSync(directory)) {
99 if (!file.endsWith(".json")) continue;
100 const recordPath = NodePath.join(directory, file);
101 const record = readRecord(recordPath);
102 if (record === undefined) continue;
103 if (record.hostname !== hostname || record.stateDir !== stateDir) continue;
104 if (matches(record.owner)) {
105 if (record.owner.pid !== process.pid) hasOtherLiveOwner = true;
106 continue;
107 }
108 let survived = false;
109 for (const survivor of record.processes) {
110 if (survivor.pid === process.pid || !matches(survivor)) continue;
111 // Never infer ownership from argv, executable names, or group membership.
112 // As in the ACP controller, starttime blocks reuse between observations.
113 // Node has no pidfd_send_signal, so the final read-to-signal race remains.
114 kill(survivor);
115 for (let attempt = 0; matches(survivor) && !survived; attempt++) {
116 survived = attempt === 100;
117 if (!survived) yield* Effect.sleep("10 millis");
118 }
119 }
120 // Like a failed slice stop, an unkillable CLI must not keep the server down;
121 // its record stays so the next start retries.
122 if (survived) {
123 yield* Effect.logWarning("Could not stop a provider left by a previous server", { file });
124 continue;
125 }
126 NodeFS.rmSync(recordPath, { force: true });
127 }
128
129 // The launcher's own parent is checked so a reused PID of a dead launcher is not trusted.
130 const isOwnedParent = (ppid: number) =>
131 ppid === process.pid ||
132 (ppid === runSync(processLauncher.currentPid) && identity(ppid)?.ppid === process.pid);
133
134 return {
135 hasOtherLiveOwner,
136 register: (pid: number) => {
137 const provider = identity(pid);
138 if (provider === undefined || !isOwnedParent(provider.ppid)) {
139 throw new Error("Cannot identify spawned provider");
140 }
141 // A rename keeps startup from seeing a partial write. The child is gated
142 // until this returns, so an abrupt death cannot leave an unrecorded CLI.
143 return writeRecord([{ pid, startTime: provider.startTime, pgid: provider.pgid }]);
144 },
145 };
146});
147
148export const layer = Layer.effect(ProviderProcesses, make);