Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions lib/shutdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ type CleanupFn = () => void | Promise<void>;

const cleanupFunctions: CleanupFn[] = [];
let shutdownRegistered = false;
let cleanupPromise: Promise<void> | null = null;

export function registerCleanup(fn: CleanupFn): void {
cleanupFunctions.push(fn);
Expand All @@ -15,17 +16,27 @@ export function unregisterCleanup(fn: CleanupFn): void {
}
}

export async function runCleanup(): Promise<void> {
const fns = [...cleanupFunctions];
cleanupFunctions.length = 0;
export function runCleanup(): Promise<void> {
if (cleanupPromise) {
return cleanupPromise;
}

cleanupPromise = (async () => {
const fns = [...cleanupFunctions];
cleanupFunctions.length = 0;

for (const fn of fns) {
try {
await fn();
} catch {
// Ignore cleanup errors during shutdown
for (const fn of fns) {
try {
await fn();
} catch {
// Ignore cleanup errors during shutdown
}
}
}
})().finally(() => {
cleanupPromise = null;
});

return cleanupPromise;
}

function ensureShutdownHandler(): void {
Expand Down
22 changes: 21 additions & 1 deletion test/shutdown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe("Graceful shutdown", () => {
expect(fn).not.toHaveBeenCalled();
});

it("runs multiple cleanup functions in order", async () => {
it("runs multiple cleanup functions in registration order", async () => {
const order: number[] = [];
registerCleanup(() => { order.push(1); });
registerCleanup(() => { order.push(2); });
Expand Down Expand Up @@ -65,6 +65,26 @@ describe("Graceful shutdown", () => {
expect(getCleanupCount()).toBe(0);
});

it("returns the same promise for concurrent runCleanup calls", async () => {
let release!: () => void;
const blocker = new Promise<void>((resolve) => {
release = resolve;
});
const cleanupFn = vi.fn(async () => {
await blocker;
});
registerCleanup(cleanupFn);

const first = runCleanup();
const second = runCleanup();

expect(first).toBe(second);
expect(cleanupFn).toHaveBeenCalledTimes(1);

release();
await first;
});

it("unregister is no-op for non-registered function", () => {
const fn = vi.fn();
unregisterCleanup(fn);
Expand Down