import { execFile } from "node:child_process"; import { open } from "node:fs/promises"; import net from "node:net"; import { promisify } from "node:util"; import type { HealthCheck } from "@devfn/config"; import { ProcessError } from "./types.js"; const execFileAsync = promisify(execFile); const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export type ReadinessInput = { health?: HealthCheck; ports: Record; logPath: string; logOffset?: number; cwd: string; environment: NodeJS.ProcessEnv; isAlive: () => boolean | Promise; readLog?: () => Promise; previouslyReady?: boolean }; const LOG_CHUNK_BYTES = 256 * 1024; const LOG_WINDOW_BYTES = 1024 * 1024; async function withinDeadline(promise: Promise, remainingMs: number): Promise { if (remainingMs <= 0) throw new Error("Readiness deadline elapsed."); let timer: NodeJS.Timeout | undefined; try { return await Promise.race([ promise, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error("Readiness operation exceeded the remaining deadline.")), remainingMs); }), ]); } finally { if (timer) clearTimeout(timer); } } async function tcpReady(port: number, timeoutMs = 500): Promise { return await new Promise((resolve) => { const socket = net.createConnection({ host: "127.0.0.1", port }); socket.setTimeout(timeoutMs); const done = (value: boolean) => { socket.destroy(); resolve(value); }; socket.once("connect", () => done(true)); socket.once("timeout", () => done(false)); socket.once("error", () => done(false)); }); } async function readNewLog(logPath: string, offset: number): Promise<{ bytes: Buffer; nextOffset: number; reset: boolean }> { const handle = await open(logPath, "r").catch(() => undefined); if (!handle) return { bytes: Buffer.alloc(0), nextOffset: offset, reset: false }; try { const size = (await handle.stat()).size; if (size <= offset) return { bytes: Buffer.alloc(0), nextOffset: Math.min(size, offset), reset: size < offset }; const length = Math.min(size - offset, LOG_CHUNK_BYTES); const buffer = Buffer.alloc(length); const { bytesRead } = await handle.read(buffer, 0, length, offset); return { bytes: buffer.subarray(0, bytesRead), nextOffset: offset + bytesRead, reset: false }; } finally { await handle.close(); } } async function readLogWindow(logPath: string): Promise { const handle = await open(logPath, "r").catch(() => undefined); if (!handle) return ""; try { const size = (await handle.stat()).size; const length = Math.min(size, LOG_WINDOW_BYTES); const buffer = Buffer.alloc(length); const { bytesRead } = await handle.read(buffer, 0, length, size - length); return new TextDecoder().decode(buffer.subarray(0, bytesRead)); } finally { await handle.close(); } } function appendHttpHealthPath(url: string, healthPath: string): string { const parsed = new URL(url); const baseSearch = parsed.search; const baseHash = parsed.hash; parsed.search = ""; parsed.hash = ""; parsed.pathname = `${parsed.pathname.replace(/\/$/, "")}/`; const appended = new URL(healthPath.replace(/^\/+/, ""), parsed); if (appended.origin !== parsed.origin) throw new Error("HTTP readiness path must stay on the configured URL origin."); if (appended.username || appended.password) throw new Error("HTTP readiness URL credentials must use the secret channel."); if (!appended.search) appended.search = baseSearch; if (!appended.hash) appended.hash = baseHash; return appended.toString(); } function leasedHttpHealthUrl(url: string, healthPath: string | undefined, port: number): string { const source = url ? new URL(url) : undefined; const protocol = source?.protocol ?? "http:"; const suffix = source ? `${source.pathname}${source.search}${source.hash}` : healthPath ?? "/"; return `${protocol}//127.0.0.1:${port}${suffix}`; } /** Resolve the endpoint used by startup and later readiness probes. */ export function resolveHttpReadinessUrl(health: Extract, ports: Readonly>): string { const port = health.port ? ports[health.port] : undefined; const configured = health.url ? new URL(health.url) : undefined; if (configured && configured.protocol !== "http:" && configured.protocol !== "https:") throw new Error("HTTP readiness URL must use http or https."); if (configured && (configured.username || configured.password)) throw new Error("HTTP readiness URL credentials must use the secret channel."); let url = health.url ?? ""; if (health.url && health.path) url = appendHttpHealthPath(url, health.path); // Validate an absolute path against the configured origin first. The direct // lease replaces the origin only after that relationship is established. if (port !== undefined) url = leasedHttpHealthUrl(url, health.path, port); const parsed = new URL(url); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("HTTP readiness URL must use http or https."); return parsed.toString(); } async function httpReady(health: Extract, input: ReadinessInput, timeoutMs: number): Promise { const url = resolveHttpReadinessUrl(health, input.ports); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { return (await fetch(url, { signal: controller.signal })).status === (health.expectedStatus ?? 200); } finally { clearTimeout(timer); } } export async function checkReadinessNow(input: ReadinessInput): Promise { const defaultTimeoutMs = input.health?.type === "tcp" ? 500 : input.health?.type === "command" ? 2000 : 1000; const timeoutMs = Math.max(1, input.health?.timeoutMs ?? defaultTimeoutMs); const deadline = Date.now() + timeoutMs; try { if (!await withinDeadline(Promise.resolve(input.isAlive()), deadline - Date.now())) return false; if (!input.health) return true; if ((input.health.type === "tcp" || input.health.type === "http") && input.health.port && input.ports[input.health.port] === undefined) return false; let ready: boolean; if (input.health.type === "log") { if (input.previouslyReady) ready = true; else { const output = input.readLog ? await withinDeadline(input.readLog(), deadline - Date.now()) : await withinDeadline(readLogWindow(input.logPath), deadline - Date.now()); ready = new RegExp(input.health.pattern, "i").test(output.slice(-LOG_WINDOW_BYTES)); } } else ready = await withinDeadline(checkReadiness(input.health, input, deadline - Date.now()), deadline - Date.now()); if (!ready || Date.now() >= deadline) return false; return await withinDeadline(Promise.resolve(input.isAlive()), deadline - Date.now()); } catch { return false; } } async function checkReadiness(health: Exclude, input: ReadinessInput, remainingMs: number): Promise { switch (health.type) { case "tcp": return await tcpReady(input.ports[health.port], Math.max(1, Math.min(health.timeoutMs ?? 500, remainingMs))); case "http": return await httpReady(health, input, Math.max(1, Math.min(health.timeoutMs ?? 1000, remainingMs))); case "command": { const [file, ...args] = health.command; await execFileAsync(file, args, { cwd: input.cwd, env: input.environment, timeout: Math.max(1, Math.min(health.timeoutMs ?? 2000, remainingMs)) }); return true; } } } export async function waitForReadiness(input: ReadinessInput): Promise { if (!input.health) { await delay(500); if (!await withinDeadline(Promise.resolve(input.isAlive()), 1000)) throw new ProcessError("DEVFN_PROCESS_START_FAILED", "Process exited before startup completed."); return; } const timeoutMs = input.health.timeoutMs ?? 120_000; const deadline = Date.now() + timeoutMs; let lastError: unknown; let logPattern: RegExp | undefined; let logOffset = input.logOffset ?? 0; let logWindow = ""; let logDecoder = new TextDecoder(); if (input.health.type === "log") { try { logPattern = new RegExp(input.health.pattern, "i"); } catch (error) { throw new ProcessError("DEVFN_PROCESS_NOT_READY", `Invalid readiness pattern ${input.health.pattern}.`, { cause: String(error) }); } } if ((input.health.type === "tcp" || input.health.type === "http") && input.health.port && input.ports[input.health.port] === undefined) { throw new ProcessError("DEVFN_PROCESS_NOT_READY", `Readiness check references unallocated port ${input.health.port}.`); } if (input.health.type === "http") { try { resolveHttpReadinessUrl(input.health, input.ports); } catch (error) { throw new ProcessError("DEVFN_PROCESS_NOT_READY", "Invalid HTTP readiness configuration.", { cause: error instanceof Error ? error.message : String(error) }); } } while (Date.now() < deadline) { try { if (!await withinDeadline(Promise.resolve(input.isAlive()), deadline - Date.now())) throw new ProcessError("DEVFN_PROCESS_START_FAILED", "Process exited while waiting for readiness."); } catch (error) { if (error instanceof ProcessError) throw error; lastError = error; break; } if (Date.now() >= deadline) break; try { if (input.health.type === "log") { if (input.readLog) logWindow = (await withinDeadline(input.readLog(), deadline - Date.now())).slice(-LOG_WINDOW_BYTES); else { const chunk = await readNewLog(input.logPath, logOffset); logOffset = chunk.nextOffset; if (chunk.reset) { logDecoder = new TextDecoder(); logWindow = ""; } logWindow = `${logWindow}${logDecoder.decode(chunk.bytes, { stream: true })}`.slice(-LOG_WINDOW_BYTES); } if (logPattern?.test(logWindow) && Date.now() < deadline) return; } else if (await checkReadiness(input.health, input, Math.max(1, deadline - Date.now())) && Date.now() < deadline) return; } catch (error) { lastError = error; } await delay(Math.min(100, Math.max(1, deadline - Date.now()))); } throw new ProcessError("DEVFN_PROCESS_NOT_READY", `Readiness check timed out after ${timeoutMs} ms.`, { cause: lastError instanceof Error ? lastError.message : String(lastError ?? "not ready") }); }