import { describe, expect, it, vi } from "vitest"; import { coordinateHeartbeatSchedulerShutdown } from "./shutdown.js"; describe("coordinateHeartbeatSchedulerShutdown", () => { it("captures a hot-restart snapshot without waiting for active scheduler work", async () => { let snapshotCaptured = false; const waitForHeartbeatSchedulerIdle = vi.fn(() => new Promise(() => undefined)); const result = await coordinateHeartbeatSchedulerShutdown({ signal: "SIGTERM", prepareHotRestartShutdown: vi.fn(async () => { snapshotCaptured = true; return { mode: "prepared" as const, skipDrain: true }; }), waitForHeartbeatSchedulerIdle, }); expect(snapshotCaptured).toBe(true); expect(waitForHeartbeatSchedulerIdle).not.toHaveBeenCalled(); expect(result).toEqual({ hotRestart: { mode: "prepared", skipDrain: true }, preparationError: null, waitedForSchedulerIdle: false, }); }); it("preserves the scheduler idle wait for normal graceful shutdown", async () => { let releaseScheduler!: () => void; const schedulerIdle = new Promise((resolve) => { releaseScheduler = resolve; }); const waitForHeartbeatSchedulerIdle = vi.fn(() => schedulerIdle); let settled = false; const shutdown = coordinateHeartbeatSchedulerShutdown({ signal: "SIGTERM", prepareHotRestartShutdown: vi.fn(async () => ({ mode: "not_requested" as const, skipDrain: false, })), waitForHeartbeatSchedulerIdle, }).finally(() => { settled = true; }); await vi.waitFor(() => expect(waitForHeartbeatSchedulerIdle).toHaveBeenCalledOnce()); expect(settled).toBe(false); releaseScheduler(); await expect(shutdown).resolves.toEqual({ hotRestart: { mode: "not_requested", skipDrain: false }, preparationError: null, waitedForSchedulerIdle: true, }); }); it("waits for scheduler idle when hot-restart preparation is unavailable", async () => { const waitForHeartbeatSchedulerIdle = vi.fn(async () => undefined); const result = await coordinateHeartbeatSchedulerShutdown({ signal: "SIGTERM", prepareHotRestartShutdown: null, waitForHeartbeatSchedulerIdle, }); expect(waitForHeartbeatSchedulerIdle).toHaveBeenCalledOnce(); expect(result).toEqual({ hotRestart: null, preparationError: null, waitedForSchedulerIdle: true, }); }); it("falls back to the scheduler idle wait when hot-restart preparation fails", async () => { const preparationError = new Error("snapshot failed"); const waitForHeartbeatSchedulerIdle = vi.fn(async () => undefined); const result = await coordinateHeartbeatSchedulerShutdown({ signal: "SIGTERM", prepareHotRestartShutdown: vi.fn(async () => { throw preparationError; }), waitForHeartbeatSchedulerIdle, }); expect(waitForHeartbeatSchedulerIdle).toHaveBeenCalledOnce(); expect(result).toEqual({ hotRestart: null, preparationError, waitedForSchedulerIdle: true, }); }); });