moved folders around
This commit is contained in:
parent
4f89affc2b
commit
36cb84b343
202 changed files with 1160 additions and 660 deletions
109
libs/services/shutdown/src/index.ts
Normal file
109
libs/services/shutdown/src/index.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { Shutdown } from './shutdown';
|
||||
import type { ShutdownResult } from './types';
|
||||
|
||||
/**
|
||||
* @stock-bot/shutdown - Shutdown management library
|
||||
*
|
||||
* Main exports for the shutdown library
|
||||
*/
|
||||
|
||||
// Core shutdown classes and types
|
||||
export { Shutdown } from './shutdown';
|
||||
export type { ShutdownCallback, ShutdownOptions, ShutdownResult, PrioritizedShutdownCallback } from './types';
|
||||
|
||||
// Global singleton instance
|
||||
let globalInstance: Shutdown | null = null;
|
||||
|
||||
/**
|
||||
* Get the global shutdown instance (creates one if it doesn't exist)
|
||||
*/
|
||||
function getGlobalInstance(): Shutdown {
|
||||
if (!globalInstance) {
|
||||
globalInstance = Shutdown.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, priority?: number, name?: string): void {
|
||||
getGlobalInstance().onShutdown(callback, priority, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a high priority shutdown callback (for queues, critical services)
|
||||
*/
|
||||
export function onShutdownHigh(callback: () => Promise<void> | void, name?: string): void {
|
||||
getGlobalInstance().onShutdownHigh(callback, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a medium priority shutdown callback (for databases, connections)
|
||||
*/
|
||||
export function onShutdownMedium(callback: () => Promise<void> | void, name?: string): void {
|
||||
getGlobalInstance().onShutdownMedium(callback, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a low priority shutdown callback (for loggers, cleanup)
|
||||
*/
|
||||
export function onShutdownLow(callback: () => Promise<void> | void, name?: string): void {
|
||||
getGlobalInstance().onShutdownLow(callback, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the shutdown timeout in milliseconds
|
||||
*/
|
||||
export function setShutdownTimeout(timeout: number): void {
|
||||
getGlobalInstance().setTimeout(timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if shutdown is currently in progress
|
||||
*/
|
||||
export function isShuttingDown(): boolean {
|
||||
return globalInstance?.isShutdownInProgress() || false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if shutdown signal was received (for quick checks in running jobs)
|
||||
*/
|
||||
export function isShutdownSignalReceived(): boolean {
|
||||
const globalFlag = globalThis.__SHUTDOWN_SIGNAL_RECEIVED__ || false;
|
||||
const instanceFlag = globalInstance?.isShutdownSignalReceived() || false;
|
||||
return globalFlag || instanceFlag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
Shutdown.reset();
|
||||
}
|
||||
251
libs/services/shutdown/src/shutdown.ts
Normal file
251
libs/services/shutdown/src/shutdown.ts
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
/**
|
||||
* Shutdown management for Node.js applications
|
||||
*
|
||||
* Features:
|
||||
* - Automatic signal handling (SIGTERM, SIGINT, etc.)
|
||||
* - Configurable shutdown timeout
|
||||
* - Multiple cleanup callbacks with error handling
|
||||
* - Platform-specific signal support (Windows/Unix)
|
||||
*/
|
||||
|
||||
import type { PrioritizedShutdownCallback, ShutdownCallback, ShutdownOptions, ShutdownResult } from './types';
|
||||
|
||||
// Global flag that works across all processes/workers
|
||||
declare global {
|
||||
var __SHUTDOWN_SIGNAL_RECEIVED__: boolean | undefined;
|
||||
}
|
||||
|
||||
export class Shutdown {
|
||||
private static instance: Shutdown | null = null;
|
||||
private isShuttingDown = false;
|
||||
private signalReceived = false; // Track if shutdown signal was received
|
||||
private shutdownTimeout = 30000; // 30 seconds default
|
||||
private callbacks: PrioritizedShutdownCallback[] = [];
|
||||
private signalHandlersRegistered = false;
|
||||
|
||||
constructor(options: ShutdownOptions = {}) {
|
||||
this.shutdownTimeout = options.timeout || 30000;
|
||||
|
||||
if (options.autoRegister !== false) {
|
||||
this.setupSignalHandlers();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create singleton instance
|
||||
*/
|
||||
static getInstance(options?: ShutdownOptions): Shutdown {
|
||||
if (!Shutdown.instance) {
|
||||
Shutdown.instance = new Shutdown(options);
|
||||
}
|
||||
return Shutdown.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset singleton instance (mainly for testing)
|
||||
*/
|
||||
static reset(): void {
|
||||
Shutdown.instance = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a cleanup callback with priority (lower numbers = higher priority)
|
||||
*/
|
||||
onShutdown(callback: ShutdownCallback, priority: number = 50, name?: string): void {
|
||||
if (this.isShuttingDown) {
|
||||
return;
|
||||
}
|
||||
this.callbacks.push({ callback, priority, name });
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a high priority shutdown callback (for queues, critical services)
|
||||
*/
|
||||
onShutdownHigh(callback: ShutdownCallback, name?: string): void {
|
||||
this.onShutdown(callback, 10, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a medium priority shutdown callback (for databases, connections)
|
||||
*/
|
||||
onShutdownMedium(callback: ShutdownCallback, name?: string): void {
|
||||
this.onShutdown(callback, 50, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a low priority shutdown callback (for loggers, cleanup)
|
||||
*/
|
||||
onShutdownLow(callback: ShutdownCallback, name?: string): void {
|
||||
this.onShutdown(callback, 90, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set shutdown timeout in milliseconds
|
||||
*/
|
||||
setTimeout(timeout: number): void {
|
||||
if (timeout <= 0) {
|
||||
throw new Error('Shutdown timeout must be positive');
|
||||
}
|
||||
this.shutdownTimeout = timeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current shutdown state
|
||||
*/
|
||||
isShutdownInProgress(): boolean {
|
||||
return this.isShuttingDown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if shutdown signal was received (for quick checks in running jobs)
|
||||
*/
|
||||
isShutdownSignalReceived(): boolean {
|
||||
return this.signalReceived || this.isShuttingDown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of registered callbacks
|
||||
*/
|
||||
getCallbackCount(): number {
|
||||
return this.callbacks.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate graceful shutdown
|
||||
*/
|
||||
async shutdown(_signal?: string): Promise<ShutdownResult> {
|
||||
if (this.isShuttingDown) {
|
||||
return {
|
||||
success: false,
|
||||
callbacksExecuted: 0,
|
||||
callbacksFailed: 0,
|
||||
duration: 0,
|
||||
error: 'Shutdown already in progress',
|
||||
};
|
||||
}
|
||||
|
||||
this.isShuttingDown = true;
|
||||
const startTime = Date.now();
|
||||
|
||||
const shutdownPromise = this.executeCallbacks();
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error('Shutdown timeout')), this.shutdownTimeout);
|
||||
});
|
||||
|
||||
let result: ShutdownResult;
|
||||
|
||||
try {
|
||||
const callbackResult = await Promise.race([shutdownPromise, timeoutPromise]);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
result = {
|
||||
success: true,
|
||||
callbacksExecuted: callbackResult.executed,
|
||||
callbacksFailed: callbackResult.failed,
|
||||
duration,
|
||||
error: callbackResult.failed > 0 ? `${callbackResult.failed} callbacks failed` : undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime;
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
||||
result = {
|
||||
success: false,
|
||||
callbacksExecuted: 0,
|
||||
callbacksFailed: 0,
|
||||
duration,
|
||||
error: errorMessage,
|
||||
};
|
||||
}
|
||||
|
||||
// Don't call process.exit here - let the caller decide
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate shutdown and exit process
|
||||
*/
|
||||
async shutdownAndExit(signal?: string, exitCode = 0): Promise<never> {
|
||||
const result = await this.shutdown(signal);
|
||||
const finalExitCode = result.success ? exitCode : 1;
|
||||
|
||||
process.exit(finalExitCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all registered callbacks in priority order
|
||||
*/
|
||||
private async executeCallbacks(): Promise<{ executed: number; failed: number }> {
|
||||
if (this.callbacks.length === 0) {
|
||||
return { executed: 0, failed: 0 };
|
||||
}
|
||||
|
||||
// Sort callbacks by priority (lower numbers = higher priority = execute first)
|
||||
const sortedCallbacks = [...this.callbacks].sort((a, b) => a.priority - b.priority);
|
||||
|
||||
let executed = 0;
|
||||
let failed = 0;
|
||||
|
||||
// Execute callbacks in order by priority
|
||||
for (const { callback, name, priority } of sortedCallbacks) {
|
||||
try {
|
||||
await callback();
|
||||
executed++;
|
||||
} catch (error) {
|
||||
failed++;
|
||||
if (name) {
|
||||
console.error(`✗ Shutdown failed: ${name} (priority: ${priority})`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { executed, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup signal handlers for graceful shutdown
|
||||
*/
|
||||
private setupSignalHandlers(): void {
|
||||
if (this.signalHandlersRegistered) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Platform-specific signals
|
||||
const signals: NodeJS.Signals[] =
|
||||
process.platform === 'win32' ? ['SIGINT', 'SIGTERM'] : ['SIGTERM', 'SIGINT', 'SIGUSR2'];
|
||||
|
||||
signals.forEach(signal => {
|
||||
process.on(signal, () => {
|
||||
// Only process if not already shutting down
|
||||
if (!this.isShuttingDown) {
|
||||
// Set signal flag immediately for quick checks
|
||||
this.signalReceived = true;
|
||||
// Also set global flag for workers/other processes
|
||||
globalThis.__SHUTDOWN_SIGNAL_RECEIVED__ = true;
|
||||
this.shutdownAndExit(signal).catch(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Handle uncaught exceptions
|
||||
process.on('uncaughtException', () => {
|
||||
this.signalReceived = true;
|
||||
this.shutdownAndExit('uncaughtException', 1).catch(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Handle unhandled promise rejections
|
||||
process.on('unhandledRejection', () => {
|
||||
this.signalReceived = true;
|
||||
this.shutdownAndExit('unhandledRejection', 1).catch(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
this.signalHandlersRegistered = true;
|
||||
}
|
||||
}
|
||||
43
libs/services/shutdown/src/types.ts
Normal file
43
libs/services/shutdown/src/types.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/**
|
||||
* Types for shutdown functionality
|
||||
*/
|
||||
|
||||
/**
|
||||
* Callback function for shutdown cleanup
|
||||
*/
|
||||
export type ShutdownCallback = () => Promise<void> | void;
|
||||
|
||||
/**
|
||||
* Shutdown callback with priority information
|
||||
*/
|
||||
export interface PrioritizedShutdownCallback {
|
||||
callback: ShutdownCallback;
|
||||
priority: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for configuring shutdown behavior
|
||||
*/
|
||||
export interface ShutdownOptions {
|
||||
/** Timeout in milliseconds before forcing shutdown (default: 30000) */
|
||||
timeout?: number;
|
||||
/** Whether to automatically register signal handlers (default: true) */
|
||||
autoRegister?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown result information
|
||||
*/
|
||||
export interface ShutdownResult {
|
||||
/** Whether shutdown completed successfully */
|
||||
success: boolean;
|
||||
/** Number of callbacks executed */
|
||||
callbacksExecuted: number;
|
||||
/** Number of callbacks that failed */
|
||||
callbacksFailed: number;
|
||||
/** Time taken for shutdown in milliseconds */
|
||||
duration: number;
|
||||
/** Error message if shutdown failed */
|
||||
error?: string;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue