Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/git-safe/spawn.ts

Raw
// spawn.ts — Shared spawn helper with timeout and git safety env vars

import { spawn } from "node:child_process";
import { StringDecoder } from "node:string_decoder";

const DEFAULT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;

export interface SpawnResult {
	stdout: string;
	stderr: string;
	code: number | null;
	killed: boolean;
	outputLimitExceeded: boolean;
}

/**
 * Spawn a command with timeout and structured error output.
 * Kills the owned process on timeout or cancellation.
 * GIT_TERMINAL_PROMPT=0 prevents credential prompts from hanging.
 */
export function spawnWithTimeout(
	cmd: string,
	args: string[],
	opts: {
		cwd?: string;
		timeout?: number;
		maxOutputBytes?: number;
		env?: Record<string, string>;
		signal?: AbortSignal;
	} = {},
): Promise<SpawnResult> {
	const {
		cwd,
		timeout = 60_000,
		env: extraEnv,
		signal,
		maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES,
	} = opts;

	return new Promise((resolve) => {
		const env = {
			...process.env,
			GIT_TERMINAL_PROMPT: "0",
			GIT_TERMINAL_PROMPT_AUTOCHECK: "0",
			...extraEnv,
		};
		const detached = process.platform !== "win32";
		const proc = spawn(cmd, args, {
			cwd,
			detached,
			env: env as Record<string, string>,
		});
		let stdout = "";
		let stderr = "";
		const stdoutDecoder = new StringDecoder("utf8");
		const stderrDecoder = new StringDecoder("utf8");
		let outputBytes = 0;
		let outputLimitExceeded = false;
		let timedOut = false;
		let aborted = false;
		let settled = false;
		let termination: Promise<void> | undefined;
		const cleanup = () => {
			clearTimeout(timer);
			signal?.removeEventListener("abort", onAbort);
			proc.stdin?.destroy();
			proc.stdout?.destroy();
			proc.stderr?.destroy();
		};
		const finish = (result: SpawnResult) => {
			if (settled) return;
			settled = true;
			clearTimeout(timer);
			void (termination ?? Promise.resolve()).then(() => {
				cleanup();
				resolve(result);
			});
		};
		const killOwnedProcessTree = (kind: NodeJS.Signals) => {
			if (proc.pid === undefined) return;
			try {
				if (detached) process.kill(-proc.pid, kind);
				else proc.kill(kind);
			} catch {
				try {
					proc.kill(kind);
				} catch {}
			}
		};
		const forceKillWindowsTree = (): Promise<void> =>
			new Promise((done) => {
				if (proc.pid === undefined) return done();
				try {
					const killer = spawn(
						"taskkill",
						["/pid", String(proc.pid), "/T", "/F"],
						{ stdio: "ignore", windowsHide: true },
					);
					let finished = false;
					const finishKill = () => {
						if (finished) return;
						finished = true;
						clearTimeout(killerTimeout);
						try {
							proc.kill("SIGKILL");
						} catch {}
						done();
					};
					const killerTimeout = setTimeout(() => {
						killer.kill("SIGKILL");
						finishKill();
					}, 1_000);
					killerTimeout.unref();
					killer.once("close", finishKill);
					killer.once("error", finishKill);
				} catch {
					try {
						proc.kill("SIGKILL");
					} catch {}
					done();
				}
			});
		const terminate = () => {
			if (termination) return;
			proc.stdin?.destroy();
			proc.stdout?.destroy();
			proc.stderr?.destroy();
			if (process.platform === "win32") termination = forceKillWindowsTree();
			else {
				// Disposable clone work has no graceful-shutdown state to retain.
				// Kill the entire owned group before parent exit can release the target queue.
				killOwnedProcessTree("SIGKILL");
				termination = Promise.resolve();
			}
		};
		const onAbort = () => {
			aborted = true;
			terminate();
		};
		const timer = setTimeout(() => {
			timedOut = true;
			terminate();
		}, timeout);
		if (signal?.aborted) onAbort();
		else signal?.addEventListener("abort", onAbort, { once: true });
		const capture = (data: Buffer, stream: "stdout" | "stderr") => {
			if (outputLimitExceeded) return;
			const remaining = Math.max(0, maxOutputBytes - outputBytes);
			const kept = data.subarray(0, remaining);
			if (stream === "stdout") stdout += stdoutDecoder.write(kept);
			else stderr += stderrDecoder.write(kept);
			outputBytes += kept.length;
			if (data.length > remaining) {
				outputLimitExceeded = true;
				terminate();
			}
		};
		proc.stdout?.on("data", (data: Buffer) => capture(data, "stdout"));
		proc.stderr?.on("data", (data: Buffer) => capture(data, "stderr"));
		proc.on("close", (code) => {
			if (!outputLimitExceeded) {
				stdout += stdoutDecoder.end();
				stderr += stderrDecoder.end();
			}
			finish({
				stdout,
				stderr,
				code,
				killed: timedOut || aborted || outputLimitExceeded,
				outputLimitExceeded,
			});
		});
		proc.on("error", (err) => {
			finish({
				stdout,
				stderr: err.message,
				code: null,
				killed: timedOut || aborted || outputLimitExceeded,
				outputLimitExceeded,
			});
		});
	});
}

/** Spawn and expect exit code 0. Throws structured error on failure. */
export async function spawnExpect(
	cmd: string,
	args: string[],
	opts: {
		cwd?: string;
		timeout?: number;
		maxOutputBytes?: number;
		env?: Record<string, string>;
		signal?: AbortSignal;
	} = {},
): Promise<string> {
	if (opts.signal?.aborted) throw opts.signal.reason;
	const result = await spawnWithTimeout(cmd, args, opts);
	if (opts.signal?.aborted) throw opts.signal.reason;
	if (result.outputLimitExceeded)
		throw new SpawnOutputLimitError(
			opts.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
		);
	if (result.killed)
		throw new SpawnTimeoutError(cmd, args, opts.timeout ?? 60_000);
	if (result.code !== 0) {
		throw new SpawnExitError(
			cmd,
			args,
			result.code,
			result.stderr,
			result.stdout,
		);
	}
	return result.stdout;
}

export class SpawnOutputLimitError extends Error {
	constructor(maxOutputBytes: number) {
		super(`Command exceeded output limit of ${maxOutputBytes} bytes`);
		this.name = "SpawnOutputLimitError";
	}
}

export class SpawnTimeoutError extends Error {
	constructor(
		public readonly cmd: string,
		public readonly args: string[],
		public readonly timeoutMs: number,
	) {
		super(`Command timed out after ${timeoutMs}ms: ${cmd} ${args.join(" ")}`);
		this.name = "SpawnTimeoutError";
	}
}

export class SpawnExitError extends Error {
	constructor(
		public readonly cmd: string,
		public readonly args: string[],
		public readonly exitCode: number | null,
		public readonly stderr: string,
		public readonly stdout: string,
	) {
		const stderrLine = stderr.trim().split("\n").pop() ?? "";
		super(
			`Command failed (exit ${exitCode}): ${cmd} ${args.join(" ")}\n${stderrLine}`,
		);
		this.name = "SpawnExitError";
	}
}