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