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

ProcessLauncher.ts

397 lines14.2 KB

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