Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/src/gates.ts

Raw
import { spawn } from "node:child_process";
import { basename, resolve } from "node:path";

/** A raw executable; no shell or interpreter is implied. */
export type Gate = {
	name?: string;
	command: string;
	args?: string[];
	env?: Record<string, string>;
	cwd?: string;
};

export type GateResult = {
	exitCode: number | null;
	stdout: string;
	stderr: string;
	truncated: boolean;
	error: string | null;
	startedAt: number;
	endedAt: number;
};

export type GatePass = {
	attempt: number;
	results: GateResult[];
	/** Index of the first failing gate; null when every gate exited 0. */
	failedIndex: number | null;
};

export type GateOutput = { stdout: string; stderr: string; truncated: boolean };

export type GateRunner = (
	gate: Gate,
	cwd: string,
	signal: AbortSignal,
	onOutput?: (output: GateOutput) => void,
	onProcess?: (pid: number) => void,
) => Promise<GateResult>;

export const MAX_GATES = 32;
/** Per-stream capture limit; the tail is kept because failures usually summarize last. */
export const CAPTURE_LIMIT = 65_536;
const KILL_GRACE_MS = 2_000;
const GATE_KEYS = new Set(["name", "command", "args", "env", "cwd"]);

function text(value: unknown, field: string, max: number): string {
	if (typeof value !== "string" || !value.trim() || value.length > max)
		throw new Error(
			`${field} must be a non-empty string of at most ${max} characters`,
		);
	return value;
}

/** Validate a gate list from parsed JSON or a JSON string. */
export function parseGates(raw: unknown): Gate[] {
	const value = typeof raw === "string" ? JSON.parse(raw) : raw;
	if (!Array.isArray(value) || value.length === 0 || value.length > MAX_GATES)
		throw new Error(`Gates must be a JSON array of 1 to ${MAX_GATES} gates`);
	return value.map((item, index): Gate => {
		const at = `Gate ${index + 1}`;
		if (!item || typeof item !== "object" || Array.isArray(item))
			throw new Error(`${at} must be an object`);
		for (const key of Object.keys(item))
			if (!GATE_KEYS.has(key))
				throw new Error(`${at} has unknown field ${key}`);
		const gate: Gate = { command: text(item.command, `${at} command`, 4096) };
		if (item.name !== undefined) gate.name = text(item.name, `${at} name`, 80);
		if (item.args !== undefined) {
			if (
				!Array.isArray(item.args) ||
				item.args.length > 256 ||
				!item.args.every(
					(arg: unknown) => typeof arg === "string" && arg.length <= 16_384,
				)
			)
				throw new Error(`${at} args must be at most 256 strings`);
			gate.args = [...item.args];
		}
		if (item.env !== undefined) {
			const entries =
				item.env && typeof item.env === "object" && !Array.isArray(item.env)
					? Object.entries(item.env)
					: undefined;
			if (
				!entries ||
				entries.length > 64 ||
				!entries.every(([, v]) => typeof v === "string" && v.length <= 16_384)
			)
				throw new Error(`${at} env must map at most 64 names to strings`);
			gate.env = Object.fromEntries(entries) as Record<string, string>;
		}
		if (item.cwd !== undefined) gate.cwd = text(item.cwd, `${at} cwd`, 4096);
		return gate;
	});
}

export function errorMessage(cause: unknown): string {
	return cause instanceof Error ? cause.message : String(cause);
}

export function gateLabel(gate: Gate): string {
	return gate.name ?? basename(gate.command);
}

/** Keep the newest CAPTURE_LIMIT bytes of a stream without unbounded buffering. */
function tailCapture() {
	let chunks: Buffer[] = [];
	let size = 0;
	let dropped = false;
	return {
		push(chunk: Buffer) {
			chunks.push(chunk);
			size += chunk.length;
			if (size <= CAPTURE_LIMIT * 2) return;
			const joined = Buffer.concat(chunks).subarray(size - CAPTURE_LIMIT);
			chunks = [joined];
			size = joined.length;
			dropped = true;
		},
		done() {
			const all = Buffer.concat(chunks);
			const kept =
				all.length > CAPTURE_LIMIT
					? all.subarray(all.length - CAPTURE_LIMIT)
					: all;
			return {
				text: kept.toString("utf8"),
				truncated: dropped || all.length > CAPTURE_LIMIT,
			};
		},
	};
}

