import { addAbortListener } from "node:events"; const MAX_ACTIVE = 2; const MAX_QUEUED = 16; const MAX_WAIT_MS = 7_500; let active = 0; const waiting = new Set<() => boolean>(); function acquire(signal?: AbortSignal): boolean | Promise { if (signal?.aborted) return false; if (active < MAX_ACTIVE) { active++; return true; } if (waiting.size >= MAX_QUEUED) return false; return new Promise((resolve) => { const deadline = performance.now() + MAX_WAIT_MS; const finish = (admitted: boolean) => { waiting.delete(admit); clearTimeout(timer); subscription?.[Symbol.dispose](); resolve(admitted); }; const admit = () => { const valid = !signal?.aborted && performance.now() < deadline; finish(valid); return valid; }; const timer = setTimeout(() => finish(false), MAX_WAIT_MS); const subscription = signal ? addAbortListener(signal, () => finish(false)) : undefined; waiting.add(admit); }); } function release(): void { for (const admit of waiting) { if (admit()) return; // Transfer the occupied slot to the oldest waiter. } active--; } /** Admit a fresh macOS Core ancestry read, not a previous ownership result. */ export async function withCoreInspectionSlot( inspect: () => Promise, signal?: AbortSignal, ): Promise { const admitted = acquire(signal); if (!(typeof admitted === "boolean" ? admitted : await admitted)) return; try { if (!signal?.aborted) return await inspect(); } finally { release(); } }