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

processLauncherWorker.ts

112 lines4.2 KB

1// @effect-diagnostics nodeBuiltinImport:off - the launcher loads only Node builtins so it starts in milliseconds.
2import * as NodeChildProcess from "node:child_process";
3import type * as NodeNet from "node:net";
4​
5export interface LauncherSpawnRequest {
6 readonly type: "spawn";
7 readonly id: number;
8 readonly command: string;
9 readonly args: ReadonlyArray<string>;
10 readonly options: NodeChildProcess.SpawnOptions;
12​
13export interface LauncherError {
14 readonly message: string;
15 readonly code?: string | undefined;
16 readonly errno?: number | undefined;
17 readonly syscall?: string | undefined;
18 readonly path?: string | undefined;
20​
21/** Per child, in order: `pid`, `stdio` per piped fd (carrying its socket), `spawn`, then `exit`; or `error`. */
22export type LauncherEvent =
23 | { readonly type: "ready" }
24 | { readonly type: "pid"; readonly id: number; readonly pid: number }
25 | { readonly type: "stdio"; readonly id: number; readonly fd: number }
26 | { readonly type: "spawn"; readonly id: number }
27 | {
28 readonly type: "exit";
29 readonly id: number;
30 readonly code: number | null;
31 readonly signal: NodeJS.Signals | null;
32 }
33 | { readonly type: "error"; readonly id: number; readonly error: LauncherError };
34​
35// Leaves out spawnargs; the server's spawner redacts its own copy.
36const toLauncherError = (cause: unknown): LauncherError => {
37 const error = cause as Partial<NodeJS.ErrnoException> | undefined;
38 return {
39 message: typeof error?.message === "string" ? error.message : String(cause),
40 code: error?.code,
41 errno: error?.errno,
42 syscall: error?.syscall,
43 path: error?.path,
44 };
45};
46​
47// Child stdio has no public paused option; this is what net's pauseOnCreate does.
48const stopReading = (socket: NodeNet.Socket) =>
49 (socket as unknown as { _handle?: { readStop?: () => void } | null })._handle?.readStop?.();
50​
51// Bundled import.meta.main is always true; importing this module must have no side effects.
52export function runProcessLauncher(): void {
53 const channel = process.send?.bind(process);
54 if (!channel) {
55 process.stderr.write("The process launcher is started by the T3 server.\n");
56 process.exitCode = 1;
57 return;
58 }
59 const send = (event: LauncherEvent, socket?: NodeNet.Socket) =>
60 channel(event, socket, undefined, () => {});
61 const children = new Map<number, NodeChildProcess.ChildProcess>();
62​
63 // Group signals target the server; this process exits when the server's channel closes.
64 for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => {});
65 process.on("disconnect", () => {
66 for (const child of children.values()) {
67 try {
68 process.kill(-child.pid!, "SIGKILL");
69 } catch {
70 child.kill("SIGKILL");
71 }
72 }
73 process.exit(0);
74 });
75​
76 process.on("message", (request: LauncherSpawnRequest) => {
77 const { id } = request;
78 let child: NodeChildProcess.ChildProcess;
79 try {
80 child = NodeChildProcess.spawn(request.command, [...request.args], request.options);
81 } catch (cause) {
82 send({ type: "error", id, error: toLauncherError(cause) });
83 return;
84 }
85 const stdio = child.stdio.map((socket) => socket as NodeNet.Socket | null);
86 // The server reads and writes these pipes itself, so no byte may be consumed here.
87 for (const socket of stdio) if (socket) stopReading(socket);
88 // Node flushes and destroys a child's stdio at exit, even while a socket waits to be sent.
89 child.stdin = null;
90 child.stdout = null;
91 child.stderr = null;
92 child.stdio.fill(null);
93 child.on("error", (cause) => {
94 if (child.pid === undefined) for (const socket of stdio) socket?.destroy();
95 send({ type: "error", id, error: toLauncherError(cause) });
96 });
97 child.once("spawn", () => {
98 children.set(id, child);
99 // First, so the server can kill the child if this process dies while handing over its pipes.
100 send({ type: "pid", id, pid: child.pid! });
101 stdio.forEach((socket, fd) => {
102 if (socket) send({ type: "stdio", id, fd }, socket);
103 });
104 send({ type: "spawn", id });
105 });
106 child.once("exit", (code, signal) => {
107 children.delete(id);
108 send({ type: "exit", id, code, signal });
109 });
110 });
111 send({ type: "ready" });