function killTree(pid: number | undefined, force: boolean) {
	if (pid === undefined) return;
	try {
		if (process.platform === "win32")
			spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
				stdio: "ignore",
				windowsHide: true,
			}).on("error", () => {});
		else process.kill(-pid, force ? "SIGKILL" : "SIGTERM");
	} catch {
		/* The process group already exited. */
	}
}

/** Run one gate; exit code is the only success signal and output is diagnostic. */
export const runGate: GateRunner = (gate, cwd, signal, onOutput, onProcess) =>
	new Promise((done) => {
		const startedAt = Date.now();
		const stdout = tailCapture();
		const stderr = tailCapture();
		let spawnError: string | null = null;
		let grace: ReturnType<typeof setTimeout> | undefined;
		let abort = () => {};
		let lastOutput = 0;
		let trailing: ReturnType<typeof setTimeout> | undefined;
		const output = () => {
			if (!onOutput) return;
			if (Date.now() - lastOutput < 100) {
				trailing ??= setTimeout(() => {
					trailing = undefined;
					output();
				}, 100);
				return;
			}
			clearTimeout(trailing);
			trailing = undefined;
			lastOutput = Date.now();
			const out = stdout.done();
			const err = stderr.done();
			onOutput({
				stdout: out.text.slice(-4096),
				stderr: err.text.slice(-4096),
				truncated:
					out.truncated ||
					err.truncated ||
					out.text.length > 4096 ||
					err.text.length > 4096,
			});
		};
		const finish = (exitCode: number | null, error: string | null) => {
			clearTimeout(grace);
			clearTimeout(trailing);
			signal.removeEventListener("abort", abort);
			const out = stdout.done();
			const err = stderr.done();
			done({
				exitCode,
				stdout: out.text,
				stderr: err.text,
				truncated: out.truncated || err.truncated,
				error,
				startedAt,
				endedAt: Date.now(),
			});
		};
		if (signal.aborted) return finish(null, "Gate cancelled before start");
		const child = spawn(gate.command, gate.args ?? [], {
			cwd: resolve(cwd, gate.cwd ?? "."),
			env: { ...process.env, ...gate.env },
			stdio: ["ignore", "pipe", "pipe"],
			windowsHide: true,
			// A process group lets cancellation reach grandchildren on POSIX.
			detached: process.platform !== "win32",
		});
		abort = () => {
			killTree(child.pid, false);
			grace = setTimeout(() => killTree(child.pid, true), KILL_GRACE_MS);
			grace.unref();
		};
		signal.addEventListener("abort", abort, { once: true });
		child.stdout.on("data", (chunk: Buffer) => {
			stdout.push(chunk);
			output();
		});
		child.stderr.on("data", (chunk: Buffer) => {
			stderr.push(chunk);
			output();
		});
		child.once("error", (error) => {
			spawnError = error.message.slice(0, 2048);
		});
		if (child.pid !== undefined) {
			try {
				onProcess?.(child.pid);
			} catch (error) {
				spawnError = errorMessage(error);
				abort();
			}
		}
		child.once("close", (code, killed) => {
			if (signal.aborted)
				return finish(code, "Gate cancelled; result not accepted");
			if (spawnError) return finish(null, spawnError);
			finish(
				code,
				code === null ? `Gate terminated by ${killed ?? "signal"}` : null,
			);
		});
	});

/** One attempt: run gates in order and stop at the first failure. */
export async function runGatePass(
	gates: Gate[],
	cwd: string,
	signal: AbortSignal,
	runner: GateRunner = runGate,
	onResult?: (index: number, result: GateResult) => void,
	onStart?: (index: number) => void,
	onOutput?: (output: GateOutput) => void,
	onProcess?: (pid: number) => void,
): Promise<Omit<GatePass, "attempt">> {
	const results: GateResult[] = [];
	for (const [index, gate] of gates.entries()) {
		let result: GateResult;
		try {
			onStart?.(index);
			result = await runner(gate, cwd, signal, onOutput, onProcess);
		} catch (cause) {
			const now = Date.now();
			result = {
				exitCode: null,
				stdout: "",
				stderr: "",
				truncated: false,
				error: errorMessage(cause).slice(0, 2048),
				startedAt: now,
				endedAt: now,
			};
		}
		results.push(result);
		onResult?.(index, result);
		if (result.exitCode !== 0 || result.error !== null || signal.aborted)
			return { results, failedIndex: index };
	}
	return { results, failedIndex: null };
}