diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 7b980e01b5fa7..4bbc5801d2c83 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -53,6 +53,10 @@ if ( const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3)); if (launcher !== undefined && launcherOptions !== undefined) { await launcher.runServiceLauncherCli(launcherOptions); + } else if (process.argv[2] === "__process-launcher") { + // Single executables host the launcher here; other builds start process-launcher.mjs directly. + const { runProcessLauncher } = await import("./process/processLauncherWorker.ts"); + runProcessLauncher(); } else { const { runCliCommand } = await loadCliMain(); await runCliCommand(); diff --git a/apps/server/src/process-launcher.ts b/apps/server/src/process-launcher.ts new file mode 100644 index 0000000000000..7399bdc7d72ce --- /dev/null +++ b/apps/server/src/process-launcher.ts @@ -0,0 +1,3 @@ +import { runProcessLauncher } from "./process/processLauncherWorker.ts"; + +runProcessLauncher(); diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts new file mode 100644 index 0000000000000..f62a3c8445da2 --- /dev/null +++ b/apps/server/src/process/ProcessLauncher.ts @@ -0,0 +1,380 @@ +// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - IPC and timer callbacks implement the spawner boundary, as in the native spawner. +import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; +import type * as NodeNet from "node:net"; +import type * as NodeStream from "node:stream"; +import * as NodeChildProcessSpawner from "@effect/platform-node-shared/NodeChildProcessSpawner"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import * as NonBlockingSpawner from "./NonBlockingSpawner.ts"; +import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorker.ts"; + +// A launcher that misses either is treated as hung; neither happens to a healthy one. +const READY_TIMEOUT = "10 seconds"; +const SPAWN_REPLY_TIMEOUT = "10 seconds"; + +/** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ +class HostedChild + extends NodeEvents.EventEmitter + implements NodeChildProcessSpawner.SpawnedChildProcess +{ + pid: number | undefined; + exitCode: number | null = null; + signalCode: NodeJS.Signals | null = null; + stdin: NodeStream.Writable | null = null; + stdout: NodeStream.Readable | null = null; + stderr: NodeStream.Readable | null = null; + readonly stdio: Array = []; + referenced = true; + /** Its pipes are handed over and the native spawner owns it. */ + started = false; + /** No longer awaited: its spawn failed, timed out or it exited. */ + settled = false; + readonly launcher: Launcher; + /** The fds requested as pipes, each of which must arrive before the child counts as started. */ + readonly pipes: ReadonlyArray; + + constructor(launcher: Launcher, stdio: NodeChildProcess.SpawnOptions["stdio"]) { + super(); + this.launcher = launcher; + this.pipes = stdioModes(stdio).flatMap((mode, fd) => (isPipe(mode) ? [fd] : [])); + } + + kill(signal: NodeJS.Signals | number = "SIGTERM"): boolean { + if (this.pid === undefined || this.exitCode !== null || this.signalCode !== null) return false; + try { + process.kill(this.pid, signal); + return true; + } catch { + return false; + } + } + + ref(): void { + this.referenced = true; + syncRef(this.launcher); + } + + unref(): void { + this.referenced = false; + syncRef(this.launcher); + } + + fail(error: Error): void { + this.settled = true; + this.emit("error", error); + } + + exit(code: number | null, signal: NodeJS.Signals | null): void { + this.settled = true; + this.exitCode = code; + this.signalCode = signal; + // Node destroys stdin at exit and drains output nobody reads, so pipes never hold a child. + this.stdin?.destroy(); + this.emit("exit", code, signal); + process.nextTick(() => { + for (const stream of [this.stdout, this.stderr]) { + if ( + stream && + stream.listenerCount("data") === 0 && + stream.listenerCount("readable") === 0 + ) { + stream.resume(); + } + } + }); + } +} + +const stdioModes = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + typeof stdio === "string" || stdio === undefined ? Array(3).fill(stdio) : stdio; + +const isPipe = (mode: unknown) => + mode === undefined || mode === null || mode === "pipe" || mode === "overlapped"; + +// The launcher's own stdin and stdout are /dev/null, so only pipes and "ignore" mean the same there. +const isHostable = (stdio: NodeChildProcess.SpawnOptions["stdio"]) => + stdioModes(stdio).every((mode) => isPipe(mode) || mode === "ignore"); + +interface Launcher { + readonly worker: NodeChildProcess.ChildProcess; + readonly children: Map; + readonly ready: Deferred.Deferred; + closed: boolean; + /** Counts messages from the launcher, so a slow server is not mistaken for a hung launcher. */ + heard: number; +} + +const syncRef = (launcher: Launcher) => { + if ([...launcher.children.values()].some((child) => child.referenced)) { + launcher.worker.channel?.ref(); + } else { + launcher.worker.channel?.unref(); + } +}; + +const killGroup = (pid: number) => { + try { + process.kill(-pid, "SIGKILL"); + } catch { + // The group is already gone. + } +}; + +const launcherArguments = Effect.fn("ProcessLauncher.launcherArguments")(function* () { + // A single executable has no sibling script, so it hosts the launcher as a hidden subcommand. + if (yield* HostProcess.IsExecutable) return ["__process-launcher"]; + const path = yield* Path.Path; + const fromSource = import.meta.url.endsWith(".ts"); + return [ + ...(fromSource ? ["--experimental-strip-types"] : []), + yield* path + .fromFileUrl( + new URL(fromSource ? "../process-launcher.ts" : "./process-launcher.mjs", import.meta.url), + ) + .pipe(Effect.orDie), + ]; +}); + +// On Linux, libuv forks the whole server for every spawn and blocks the event loop while the +// kernel copies its page tables, so commands are launched by a small long-lived helper instead. +// The helper passes each child's pipes back, so the native spawner keeps all of its semantics. +export const make = Effect.fn("ProcessLauncher.make")(function* ( + replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, +) { + const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; + if ((yield* HostProcess.Platform) !== "linux") return fallback; + + const executablePath = yield* HostProcess.ExecutablePath; + const args = yield* launcherArguments(); + let current: Launcher | undefined; + // A launcher that never starts will not start next time either; stop forking for it. + let unavailable = false; + let warned = false; + let shutDown = false; + let nextId = 0; + + const close = (launcher: Launcher, hung = false) => { + if (launcher.closed) return; + launcher.closed = true; + if (current === launcher) current = undefined; + const ready = Deferred.isDoneUnsafe(launcher.ready); + if (!ready) unavailable = true; + Deferred.doneUnsafe(launcher.ready, Exit.succeed(false)); + const error = new Error( + hung ? "The process launcher did not respond." : "The process launcher exited.", + ); + for (const child of launcher.children.values()) { + if (child.settled) continue; + if (child.pid !== undefined) killGroup(child.pid); + if (child.started) { + child.exit(null, "SIGKILL"); + } else { + for (const stream of child.stdio) stream?.destroy(); + child.fail(error); + } + } + launcher.children.clear(); + if (launcher.worker.connected) launcher.worker.disconnect(); + // A started launcher kills its children and exits once disconnected; a hung one never reads that. + if (hung || !ready) launcher.worker.kill("SIGKILL"); + }; + + const onEvent = ( + launcher: Launcher, + event: LauncherEvent, + socket: NodeNet.Socket | undefined, + ) => { + launcher.heard++; + if (event.type === "ready") { + Deferred.doneUnsafe(launcher.ready, Exit.succeed(true)); + return; + } + const child = launcher.children.get(event.id); + if (child === undefined) { + socket?.destroy(); + return; + } + switch (event.type) { + case "stdio": + if (child.settled) socket?.destroy(); + else if (socket) { + child.stdio[event.fd] = socket; + if (event.fd === 0) { + // Unlike Node's own stdin pipe this socket also reads, and an unread write resets it. + socket.on("error", () => {}); + child.stdin = socket; + } else if (event.fd === 1) child.stdout = socket; + else if (event.fd === 2) child.stderr = socket; + } + break; + case "pid": + child.pid = event.pid; + break; + case "spawn": + // A lost handle would otherwise read as a command that printed nothing. + if (child.pipes.some((fd) => child.stdio[fd] == null)) { + if (child.pid !== undefined) killGroup(child.pid); + for (const stream of child.stdio) stream?.destroy(); + child.fail(new Error("The process launcher did not hand over the command's pipes.")); + break; + } + child.started = true; + child.emit("spawn"); + break; + case "exit": + launcher.children.delete(event.id); + syncRef(launcher); + if (!child.settled) child.exit(event.code, event.signal); + break; + case "error": + if (child.pid !== undefined || child.settled) break; + launcher.children.delete(event.id); + syncRef(launcher); + child.fail(Object.assign(new Error(event.error.message), event.error)); + break; + } + }; + + const launch = (): Launcher | undefined => { + if (unavailable || shutDown) return undefined; + if (current !== undefined) return current; + const env: NodeJS.ProcessEnv = { ...process.env, ELECTRON_RUN_AS_NODE: "1" }; + delete env.NODE_OPTIONS; + // `node --watch` children would report their imports over the launcher's IPC channel. + delete env.WATCH_REPORT_DEPENDENCIES; + let worker: NodeChildProcess.ChildProcess; + try { + worker = NodeChildProcess.spawn(executablePath, args, { + cwd: "/", + env, + stdio: ["ignore", "ignore", "inherit", "ipc"], + }); + } catch { + // Node throws some errnos, such as ENOMEM, instead of emitting "error". + unavailable = true; + return undefined; + } + const launcher: Launcher = { + worker, + children: new Map(), + ready: Deferred.makeUnsafe(), + closed: false, + heard: 0, + }; + worker.unref(); + worker.channel?.unref(); + worker.on("message", (event: LauncherEvent, socket: NodeNet.Socket | undefined) => + onEvent(launcher, event, socket), + ); + worker.on("error", () => close(launcher)); + worker.once("disconnect", () => close(launcher)); + worker.once("exit", () => close(launcher)); + current = launcher; + return launcher; + }; + + const spawnProcess = ( + command: string, + commandArgs: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ): NodeChildProcessSpawner.SpawnedChildProcess => { + const launcher = current; + // Lost or replaced between the readiness check and the spawn; rare enough to fork for. + if ( + launcher === undefined || + launcher.closed || + !Deferred.isDoneUnsafe(launcher.ready) || + !isHostable(options.stdio) + ) { + return NodeChildProcess.spawn(command, [...commandArgs], options); + } + const id = ++nextId; + const child = new HostedChild(launcher, options.stdio); + launcher.children.set(id, child); + syncRef(launcher); + const request: LauncherSpawnRequest = { + type: "spawn", + id, + command, + args: commandArgs, + // The launcher runs in `/` with its own environment; children inherit the server's. + options: { ...options, cwd: options.cwd ?? process.cwd(), env: options.env ?? process.env }, + }; + launcher.worker.send(request, (error) => { + if (error) close(launcher); + }); + // The native spawner waits for the reply uninterruptibly, so a hung launcher must not hold it. + // Hung means silent for a whole window; replies queued behind a busy server count once read. + const watch = (heard: number) => + setTimeout( + () => + setImmediate(() => { + if (child.started || child.settled) return; + if (launcher.heard === heard) close(launcher, true); + else watch(launcher.heard); + }), + Duration.toMillis(replyTimeout), + ).unref(); + watch(launcher.heard); + return child; + }; + + // The trampoline keeps a hung cwd or PATH entry from stalling the launcher, and with it every command. + // Fresh: the server has already built this layer around the forking spawner. + const hosted = Context.get( + yield* Layer.build( + Layer.fresh(NonBlockingSpawner.layer).pipe( + Layer.provide(NodeChildProcessSpawner.layerWithSpawn(spawnProcess)), + ), + ), + ChildProcessSpawner.ChildProcessSpawner, + ); + + const warnUnavailable = Effect.suspend(() => { + if (!unavailable || warned || shutDown) return Effect.void; + warned = true; + return Effect.logWarning("The process launcher did not start; commands fork the server."); + }); + + const isReady = Effect.suspend(() => { + const launcher = launch(); + if (launcher === undefined) return Effect.as(warnUnavailable, false); + return Deferred.await(launcher.ready).pipe( + Effect.timeoutOption(READY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.tap((ready) => { + if (ready) return Effect.void; + close(launcher); + return warnUnavailable; + }), + ); + }); + + yield* Effect.addFinalizer(() => + Effect.sync(() => { + shutDown = true; + if (current) close(current); + }), + ); + // Start while the server is still small; the launcher's own fork is the last full-size one. + launch(); + return ChildProcessSpawner.make((command) => + Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), + ); +}); + +/** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ +export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); + +/** The server's one spawner: memoized, so every build site shares a single launcher. */ +export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/process/processLauncherWorker.ts b/apps/server/src/process/processLauncherWorker.ts new file mode 100644 index 0000000000000..58918127d90ad --- /dev/null +++ b/apps/server/src/process/processLauncherWorker.ts @@ -0,0 +1,112 @@ +// @effect-diagnostics nodeBuiltinImport:off - the launcher loads only Node builtins so it starts in milliseconds. +import * as NodeChildProcess from "node:child_process"; +import type * as NodeNet from "node:net"; + +export interface LauncherSpawnRequest { + readonly type: "spawn"; + readonly id: number; + readonly command: string; + readonly args: ReadonlyArray; + readonly options: NodeChildProcess.SpawnOptions; +} + +export interface LauncherError { + readonly message: string; + readonly code?: string | undefined; + readonly errno?: number | undefined; + readonly syscall?: string | undefined; + readonly path?: string | undefined; +} + +/** Per child, in order: `pid`, `stdio` per piped fd (carrying its socket), `spawn`, then `exit`; or `error`. */ +export type LauncherEvent = + | { readonly type: "ready" } + | { readonly type: "pid"; readonly id: number; readonly pid: number } + | { readonly type: "stdio"; readonly id: number; readonly fd: number } + | { readonly type: "spawn"; readonly id: number } + | { + readonly type: "exit"; + readonly id: number; + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + } + | { readonly type: "error"; readonly id: number; readonly error: LauncherError }; + +// Leaves out spawnargs; the server's spawner redacts its own copy. +const toLauncherError = (cause: unknown): LauncherError => { + const error = cause as Partial | undefined; + return { + message: typeof error?.message === "string" ? error.message : String(cause), + code: error?.code, + errno: error?.errno, + syscall: error?.syscall, + path: error?.path, + }; +}; + +// Child stdio has no public paused option; this is what net's pauseOnCreate does. +const stopReading = (socket: NodeNet.Socket) => + (socket as unknown as { _handle?: { readStop?: () => void } | null })._handle?.readStop?.(); + +// Bundled import.meta.main is always true; importing this module must have no side effects. +export function runProcessLauncher(): void { + const channel = process.send?.bind(process); + if (!channel) { + process.stderr.write("The process launcher is started by the T3 server.\n"); + process.exitCode = 1; + return; + } + const send = (event: LauncherEvent, socket?: NodeNet.Socket) => + channel(event, socket, undefined, () => {}); + const children = new Map(); + + // Group signals target the server; this process exits when the server's channel closes. + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => {}); + process.on("disconnect", () => { + for (const child of children.values()) { + try { + process.kill(-child.pid!, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + process.exit(0); + }); + + process.on("message", (request: LauncherSpawnRequest) => { + const { id } = request; + let child: NodeChildProcess.ChildProcess; + try { + child = NodeChildProcess.spawn(request.command, [...request.args], request.options); + } catch (cause) { + send({ type: "error", id, error: toLauncherError(cause) }); + return; + } + const stdio = child.stdio.map((socket) => socket as NodeNet.Socket | null); + // The server reads and writes these pipes itself, so no byte may be consumed here. + for (const socket of stdio) if (socket) stopReading(socket); + // Node flushes and destroys a child's stdio at exit, even while a socket waits to be sent. + child.stdin = null; + child.stdout = null; + child.stderr = null; + child.stdio.fill(null); + child.on("error", (cause) => { + if (child.pid === undefined) for (const socket of stdio) socket?.destroy(); + send({ type: "error", id, error: toLauncherError(cause) }); + }); + child.once("spawn", () => { + children.set(id, child); + // First, so the server can kill the child if this process dies while handing over its pipes. + send({ type: "pid", id, pid: child.pid! }); + stdio.forEach((socket, fd) => { + if (socket) send({ type: "stdio", id, fd }, socket); + }); + send({ type: "spawn", id }); + }); + child.once("exit", (code, signal) => { + children.delete(id); + send({ type: "exit", id, code, signal }); + }); + }); + send({ type: "ready" }); +} diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 6768fa23c763b..bd4ad037defa6 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,17 +1,27 @@ +// @effect-diagnostics nodeBuiltinImport:off - A test kills the helper mid-handoff and watches its child through a FIFO. import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeNet from "node:net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Cause from "effect/Cause"; +import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { ChildProcessSpawner } from "effect/process"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as ProcessRunner from "./processRunner.ts"; type ChildProcessCommand = { @@ -288,6 +298,381 @@ describe("runProcess", () => { ); }); +// The server's spawner stack, as server.ts builds it. +const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer)); + +// A command's $PPID, required to be the helper: signalling a fallback's parent would hit the test runner. +const expectHelperPid = (stdout: string) => { + expect(stdout.trim()).toMatch(/^[1-9]\d*$/); + const pid = Number(stdout.trim()); + expect(pid, "the command's parent process is the server process itself").not.toBe(process.pid); + return pid; +}; + +describe("ProcessRunner.layer", () => { + // Forking the server for every git call stalls its event loop in proportion to its RSS. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "launches commands from a helper process instead of forking the server", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expectHelperPid(result.stdout); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + // The helper's stdin and stdout are /dev/null, so inherited stdio must come from the server. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "forks the server for a command that inherits its stdio", + () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", ["-c", "echo $PPID >&2"], { stdin: "inherit" }), + ); + const parent = yield* handle.stderr.pipe(Stream.decodeText(), Stream.mkString); + + expect(Number(parent.trim())).toBe(process.pid); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layerServer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + // Node throws some spawn errnos, such as ENOMEM, instead of emitting "error". + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs commands natively when starting the helper throws", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const launcherArgs = args[1]; + if ( + Array.isArray(launcherArgs) && + launcherArgs.some((arg) => String(arg).includes("process-launcher")) + ) { + throw Object.assign(new Error("spawn ENOMEM"), { code: "ENOMEM" }); + } + return spawn(...args); + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] }); + + expect(Number(result.stdout.trim())).toBe(process.pid); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + // Callers report a missing CLI from the NotFound reason. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "reports a missing command as a NotFound spawn failure", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "t3code-missing-command", args: [] }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills descendants that ignore SIGTERM when a run is interrupted", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const runner = yield* ProcessRunner.ProcessRunner; + const started = yield* Deferred.make(); + const run = yield* runner + .run({ + command: "sh", + // The descendant prints its pid only once it ignores SIGTERM. + args: ["-c", `sh -c 'trap "" TERM; echo $$; exec sleep 1000' & wait`], + onStdoutChunk: (chunk) => + Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))), + }) + .pipe(Effect.forkChild); + const descendant = yield* Deferred.await(started); + const ignored = (yield* fs.readFileString(`/proc/${descendant}/status`)).match( + /^SigIgn:\s*([0-9a-f]+)$/m, + )?.[1]; + expect( + BigInt(`0x${ignored ?? "0"}`) & (1n << 14n), + "the descendant ignores SIGTERM", + ).not.toBe(0n); + yield* Fiber.interrupt(run); + // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it. + const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe( + Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]), + Effect.orElseSucceed(() => "gone"), + ); + + expect(["gone", "Z"]).toContain(state); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provideMerge(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs in the server's working directory and fails stdin a command never reads", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const result = yield* runner.run({ command: "pwd", args: [] }); + const error = yield* runner + .run({ command: "true", args: [], stdin: "x".repeat(16 * 1024 * 1024) }) + .pipe(Effect.flip); + + expect(result.stdout.trim()).toBe(process.cwd()); + expect(error._tag).toBe("ProcessStdinError"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "rejects a NUL byte in an environment value without echoing the value", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const error = yield* runner + .run({ command: "true", args: [], env: { T3_TOKEN: "secret\0value" } }) + .pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument"); + expect(String(error.cause)).toContain("T3_TOKEN"); + expect(String(error.cause)).not.toContain("secret"); + }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))), + ); + + // Descendants keep writing after the leader exits; losing the helper must not truncate that. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "delivers output written after the helper process dies", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make("sh", [ + "-c", + `d=$(mktemp -d); mkfifo "$d/f"; (cat "$d/f"; rm -r "$d") & echo "$PPID $d/f"`, + ]), + ); + expect(yield* handle.exitCode).toBe(0); + const output = yield* handle.stdout.pipe( + Stream.tap((chunk) => { + const [helper = "", fifo] = new TextDecoder().decode(chunk).trim().split(" "); + if (fifo === undefined) return Effect.void; + process.kill(expectHelperPid(helper), "SIGKILL"); + return fs.writeFileString(fifo, "complete\n"); + }), + Stream.decodeText(), + Stream.mkString, + ); + + expect(output).toMatch(/ \S+\ncomplete\n$/); + }).pipe( + Effect.scoped, + Effect.provide(ProcessLauncher.layer.pipe(Layer.provideMerge(NodeServices.layer))), + ), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "kills a command whose helper dies while handing over its pipes", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const fifo = `${yield* fs.makeTempDirectoryScoped()}/alive`; + NodeChildProcess.execFileSync("mkfifo", [fifo]); + // Reaches EOF once the command, its only writer, is gone. + const alive = new NodeNet.Socket({ + fd: NodeFS.openSync(fifo, NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK), + readable: true, + writable: false, + }); + const commandReady = Deferred.makeUnsafe(); + const commandGone = Deferred.makeUnsafe(); + alive.once("data", () => Deferred.doneUnsafe(commandReady, Exit.void)); + alive.once("end", () => Deferred.doneUnsafe(commandGone, Exit.void)); + + const helperPaused = Deferred.makeUnsafe(); + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "stdio" || Deferred.isDoneUnsafe(helperPaused)) return; + process.kill(helper.pid!, "SIGSTOP"); + Deferred.doneUnsafe(helperPaused, Exit.succeed(helper.pid!)); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + const run = yield* runner + .run({ + command: "sh", + args: ["-c", `exec 3>"$0"; echo ready >&3; exec sleep 1000`, fifo], + }) + .pipe(Effect.forkChild); + const helper = yield* Deferred.await(helperPaused); + yield* Deferred.await(commandReady); + process.kill(helper, "SIGKILL"); + + expect((yield* Effect.flip(Fiber.join(run)))._tag).toBe("ProcessSpawnError"); + yield* Deferred.await(commandGone); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "fails a command whose output pipe never arrives instead of returning no output", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + const emit = helper.emit.bind(helper); + helper.emit = ((event: string, ...rest: Array) => { + const [message, socket] = rest as [{ type?: string; fd?: number }, NodeNet.Socket?]; + if (event !== "message" || message.type !== "stdio" || message.fd !== 1) { + return emit(event, ...rest); + } + socket?.destroy(); + return emit(event, message, undefined); + }) as typeof helper.emit; + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner); + + const error = yield* runner.run({ command: "echo", args: ["output"] }).pipe(Effect.flip); + + expect(error._tag).toBe("ProcessSpawnError"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "replaces a helper that stops answering", + () => + Effect.gen(function* () { + const runner = yield* ProcessRunner.ProcessRunner; + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); + const helper = yield* parentPid; + process.kill(helper, "SIGSTOP"); + const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); + const replacement = yield* parentPid; + + expect(error._tag).toBe("ProcessSpawnError"); + expect(replacement).not.toBe(helper); + expect(replacement).not.toBe(process.pid); + }).pipe( + Effect.provide( + ProcessRunner.layer.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + Layer.provide(NodeServices.layer), + ), + ), + ), + ); + + // Under load the server reads the helper's replies late; that is not a hung helper. + it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "keeps a helper whose replies wait behind a busy server", + () => + Effect.gen(function* () { + const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)( + "node:child_process", + ); + const spawn = childProcess.spawn; + let blocked = false; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = ((...args: Parameters) => { + const helper = spawn(...args); + helper.on("message", (event: { readonly type: string }) => { + if (event.type !== "pid" || blocked) return; + blocked = true; + // Holds the server's event loop past the reply deadline, as a loaded server does. + NodeChildProcess.execFileSync("sleep", ["1.5"]); + }); + return helper; + }) as typeof spawn; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = spawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + const runner = Context.get( + yield* Layer.build( + ProcessRunner.layer.pipe( + Layer.provide( + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + ProcessLauncher.make("1 second"), + ), + ), + ), + ), + ProcessRunner.ProcessRunner, + ); + const parentPid = runner + .run({ command: "sh", args: ["-c", "echo $PPID"] }) + .pipe(Effect.map((result) => expectHelperPid(result.stdout))); + const first = yield* parentPid; + const second = yield* parentPid; + + expect(blocked).toBe(true); + expect(second).toBe(first); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); + describe("isWindowsCommandNotFound", () => { it.effect("matches the localized German cmd.exe error text", () => Effect.gen(function* () { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 499c1e2acc0ca..26cea18609b93 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,7 +33,6 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; -import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; import { withRootRequestSpans, withUntracedRequests } from "./http.ts"; @@ -48,6 +47,7 @@ import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as ProcessLauncher from "./process/ProcessLauncher.ts"; import * as SpawnWorker from "./process/SpawnWorker.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; @@ -410,11 +410,11 @@ const layerHttpServer = Layer.unwrap( ).pipe( Layer.provide(ManagedPolicy.layer), // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one. - (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)), + (layer) => ProcessLauncher.layerServer.pipe(Layer.provideMerge(layer)), ); const layerPlatformServices = DocumentText.layer.pipe( - Layer.provideMerge(NonBlockingSpawner.layer), + Layer.provideMerge(ProcessLauncher.layerServer), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerSpawner)), ); @@ -1436,5 +1436,7 @@ const layerMakeServer = Layer.unwrap( export const runServer = Layer.launch( // For the layers above whose spawner requirement is not met by one of them. - layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer.pipe(Layer.provide(layerSpawner)))), + layerMakeServer.pipe( + Layer.provide(ProcessLauncher.layerServer.pipe(Layer.provide(layerSpawner))), + ), ); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 882469b57a5c0..c3b5d4143086b 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -25,6 +25,7 @@ import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; import { gitCommandDuration, gitCommandsTotal } from "../observability/Metrics.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; import type * as VcsDriver from "./VcsDriver.ts"; @@ -154,6 +155,33 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +// Forking the server for every git call stalls its event loop in proportion to its RSS. +it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "runs git from the process launcher instead of forking the server", + () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const result = yield* driver.execute({ + operation: "GitVcsDriver.test.parentPid", + cwd: process.cwd(), + args: ["-c", "alias.parent-pid=!awk '{print $4}' /proc/$PPID/stat", "parent-pid"], + }); + + assert.match(result.stdout.trim(), /^[1-9]\d*$/); + assert.notStrictEqual(Number(result.stdout.trim()), process.pid); + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide(layerServerConfig), + Layer.provideMerge(VcsProcess.layer), + // The server's spawner stack, as server.ts builds it. + Layer.provide(ProcessLauncher.layerServer), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + interface UntrackedBlobChange { readonly git: Effect.Success>["git"]; readonly write: ( diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 2715d2987b604..2bec8830d86c5 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -110,12 +110,12 @@ export default mergeConfig( }, }, ], - // SEA embeds one entry; expose the history worker as a hidden subcommand. + // SEA embeds one entry; expose the workers as hidden subcommands. entry: packBootstrap ? ["src/bin.ts"] : packExecutable ? ["src/binMain.ts"] - : ["src/bin.ts", "src/claude-history-worker.ts"], + : ["src/bin.ts", "src/claude-history-worker.ts", "src/process-launcher.ts"], outDir: packBootstrap ? "dist-exe" : packExecutable ? cliAssetDir : "dist", sourcemap: !packExecutable, clean: true, diff --git a/knip.jsonc b/knip.jsonc index bd3228b7ac504..02ebb4bc8fecf 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -57,6 +57,7 @@ "entry": [ "src/bin.ts!", "src/claude-history-worker.ts!", + "src/process-launcher.ts!", "scripts/cli.ts", "scripts/fetch-expo-schema.ts", "scripts/probe-claude-fork-local-rollback-replay.ts",