Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - the host client drives a Node child process from its IPC callbacks, outside the Effect runtime.
2// Linux forks copy the parent's page tables. Spawn from a small host so a large
3// server heap cannot block the event loop; other platforms spawn directly.
4import * as NodeChildProcess from "node:child_process";
5import * as NodeEvents from "node:events";
6import type * as NodeNet from "node:net";
7import type * as NodeStream from "node:stream";
8
9import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
14
15import type { SpawnHostError, SpawnHostEvent, SpawnHostSpawnRequest } from "./spawnHostProcess.ts";
16
17const MAX_HOST_FAILURES = 3;
18const HOST_READY_TIMEOUT_MS = 10_000;
19const HOSTED_OPTION_KEYS: ReadonlySet<string> = new Set([
20 "cwd",
21 "env",
22 "stdio",
23 "detached",
24 "shell",
25 "windowsHide",
26]);
27const HOSTED_STDIO: ReadonlySet<unknown> = new Set([undefined, null, "pipe", "ignore", "inherit"]);
28
29const canHost = (options: NodeChildProcess.SpawnOptions) =>
30 Object.keys(options).every((key) => HOSTED_OPTION_KEYS.has(key)) &&
31 Array.isArray(options.stdio) &&
32 options.stdio.every((stdio) => HOSTED_STDIO.has(stdio));
33
34const toSpawnError = (error: SpawnHostError) =>
35 Object.assign(new Error(error.message), {
36 code: error.code,
37 errno: error.errno,
38 syscall: error.syscall,
39 path: error.path,
40 spawnargs: error.spawnargs,
41 });
42
43const killGroupOrProcess = (pid: number, signal: NodeJS.Signals) => {
44 try {
45 process.kill(-pid, signal);
46 } catch {
47 try {
48 process.kill(pid, signal);
49 } catch {
50 // Already gone.
51 }
52 }
53};
54
55export interface SpawnHostFailure {
56 readonly failures: number;
57 readonly disabled: boolean;
58 readonly cause: unknown;
59}
60
61/** A child started by the host, shaped like the `ChildProcess` the Effect spawner reads. */
62class HostedChildProcess
63 extends NodeEvents.EventEmitter
64 implements NodeChildProcessSpawner.SpawnedChildProcess
65{
66 pid: number | undefined = undefined;
67 stdin: NodeStream.Writable | null = null;
68 stdout: NodeStream.Readable | null = null;
69 stderr: NodeStream.Readable | null = null;
70 stdio: Array<NodeStream.Readable | NodeStream.Writable | null | undefined> = [];
71 state: "queued" | "sent" | "running" | "exited" = "queued";
72 referenced = true;
73 readonly request: SpawnHostSpawnRequest;
74 readonly #client: SpawnHostClient;
75 #pendingSignal: NodeJS.Signals | number | undefined;
76 #direct: NodeChildProcess.ChildProcess | undefined;
77
78 constructor(client: SpawnHostClient, request: SpawnHostSpawnRequest) {
79 super();
80 this.#client = client;
81 this.request = request;
82 }
83
84 kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean {
85 if (this.#direct) return this.#direct.kill(signal);
86 if (this.state === "exited") return false;
87 if (this.state === "queued") {
88 this.#client.settle(this);
89 return true;
90 }
91 if (this.pid === undefined) {
92 this.#pendingSignal = signal;
93 return true;
94 }
95 try {
96 process.kill(this.pid, signal);
97 return true;
98 } catch {
99 return false;
100 }
101 }
102
103 ref(): void {
104 if (this.#direct) this.#direct.ref();
105 else this.#client.setReferenced(this, true);
106 }
107
108 unref(): void {
109 if (this.#direct) this.#direct.unref();
110 else this.#client.setReferenced(this, false);
111 }
112
113 attachStdio(fd: number, socket: NodeNet.Socket): void {
114 this.stdio[fd] = socket;
115 if (fd === 0) {
116 // Transferred stdin can reset after the sink removes its error listener.
117 socket.on("error", () => {});
118 this.stdin = socket;
119 } else if (fd === 1) this.stdout = socket;
120 else if (fd === 2) this.stderr = socket;
121 }
122
123 markSpawned(pid: number): void {
124 this.state = "running";
125 this.pid = pid;
126 if (this.#pendingSignal !== undefined) this.kill(this.#pendingSignal);
127 this.emit("spawn");
128 }
129
130 markExited(code: number | null, signal: NodeJS.Signals | null): void {
131 this.#client.settle(this);
132 // Node destroys a child's stdin when it exits.
133 this.stdin?.destroy();
134 this.emit("exit", code, signal);
135 // Match Node's flushStdio: drain unread output to EOF so its socket closes.
136 process.nextTick(() => {
137 for (const stream of this.stdio) {
138 if (
139 stream &&
140 "resume" in stream &&
141 stream.readable &&
142 stream.listenerCount("data") === 0 &&
143 stream.listenerCount("readable") === 0
144 ) {
145 stream.resume();
146 }
147 }
148 });
149 }
150
151 markFailed(error: Error): void {
152 this.#client.settle(this);
153 this.emit("error", error);
154 }
155
156 spawnDirectly(): void {
157 this.#client.settle(this);
158 const { command, args, options } = this.request;
159 const child = NodeChildProcess.spawn(command, [...args], options);
160 this.#direct = child;
161 this.stdin = child.stdin;
162 this.stdout = child.stdout;
163 this.stderr = child.stderr;
164 this.stdio = [...child.stdio];
165 if (!this.referenced) child.unref();
166 child.on("error", (error) => this.emit("error", error));
167 child.on("spawn", () => {
168 this.pid = child.pid;
169 this.emit("spawn");
170 });
171 child.on("exit", (code, signal) => this.emit("exit", code, signal));
172 }
173}
174
175class SpawnHostClient {
176 readonly #command: string;
177 readonly #args: ReadonlyArray<string>;
178 readonly #onHostFailure: (failure: SpawnHostFailure) => void;
179 readonly #children = new Map<number, HostedChildProcess>();
180 #host: NodeChildProcess.ChildProcess | undefined;
181 #ready = false;
182 #closed = false;
183 #failures = 0;
184 #nextId = 0;
185 #referencedChildren = 0;
186 #readyTimer: NodeJS.Timeout | undefined;
187
188 constructor(
189 command: string,
190 args: ReadonlyArray<string>,
191 onHostFailure: (failure: SpawnHostFailure) => void,
192 ) {
193 this.#command = command;
194 this.#args = args;
195 this.#onHostFailure = onHostFailure;
196 }
197
198 readonly spawn = (
199 command: string,
200 args: ReadonlyArray<string>,
201 options: NodeChildProcess.SpawnOptions,
202 ): NodeChildProcessSpawner.SpawnedChildProcess => {
203 if (this.#closed || this.#failures >= MAX_HOST_FAILURES || !canHost(options)) {
204 return NodeChildProcess.spawn(command, [...args], options);
205 }
206 const child = new HostedChildProcess(this, {
207 type: "spawn",
208 id: ++this.#nextId,
209 command,
210 args,
211 // The host's own cwd and env are a snapshot from its start; send this process's.
212 options: { ...options, cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env },
213 });
214 this.#children.set(child.request.id, child);
215 this.#referencedChildren++;
216 if (this.#ready) this.#send(child);
217 else this.#start();
218 this.#syncChannelRef();
219 return child;
220 };
221
222 settle(child: HostedChildProcess): void {
223 if (child.state === "exited") return;
224 child.state = "exited";
225 this.#children.delete(child.request.id);
226 if (child.referenced) this.#referencedChildren--;
227 this.#syncChannelRef();
228 }
229
230 setReferenced(child: HostedChildProcess, referenced: boolean): void {
231 if (child.referenced === referenced) return;
232 child.referenced = referenced;
233 if (child.state !== "exited") this.#referencedChildren += referenced ? 1 : -1;
234 this.#syncChannelRef();
235 }
236
237 close(): void {
238 this.#closed = true;
239 clearTimeout(this.#readyTimer);
240 const host = this.#host;
241 this.#host = undefined;
242 if (host?.connected) host.disconnect();
243 }
244
245 // Match a direct child's process handle: only referenced children keep the server alive.
246 #syncChannelRef(): void {
247 const channel = this.#host?.channel;
248 if (!channel) return;
249 if (this.#referencedChildren > 0) channel.ref();
250 else channel.unref();
251 }
252
253 #send(child: HostedChildProcess): void {
254 const host = this.#host;
255 // After IPC EOF, leave it queued for the next host instead of sending to a closed channel.
256 if (!host?.connected) return;
257 child.state = "sent";
258 host.send(child.request);
259 }
260
261 #start(): void {
262 if (this.#host) return;
263 const env = { ...process.env };
264 // The host runs only its own module; preloads and flags meant for the server stay out.
265 delete env.NODE_OPTIONS;
266 let host: NodeChildProcess.ChildProcess;
267 try {
268 host = NodeChildProcess.spawn(this.#command, [...this.#args], {
269 env,
270 stdio: ["inherit", "inherit", "inherit", "ipc"],
271 });
272 } catch (cause) {
273 this.#failures++;
274 this.#onHostLost(cause);
275 return;
276 }
277 this.#host = host;
278 host.unref();
279 this.#syncChannelRef();
280 this.#readyTimer = setTimeout(() => {
281 host.kill("SIGKILL");
282 this.#lose(host, new Error("The spawn host did not start in time."));
283 }, HOST_READY_TIMEOUT_MS);
284 this.#readyTimer.unref();
285 host.on("message", (event, socket) => {
286 if (host === this.#host) {
287 this.#onEvent(event as SpawnHostEvent, socket as NodeNet.Socket | undefined);
288 }
289 });
290 // Keep listening: later errors would otherwise crash the server.
291 host.on("error", (cause) => this.#lose(host, cause));
292 // `close` follows the last IPC message, so every exit the host reported is handled first.
293 host.once("close", (code, signal) =>
294 this.#lose(host, new Error(`The spawn host exited (code ${code}, signal ${signal}).`)),
295 );
296 }
297
298 #onEvent(event: SpawnHostEvent, socket: NodeNet.Socket | undefined): void {
299 if (event.type === "ready") {
300 clearTimeout(this.#readyTimer);
301 this.#ready = true;
302 for (const child of this.#children.values()) {
303 if (child.state === "queued") this.#send(child);
304 }
305 return;
306 }
307 const child = this.#children.get(event.id);
308 if (!child) {
309 socket?.destroy();
310 return;
311 }
312 switch (event.type) {
313 case "stdio":
314 if (socket) child.attachStdio(event.fd, socket);
315 return;
316 case "spawn":
317 child.markSpawned(event.pid);
318 return;
319 case "exit":
320 child.markExited(event.code, event.signal);
321 return;
322 case "error":
323 child.markFailed(toSpawnError(event.error));
324 return;
325 }
326 }
327
328 #lose(host: NodeChildProcess.ChildProcess, cause: unknown): void {
329 if (host !== this.#host) return;
330 clearTimeout(this.#readyTimer);
331 this.#host = undefined;
332 this.#ready = false;
333 if (host.connected) host.disconnect();
334 if (this.#closed) return;
335 this.#failures++;
336 this.#onHostLost(cause);
337 }
338
339 #onHostLost(cause: unknown): void {
340 const disabled = this.#failures >= MAX_HOST_FAILURES;
341 this.#onHostFailure({ failures: this.#failures, disabled, cause });
342 for (const child of this.#children.values()) {
343 if (child.state === "queued") {
344 if (disabled) child.spawnDirectly();
345 } else if (child.state === "sent") {
346 // It may have started; spawning again could run it twice.
347 child.markFailed(new Error("The spawn host exited before reporting the spawn."));
348 } else if (!child.referenced) {
349 // Detached editors outlive the host, as they would a scope release.
350 child.markExited(null, null);
351 } else if (child.pid !== undefined) {
352 // Its exit status left with the host. Stop the group it leads, as a scope release would.
353 killGroupOrProcess(child.pid, "SIGKILL");
354 child.markExited(null, "SIGKILL");
355 }
356 }
357 if (this.#children.size > 0 && !disabled) this.#start();
358 }
359}
360
361export const layerHost = (
362 command: string,
363 args: ReadonlyArray<string>,
364 onHostFailure: (failure: SpawnHostFailure) => void,
365) =>
366 Layer.unwrap(
367 Effect.acquireRelease(
368 Effect.sync(() => new SpawnHostClient(command, args, onHostFailure)),
369 (client) => Effect.sync(() => client.close()),
370 ).pipe(Effect.map((client) => NodeChildProcessSpawner.layerWithSpawn(client.spawn))),
371 );
372
373export const layer = Layer.unwrap(
374 Effect.gen(function* () {
375 if ((yield* HostProcess.Platform) !== "linux") return NodeChildProcessSpawner.layer;
376 const invocation = yield* resolveSelfInvocation();
377 const runFork = Effect.runForkWith(yield* Effect.context<never>());
378 return layerHost(
379 invocation.command,
380 selfInvocationArgs(invocation, ["__spawn-host"]),
381 ({ failures, disabled, cause }) =>
382 runFork(
383 Effect.logWarning(
384 disabled
385 ? "The spawn host failed; child processes now start from the server."
386 : "The spawn host stopped; it restarts for the next child process.",
387 { failures, cause },
388 ),
389 ),
390 );
391 }),
392);