import { test, expect } from "vitest"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { MaintenanceBarrier } from "../src/runtime/maintenance-gate.js"; test("activation waits for an in-flight admission lease and rejects later admissions", async () => { const gate = new MaintenanceBarrier(); const release = gate.acquire(); expect(release).toBeTypeOf("function"); let acknowledged = false; const activation = gate.activate().then(() => { acknowledged = true; }); await Promise.resolve(); expect(acknowledged).toBe(false); expect(gate.acquire()).toBeUndefined(); release?.(); await activation; expect(acknowledged).toBe(true); expect(gate.status()).toEqual({ active: true, admissions: 0 }); gate.deactivate(); expect(gate.acquire()).toBeTypeOf("function"); }); test("durable activation survives recreation and deactivation removes the marker first", async () => { const directory = mkdtempSync(join(tmpdir(), "tht-maintenance-gate-")); const marker = join(directory, "maintenance.json"); try { const first = new MaintenanceBarrier(marker); const release = first.acquire(); expect(release).toBeTypeOf("function"); const activation = first.activate(); expect(existsSync(marker)).toBe(true); expect(first.acquire()).toBeUndefined(); expect(first.status()).toEqual({ active: true, admissions: 1 }); release?.(); await activation; expect(first.status()).toEqual({ active: true, admissions: 0 }); const recreated = new MaintenanceBarrier(marker); expect(recreated.status()).toEqual({ active: true, admissions: 0 }); recreated.deactivate(); expect(existsSync(marker)).toBe(false); expect(recreated.status()).toEqual({ active: false, admissions: 0 }); } finally { rmSync(directory, { recursive: true, force: true }); } });