Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - worker threads and Node streams implement the platform spawner boundary.
2import * as NodeEvents from "node:events";
3import type * as NodeChildProcess from "node:child_process";
4import * as NodeStream from "node:stream";
5import * as NodeWorkerThreads from "node:worker_threads";
6import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import { supportsEnvChdir } from "@t3tools/shared/envTrampoline";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11
12// Windows runs CreateProcess synchronously on the calling thread, and antivirus or a busy disk can
13// hold it for seconds; Linux's spawn waits for chdir and the PATH search, which a hung mount
14// stalls. Workers own the children, so only the worker waits.
15const MAX_WORKERS = 4;
16const MAX_IDLE_WORKERS = 1;
17
18type ToWorker =
19 | {
20 readonly type: "spawn";
21 readonly id: number;
22 readonly command: string;
23 readonly args: ReadonlyArray<string>;
24 readonly options: NodeChildProcess.SpawnOptions;
25 }
26 | { readonly type: "write"; readonly id: number; readonly fd: number; readonly data: Uint8Array }
27 | { readonly type: "end"; readonly id: number; readonly fd: number }
28 | { readonly type: "flow"; readonly id: number; readonly fd: number; readonly paused: boolean }
29 | { readonly type: "destroy"; readonly id: number; readonly fd: number }
30 | { readonly type: "kill"; readonly id: number; readonly signal: NodeJS.Signals | number };
31
32interface SerializedError {
33 readonly message: string;
34 readonly [key: string]: unknown;
35}
36
37type FromWorker =
38 | { readonly type: "spawn"; readonly id: number; readonly pid: number | undefined }
39 | { readonly type: "error"; readonly id: number; readonly error: SerializedError }
40 | { readonly type: "data"; readonly id: number; readonly fd: number; readonly data: Uint8Array }
41 | {
42 readonly type: "written";
43 readonly id: number;
44 readonly fd: number;
45 readonly error?: SerializedError;
46 }
47 | { readonly type: "eof"; readonly id: number; readonly fd: number }
48 | { readonly type: "finished"; readonly id: number; readonly fd: number }
49 | {
50 readonly type: "stream-error";
51 readonly id: number;
52 readonly fd: number;
53 readonly error: SerializedError;
54 }
55 | {
56 readonly type: "exit";
57 readonly id: number;
58 readonly code: number | null;
59 readonly signal: NodeJS.Signals | null;
60 }
61 | { readonly type: "close"; readonly id: number };
62
63// Inline source runs from bundles, asar archives and single-executable builds without module files.
64const workerSource = `
65const { parentPort } = require("node:worker_threads");
66const { spawn } = require("node:child_process");
67const children = new Map();
68const post = (message, transfer) => parentPort.postMessage(message, transfer);
69const serialize = (error) => {
70 const out = { message: String(error && error.message) };
71 for (const key of ["code", "errno", "syscall", "path", "spawnargs"]) {
72 if (error && error[key] !== undefined) out[key] = error[key];
73 }
74 return out;
75};
76parentPort.on("message", (request) => {
77 const { id } = request;
78 if (request.type === "spawn") {
79 let child;
80 try {
81 child = spawn(request.command, request.args, request.options);
82 } catch (error) {
83 post({ type: "error", id, error: serialize(error) });
84 return;
85 }
86 children.set(id, child);
87 child.on("spawn", () => post({ type: "spawn", id, pid: child.pid }));
88 child.on("error", (error) => post({ type: "error", id, error: serialize(error) }));
89 child.on("exit", (code, signal) => post({ type: "exit", id, code, signal }));
90 // Output can still arrive after exit; close follows the last of it.
91 child.on("close", () => {
92 children.delete(id);
93 post({ type: "close", id });
94 });
95 child.stdio?.forEach((stream, fd) => {
96 if (!stream) return;
97 stream.on("error", (error) => post({ type: "stream-error", id, fd, error: serialize(error) }));
98 if (fd === 0) return;
99 // Cloning a Buffer copies its whole backing store; copy the bytes once and transfer them.
100 stream.on("data", (chunk) => {
101 const data = new Uint8Array(chunk);
102 post({ type: "data", id, fd, data }, [data.buffer]);
103 });
104 stream.on("end", () => post({ type: "eof", id, fd }));
105 });
106 return;
107 }
108 const child = children.get(id);
109 if (child === undefined) {
110 if (request.type === "write") post({ type: "written", id, fd: request.fd, error: { message: "write after exit", code: "EPIPE" } });
111 if (request.type === "end") post({ type: "finished", id, fd: request.fd });
112 return;
113 }
114 const stream = child.stdio?.[request.fd];
115 switch (request.type) {
116 case "write":
117 if (!stream || stream.destroyed) {
118 post({ type: "written", id, fd: request.fd, error: { message: "write after end", code: "EPIPE" } });
119 return;
120 }
121 try {
122 stream.write(request.data, (error) => post({ type: "written", id, fd: request.fd, error: error ? serialize(error) : undefined }));
123 } catch (error) {
124 post({ type: "written", id, fd: request.fd, error: serialize(error) });
125 }
126 return;
127 case "end":
128 if (!stream || stream.destroyed || stream.writableFinished) post({ type: "finished", id, fd: request.fd });
129 else stream.end(() => post({ type: "finished", id, fd: request.fd }));
130 return;
131 case "flow":
132 if (request.paused) stream?.pause();
133 else stream?.resume();
134 return;
135 case "destroy":
136 stream?.destroy();
137 return;
138 case "kill":
139 try {
140 child.kill(request.signal);
141 } catch {}
142 return;
143 }
144});
145`;
146
147const toError = (serialized: SerializedError) =>
148 Object.assign(new Error(serialized.message), serialized);
149
150const toBuffer = (data: Uint8Array) => Buffer.from(data.buffer, data.byteOffset, data.byteLength);
151
152class WorkerChild
153 extends NodeEvents.EventEmitter
154 implements NodeChildProcessSpawner.SpawnedChildProcess
155{
156 pid: number | undefined;
157 exitCode: number | null = null;
158 signalCode: NodeJS.Signals | null = null;
159 stdin: NodeStream.Writable | null = null;
160 stdout: NodeStream.Readable | null = null;
161 stderr: NodeStream.Readable | null = null;
162 readonly stdio: Array<NodeStream.Readable | NodeStream.Writable | null | undefined> = [];
163 referenced = true;
164 killed = false;
165 spawned = false;
166 exited = false;
167 readonly #writes = new Map<number, Array<(error?: Error | null) => void>>();
168 readonly #finals = new Map<number, (error?: Error | null) => void>();
169 readonly #paused = new Set<number>();
170
171 readonly worker: SpawnWorker;
172 readonly id: number;
173
174 constructor(worker: SpawnWorker, id: number, stdio: ReadonlyArray<unknown>) {
175 super();
176 this.worker = worker;
177 this.id = id;
178 stdio.forEach((option, fd) => {
179 if (option !== "pipe" && option !== "overlapped") return;
180 const stream = this.#relay(fd);
181 this.stdio[fd] = stream;
182 if (fd === 0) this.stdin = stream as NodeStream.Writable;
183 else if (fd === 1) this.stdout = stream as NodeStream.Readable;
184 else if (fd === 2) this.stderr = stream as NodeStream.Readable;
185 });
186 }
187
188 #relay(fd: number): NodeStream.Readable | NodeStream.Writable {
189 const read = () => {
190 if (this.#paused.delete(fd))
191 this.worker.post({ type: "flow", id: this.id, fd, paused: false });
192 };
193 const write = (
194 chunk: Buffer,
195 _encoding: BufferEncoding,
196 callback: (error?: Error | null) => void,
197 ) => {
198 if (this.worker.closed) {
199 callback(Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
200 return;
201 }
202 const pending = this.#writes.get(fd) ?? [];
203 pending.push(callback);
204 this.#writes.set(fd, pending);
205 const data = new Uint8Array(chunk);
206 this.worker.post({ type: "write", id: this.id, fd, data }, [data.buffer]);
207 };
208 const final = (callback: (error?: Error | null) => void) => {
209 this.#finals.set(fd, callback);
210 this.worker.post({ type: "end", id: this.id, fd });
211 };
212 // A caller that destroys its end closes the child pipe, as it would with a real pipe.
213 const destroy = (error: Error | null, callback: (error?: Error | null) => void) => {
214 if (!this.exited) this.worker.post({ type: "destroy", id: this.id, fd });
215 callback(error);
216 };
217 if (fd === 0) return new NodeStream.Writable({ write, final, destroy });
218 if (fd <= 2) return new NodeStream.Readable({ read, destroy });
219 return new NodeStream.Duplex({ read, write, final, destroy, allowHalfOpen: true });
220 }
221
222 onData(fd: number, data: Uint8Array): void {
223 const stream = this.stdio[fd];
224 if (!stream || !("push" in stream)) return;
225 if (!stream.push(toBuffer(data)) && !this.#paused.has(fd)) {
226 this.#paused.add(fd);
227 this.worker.post({ type: "flow", id: this.id, fd, paused: true });
228 }
229 }
230
231 onEof(fd: number): void {
232 const stream = this.stdio[fd];
233 if (stream && "push" in stream) stream.push(null);
234 }
235
236 onFinished(fd: number): void {
237 const callback = this.#finals.get(fd);
238 this.#finals.delete(fd);
239 callback?.();
240 }
241
242 onWritten(fd: number, error: SerializedError | undefined): void {
243 const callback = this.#writes.get(fd)?.shift();
244 callback?.(error === undefined ? null : toError(error));
245 }
246
247 onStreamError(fd: number, error: SerializedError): void {
248 this.stdio[fd]?.destroy(toError(error));
249 }
250
251 kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean {
252 if (this.exited) return false;
253 this.killed = true;
254 this.worker.post({ type: "kill", id: this.id, signal });
255 return true;
256 }
257
258 ref(): void {
259 this.referenced = true;
260 this.worker.syncRef();
261 }
262
263 unref(): void {
264 this.referenced = false;
265 this.worker.syncRef();
266 }
267
268 exit(code: number | null, signal: NodeJS.Signals | null): void {
269 if (this.exited) return;
270 this.exited = true;
271 this.exitCode = code;
272 this.signalCode = signal;
273 // Node destroys stdin on exit; the Effect sink may already have removed its error listener.
274 this.stdin?.on("error", () => {});
275 this.stdin?.destroy();
276 this.emit("exit", code, signal);
277 }
278
279 /** The worker is gone: end output so readers finish, and let the exit report the kill. */
280 abandon(): void {
281 // Not destroy(error): Effect leaves an unread stderr's pipe without an error listener.
282 for (const stream of this.stdio) {
283 if (stream && "push" in stream && !stream.readableEnded) stream.push(null);
284 else if (stream && !("push" in stream)) stream.destroy();
285 }
286 }
287}
288
289class SpawnWorker {
290 readonly worker: NodeWorkerThreads.Worker;
291 readonly children = new Map<number, WorkerChild>();
292 readonly pool: SpawnWorkerPool;
293 /** Launches sent but not yet answered; the worker is inside CreateProcess for one of them. */
294 launching = 0;
295 closed = false;
296
297 constructor(pool: SpawnWorkerPool) {
298 this.pool = pool;
299 this.worker = new NodeWorkerThreads.Worker(workerSource, { eval: true });
300 this.worker.on("message", (message: FromWorker) => this.onMessage(message));
301 this.worker.on("error", (error) => this.fail(error));
302 this.worker.on("exit", () => this.fail(new Error("The process launcher thread exited.")));
303 this.worker.unref();
304 }
305
306 post(message: ToWorker, transfer?: ReadonlyArray<ArrayBuffer>): void {
307 if (!this.closed) this.worker.postMessage(message, transfer);
308 }
309
310 spawn(
311 id: number,
312 command: string,
313 args: ReadonlyArray<string>,
314 options: NodeChildProcess.SpawnOptions,
315 ): WorkerChild {
316 const io = options.stdio;
317 const stdio =
318 typeof io === "string" || io === undefined ? [io ?? "pipe", io ?? "pipe", io ?? "pipe"] : io;
319 const child = new WorkerChild(this, id, stdio);
320 // An AbortSignal cannot cross to the worker, so this thread kills on abort as Node would.
321 const { signal, ...rest } = options;
322 if (signal !== undefined) {
323 const abort = () => child.kill();
324 if (signal.aborted) queueMicrotask(abort);
325 else {
326 signal.addEventListener("abort", abort, { once: true });
327 child.once("exit", () => signal.removeEventListener("abort", abort));
328 }
329 }
330 this.children.set(id, child);
331 this.launching++;
332 this.syncRef();
333 this.post({
334 type: "spawn",
335 id,
336 command,
337 args: [...args],
338 // A worker's process.env is a copy from when it started; children get the server's current one.
339 options: { ...rest, stdio, env: rest.env ?? { ...process.env } },
340 });
341 return child;
342 }
343
344 syncRef(): void {
345 if (this.closed) return;
346 const referenced =
347 this.launching > 0 || [...this.children.values()].some((child) => child.referenced);
348 if (referenced) this.worker.ref();
349 else this.worker.unref();
350 }
351
352 onMessage(message: FromWorker): void {
353 const child = this.children.get(message.id);
354 if (child === undefined) return;
355 switch (message.type) {
356 case "spawn":
357 this.launching--;
358 child.spawned = true;
359 child.pid = message.pid;
360 child.emit("spawn");
361 break;
362 case "error":
363 if (!child.spawned) {
364 this.launching--;
365 child.exited = true;
366 this.release(child);
367 }
368 child.emit("error", toError(message.error));
369 break;
370 case "data":
371 child.onData(message.fd, message.data);
372 break;
373 case "written":
374 child.onWritten(message.fd, message.error);
375 break;
376 case "eof":
377 child.onEof(message.fd);
378 break;
379 case "finished":
380 child.onFinished(message.fd);
381 break;
382 case "stream-error":
383 child.onStreamError(message.fd, message.error);
384 break;
385 case "exit":
386 child.exit(message.code, message.signal);
387 break;
388 case "close":
389 child.emit("close", child.exitCode, child.signalCode);
390 this.release(child);
391 break;
392 }
393 }
394
395 release(child: WorkerChild): void {
396 this.children.delete(child.id);
397 this.syncRef();
398 this.pool.release(this);
399 }
400
401 fail(error: Error): void {
402 if (this.closed) return;
403 this.close();
404 for (const child of this.children.values()) {
405 if (child.exited) {
406 child.abandon();
407 continue;
408 }
409 if (!child.spawned) {
410 child.exited = true;
411 child.emit("error", error);
412 continue;
413 }
414 // The worker owned the only handle, so try to end the whole tree before reporting the exit.
415 const finish = () => {
416 child.exit(null, "SIGKILL");
417 child.abandon();
418 };
419 if (child.pid === undefined) finish();
420 else this.pool.killTree(child.pid, finish);
421 }
422 this.children.clear();
423 }
424
425 close(): void {
426 if (this.closed) return;
427 this.closed = true;
428 this.pool.workers.delete(this);
429 void this.worker.terminate();
430 }
431}
432
433class SpawnWorkerPool {
434 readonly workers = new Set<SpawnWorker>();
435 readonly platform: NodeJS.Platform;
436 #nextId = 0;
437
438 constructor(platform: NodeJS.Platform) {
439 this.platform = platform;
440 }
441
442 readonly spawn = (
443 command: string,
444 args: ReadonlyArray<string>,
445 options: NodeChildProcess.SpawnOptions,
446 ) => {
447 const workers = [...this.workers];
448 // A worker inside CreateProcess cannot start another launch until it returns.
449 const worker =
450 workers.find((candidate) => candidate.launching === 0) ??
451 (workers.length < MAX_WORKERS
452 ? this.#add()
453 : workers.reduce((best, candidate) =>
454 candidate.launching < best.launching ? candidate : best,
455 ));
456 return worker.spawn(++this.#nextId, command, args, options);
457 };
458
459 killTree(pid: number, done: () => void): void {
460 const killPid = () => {
461 try {
462 process.kill(pid, "SIGKILL");
463 } catch {}
464 };
465 if (this.platform !== "win32") {
466 killPid();
467 done();
468 return;
469 }
470 let settled = false;
471 const finish = (killed: boolean) => {
472 if (settled) return;
473 settled = true;
474 // As Effect's own kill does when taskkill fails, end at least the direct child.
475 if (!killed) killPid();
476 done();
477 };
478 this.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
479 stdio: "ignore",
480 windowsHide: true,
481 })
482 .on("error", () => finish(false))
483 .on("exit", (code) => finish(code === 0));
484 }
485
486 #add(): SpawnWorker {
487 const worker = new SpawnWorker(this);
488 this.workers.add(worker);
489 return worker;
490 }
491
492 release(worker: SpawnWorker): void {
493 if (worker.children.size > 0 || worker.launching > 0) return;
494 const idle = [...this.workers].filter(
495 (candidate) => candidate.children.size === 0 && candidate.launching === 0,
496 );
497 if (idle.length > MAX_IDLE_WORKERS) worker.close();
498 }
499
500 close(): void {
501 for (const worker of this.workers) worker.close();
502 }
503}
504
505let sharedPool: SpawnWorkerPool | undefined;
506
507/** A piped `child_process.spawn` for Windows launches outside Effect's spawner. */
508export const spawnPiped = (
509 command: string,
510 args: ReadonlyArray<string>,
511 options: Omit<NodeChildProcess.SpawnOptions, "stdio">,
512) =>
513 (sharedPool ??= new SpawnWorkerPool("win32")).spawn(command, args, {
514 ...options,
515 stdio: ["pipe", "pipe", "pipe"],
516 }) as WorkerChild & {
517 readonly stdin: NodeStream.Writable;
518 readonly stdout: NodeStream.Readable;
519 readonly stderr: NodeStream.Readable;
520 };
521
522export const layer = Layer.unwrap(
523 Effect.gen(function* () {
524 const platform = yield* HostProcess.Platform;
525 const pool = yield* Effect.acquireRelease(
526 Effect.sync(() => new SpawnWorkerPool(platform)),
527 (pool) => Effect.sync(() => pool.close()),
528 );
529 return NodeChildProcessSpawner.layerWithSpawn(pool.spawn);
530 }),
531);
532
533/** Workers on Windows, and on Linux where `NonBlockingSpawner` has no GNU `env -C` to use. */
534export const layerServer = Layer.unwrap(
535 Effect.gen(function* () {
536 const platform = yield* HostProcess.Platform;
537 if (platform === "win32") return layer;
538 if (platform === "linux" && !(yield* Effect.promise(supportsEnvChdir))) return layer;
539 return NodeChildProcessSpawner.layer;
540 }),
541);