Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - IPC and timer callbacks implement the spawner boundary, as in the native spawner.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeEvents from "node:events";
4import type * as NodeNet from "node:net";
5import type * as NodeStream from "node:stream";
6import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner";
7import * as Context from "effect/Context";
8import * as Deferred from "effect/Deferred";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17
18import * as NonBlockingSpawner from "./NonBlockingSpawner.ts";
19import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorker.ts";
20
21// A launcher that misses either is treated as hung; neither happens to a healthy one.
22const READY_TIMEOUT = "10 seconds";
23const SPAWN_REPLY_TIMEOUT = "10 seconds";
24
25/** A child of the launcher, presented to the native spawner as a Node ChildProcess. */
26class HostedChild
27 extends NodeEvents.EventEmitter
28 implements NodeChildProcessSpawner.SpawnedChildProcess
29{
30 pid: number | undefined;
31 exitCode: number | null = null;
32 signalCode: NodeJS.Signals | null = null;
33 stdin: NodeStream.Writable | null = null;
34 stdout: NodeStream.Readable | null = null;
35 stderr: NodeStream.Readable | null = null;
36 readonly stdio: Array<NodeStream.Readable | NodeStream.Writable | null | undefined> = [];
37 referenced = true;
38 /** Its pipes are handed over and the native spawner owns it. */
39 started = false;
40 /** No longer awaited: its spawn failed, timed out or it exited. */
41 settled = false;
42 readonly launcher: Launcher;
43 /** The fds requested as pipes, each of which must arrive before the child counts as started. */
44 readonly pipes: ReadonlyArray<number>;
45
46 constructor(launcher: Launcher, stdio: NodeChildProcess.SpawnOptions["stdio"]) {
47 super();
48 this.launcher = launcher;
49 this.pipes = stdioModes(stdio).flatMap((mode, fd) => (isPipe(mode) ? [fd] : []));
50 }
51
52 kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean {
53 if (this.pid === undefined || this.exitCode !== null || this.signalCode !== null) return false;
54 try {
55 process.kill(this.pid, signal);
56 return true;
57 } catch {
58 return false;
59 }
60 }
61
62 ref(): void {
63 this.referenced = true;
64 syncRef(this.launcher);
65 }
66
67 unref(): void {
68 this.referenced = false;
69 syncRef(this.launcher);
70 }
71
72 fail(error: Error): void {
73 this.settled = true;
74 this.emit("error", error);
75 }
76
77 exit(code: number | null, signal: NodeJS.Signals | null): void {
78 this.settled = true;
79 this.exitCode = code;
80 this.signalCode = signal;
81 // Node destroys stdin at exit and drains output nobody reads, so pipes never hold a child.
82 this.stdin?.destroy();
83 this.emit("exit", code, signal);
84 process.nextTick(() => {
85 for (const stream of [this.stdout, this.stderr]) {
86 if (
87 stream &&
88 stream.listenerCount("data") === 0 &&
89 stream.listenerCount("readable") === 0
90 ) {
91 stream.resume();
92 }
93 }
94 });
95 }
96}
97
98const stdioModes = (stdio: NodeChildProcess.SpawnOptions["stdio"]) =>
99 typeof stdio === "string" || stdio === undefined ? Array<typeof stdio>(3).fill(stdio) : stdio;
100
101const isPipe = (mode: unknown) =>
102 mode === undefined || mode === null || mode === "pipe" || mode === "overlapped";
103
104// The launcher's own stdin and stdout are /dev/null, so only pipes and "ignore" mean the same there.
105const isHostable = (stdio: NodeChildProcess.SpawnOptions["stdio"]) =>
106 stdioModes(stdio).every((mode) => isPipe(mode) || mode === "ignore");
107
108interface Launcher {
109 readonly worker: NodeChildProcess.ChildProcess;
110 readonly children: Map<number, HostedChild>;
111 readonly ready: Deferred.Deferred<boolean>;
112 closed: boolean;
113 /** Counts messages from the launcher, so a slow server is not mistaken for a hung launcher. */
114 heard: number;
115}
116
117const syncRef = (launcher: Launcher) => {
118 if ([...launcher.children.values()].some((child) => child.referenced)) {
119 launcher.worker.channel?.ref();
120 } else {
121 launcher.worker.channel?.unref();
122 }
123};
124
125const killGroup = (pid: number) => {
126 try {
127 process.kill(-pid, "SIGKILL");
128 } catch {
129 // The group is already gone.
130 }
131};
132
133const launcherArguments = Effect.fn("ProcessLauncher.launcherArguments")(function* () {
134 // A single executable has no sibling script, so it hosts the launcher as a hidden subcommand.
135 if (yield* HostProcess.IsExecutable) return ["__process-launcher"];
136 const path = yield* Path.Path;
137 const fromSource = import.meta.url.endsWith(".ts");
138 return [
139 ...(fromSource ? ["--experimental-strip-types"] : []),
140 yield* path
141 .fromFileUrl(
142 new URL(fromSource ? "../process-launcher.ts" : "./process-launcher.mjs", import.meta.url),
143 )
144 .pipe(Effect.orDie),
145 ];
146});
147
148// On Linux, libuv forks the whole server for every spawn and blocks the event loop while the
149// kernel copies its page tables, so commands are launched by a small long-lived helper instead.
150// The helper passes each child's pipes back, so the native spawner keeps all of its semantics.
151export const make = Effect.fn("ProcessLauncher.make")(function* (
152 replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT,
153) {
154 const fallback = yield* ChildProcessSpawner.ChildProcessSpawner;
155 if ((yield* HostProcess.Platform) !== "linux") return fallback;
156
157 const executablePath = yield* HostProcess.ExecutablePath;
158 const args = yield* launcherArguments();
159 let current: Launcher | undefined;
160 // A launcher that never starts will not start next time either; stop forking for it.
161 let unavailable = false;
162 let warned = false;
163 let shutDown = false;
164 let nextId = 0;
165
166 const close = (launcher: Launcher, hung = false) => {
167 if (launcher.closed) return;
168 launcher.closed = true;
169 if (current === launcher) current = undefined;
170 const ready = Deferred.isDoneUnsafe(launcher.ready);
171 if (!ready) unavailable = true;
172 Deferred.doneUnsafe(launcher.ready, Exit.succeed(false));
173 const error = new Error(
174 hung ? "The process launcher did not respond." : "The process launcher exited.",
175 );
176 for (const child of launcher.children.values()) {
177 if (child.settled) continue;
178 if (child.pid !== undefined) killGroup(child.pid);
179 if (child.started) {
180 child.exit(null, "SIGKILL");
181 } else {
182 for (const stream of child.stdio) stream?.destroy();
183 child.fail(error);
184 }
185 }
186 launcher.children.clear();
187 if (launcher.worker.connected) launcher.worker.disconnect();
188 // A started launcher kills its children and exits once disconnected; a hung one never reads that.
189 if (hung || !ready) launcher.worker.kill("SIGKILL");
190 };
191
192 const onEvent = (
193 launcher: Launcher,
194 event: LauncherEvent,
195 socket: NodeNet.Socket | undefined,
196 ) => {
197 launcher.heard++;
198 if (event.type === "ready") {
199 Deferred.doneUnsafe(launcher.ready, Exit.succeed(true));
200 return;
201 }
202 const child = launcher.children.get(event.id);
203 if (child === undefined) {
204 socket?.destroy();
205 return;
206 }
207 switch (event.type) {
208 case "stdio":
209 if (child.settled) socket?.destroy();
210 else if (socket) {
211 child.stdio[event.fd] = socket;
212 if (event.fd === 0) {
213 // Unlike Node's own stdin pipe this socket also reads, and an unread write resets it.
214 socket.on("error", () => {});
215 child.stdin = socket;
216 } else if (event.fd === 1) child.stdout = socket;
217 else if (event.fd === 2) child.stderr = socket;
218 }
219 break;
220 case "pid":
221 child.pid = event.pid;
222 break;
223 case "spawn":
224 // A lost handle would otherwise read as a command that printed nothing.
225 if (child.pipes.some((fd) => child.stdio[fd] == null)) {
226 if (child.pid !== undefined) killGroup(child.pid);
227 for (const stream of child.stdio) stream?.destroy();
228 child.fail(new Error("The process launcher did not hand over the command's pipes."));
229 break;
230 }
231 child.started = true;
232 child.emit("spawn");
233 break;
234 case "exit":
235 launcher.children.delete(event.id);
236 syncRef(launcher);
237 if (!child.settled) child.exit(event.code, event.signal);
238 break;
239 case "error":
240 if (child.pid !== undefined || child.settled) break;
241 launcher.children.delete(event.id);
242 syncRef(launcher);
243 child.fail(Object.assign(new Error(event.error.message), event.error));
244 break;
245 }
246 };
247
248 const launch = (): Launcher | undefined => {
249 if (unavailable || shutDown) return undefined;
250 if (current !== undefined) return current;
251 const env: NodeJS.ProcessEnv = { ...process.env, ELECTRON_RUN_AS_NODE: "1" };
252 delete env.NODE_OPTIONS;
253 // `node --watch` children would report their imports over the launcher's IPC channel.
254 delete env.WATCH_REPORT_DEPENDENCIES;
255 let worker: NodeChildProcess.ChildProcess;
256 try {
257 worker = NodeChildProcess.spawn(executablePath, args, {
258 cwd: "/",
259 env,
260 stdio: ["ignore", "ignore", "inherit", "ipc"],
261 });
262 } catch {
263 // Node throws some errnos, such as ENOMEM, instead of emitting "error".
264 unavailable = true;
265 return undefined;
266 }
267 const launcher: Launcher = {
268 worker,
269 children: new Map(),
270 ready: Deferred.makeUnsafe(),
271 closed: false,
272 heard: 0,
273 };
274 worker.unref();
275 worker.channel?.unref();
276 worker.on("message", (event: LauncherEvent, socket: NodeNet.Socket | undefined) =>
277 onEvent(launcher, event, socket),
278 );
279 worker.on("error", () => close(launcher));
280 worker.once("disconnect", () => close(launcher));
281 worker.once("exit", () => close(launcher));
282 current = launcher;
283 return launcher;
284 };
285
286 const spawnProcess = (
287 command: string,
288 commandArgs: ReadonlyArray<string>,
289 options: NodeChildProcess.SpawnOptions,
290 ): NodeChildProcessSpawner.SpawnedChildProcess => {
291 const launcher = current;
292 // Lost or replaced between the readiness check and the spawn; rare enough to fork for.
293 if (
294 launcher === undefined ||
295 launcher.closed ||
296 !Deferred.isDoneUnsafe(launcher.ready) ||
297 !isHostable(options.stdio)
298 ) {
299 return NodeChildProcess.spawn(command, [...commandArgs], options);
300 }
301 const id = ++nextId;
302 const child = new HostedChild(launcher, options.stdio);
303 launcher.children.set(id, child);
304 syncRef(launcher);
305 const request: LauncherSpawnRequest = {
306 type: "spawn",
307 id,
308 command,
309 args: commandArgs,
310 // The launcher runs in `/` with its own environment; children inherit the server's.
311 options: { ...options, cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env },
312 };
313 launcher.worker.send(request, (error) => {
314 if (error) close(launcher);
315 });
316 // The native spawner waits for the reply uninterruptibly, so a hung launcher must not hold it.
317 // Hung means silent for a whole window; replies queued behind a busy server count once read.
318 const watch = (heard: number) =>
319 setTimeout(
320 () =>
321 setImmediate(() => {
322 if (child.started || child.settled) return;
323 if (launcher.heard === heard) close(launcher, true);
324 else watch(launcher.heard);
325 }),
326 Duration.toMillis(replyTimeout),
327 ).unref();
328 watch(launcher.heard);
329 return child;
330 };
331
332 // The trampoline keeps a hung cwd or PATH entry from stalling the launcher, and with it every command.
333 // Fresh: the server has already built this layer around the forking spawner.
334 const hosted = Context.get(
335 yield* Layer.build(
336 Layer.fresh(NonBlockingSpawner.layer).pipe(
337 Layer.provide(NodeChildProcessSpawner.layerWithSpawn(spawnProcess)),
338 ),
339 ),
340 ChildProcessSpawner.ChildProcessSpawner,
341 );
342
343 const warnUnavailable = Effect.suspend(() => {
344 if (!unavailable || warned || shutDown) return Effect.void;
345 warned = true;
346 return Effect.logWarning("The process launcher did not start; commands fork the server.");
347 });
348
349 const isReady = Effect.suspend(() => {
350 const launcher = launch();
351 if (launcher === undefined) return Effect.as(warnUnavailable, false);
352 return Deferred.await(launcher.ready).pipe(
353 Effect.timeoutOption(READY_TIMEOUT),
354 Effect.map(Option.getOrElse(() => false)),
355 Effect.tap((ready) => {
356 if (ready) return Effect.void;
357 close(launcher);
358 return warnUnavailable;
359 }),
360 );
361 });
362
363 yield* Effect.addFinalizer(() =>
364 Effect.sync(() => {
365 shutDown = true;
366 if (current) close(current);
367 }),
368 );
369 // Start while the server is still small; the launcher's own fork is the last full-size one.
370 launch();
371 return ChildProcessSpawner.make((command) =>
372 Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)),
373 );
374});
375
376/** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */
377export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make());
378
379/** The server's one spawner: memoized, so every build site shares a single launcher. */
380export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer));