/ src / utils / cleanupRegistry.ts
cleanupRegistry.ts
 1  /**
 2   * Global registry for cleanup functions that should run during graceful shutdown.
 3   * This module is separate from gracefulShutdown.ts to avoid circular dependencies.
 4   */
 5  
 6  // Global registry for cleanup functions
 7  const cleanupFunctions = new Set<() => Promise<void>>()
 8  
 9  /**
10   * Register a cleanup function to run during graceful shutdown.
11   * @param cleanupFn - Function to run during cleanup (can be sync or async)
12   * @returns Unregister function that removes the cleanup handler
13   */
14  export function registerCleanup(cleanupFn: () => Promise<void>): () => void {
15    cleanupFunctions.add(cleanupFn)
16    return () => cleanupFunctions.delete(cleanupFn) // Return unregister function
17  }
18  
19  /**
20   * Run all registered cleanup functions.
21   * Used internally by gracefulShutdown.
22   */
23  export async function runCleanupFunctions(): Promise<void> {
24    await Promise.all(Array.from(cleanupFunctions).map(fn => fn()))
25  }