stock-bot/libs/shutdown/src/index.ts

86 lines
2.1 KiB
TypeScript

/**
* @stock-bot/shutdown - Graceful shutdown management library
*
* Main exports for the shutdown library
*/
// Core shutdown classes and types
export { GracefulShutdown } from './graceful-shutdown.js';
export type { ShutdownCallback, ShutdownOptions, ShutdownResult } from './types.js';
import { GracefulShutdown } from './graceful-shutdown.js';
import type { ShutdownResult } from './types.js';
// Global singleton instance
let globalInstance: GracefulShutdown | null = null;
/**
* Get the global shutdown instance (creates one if it doesn't exist)
*/
function getGlobalInstance(): GracefulShutdown {
if (!globalInstance) {
globalInstance = GracefulShutdown.getInstance();
}
return globalInstance;
}
/**
* Convenience functions for global shutdown management
*/
/**
* Register a cleanup callback that will be executed during shutdown
*/
export function onShutdown(callback: () => Promise<void> | void): void {
getGlobalInstance().onShutdown(callback);
}
/**
* Set the shutdown timeout in milliseconds
*/
export function setShutdownTimeout(timeout: number): void {
getGlobalInstance().setTimeout(timeout);
}
/**
* Enable or disable debug logging
*/
export function setShutdownDebug(enabled: boolean): void {
getGlobalInstance().setDebug(enabled);
}
/**
* Check if shutdown is currently in progress
*/
export function isShuttingDown(): boolean {
return globalInstance?.isShutdownInProgress() || false;
}
/**
* Get the number of registered shutdown callbacks
*/
export function getShutdownCallbackCount(): number {
return globalInstance?.getCallbackCount() || 0;
}
/**
* Manually initiate graceful shutdown
*/
export function initiateShutdown(signal?: string): Promise<ShutdownResult> {
return getGlobalInstance().shutdown(signal);
}
/**
* Manually initiate graceful shutdown and exit the process
*/
export function shutdownAndExit(signal?: string, exitCode = 0): Promise<never> {
return getGlobalInstance().shutdownAndExit(signal, exitCode);
}
/**
* Reset the global instance (mainly for testing)
*/
export function resetShutdown(): void {
globalInstance = null;
GracefulShutdown.reset();
}