/** * Graceful Shutdown Handler for MCP Server * * Provides controlled shutdown capabilities with proper cleanup * of resources, in-flight requests, and signal handling. * * @packageDocumentation */ import type { Logger } from '../types'; /** * Shutdown state values */ export type ShutdownState = 'running' | 'shutdown_requested' | 'draining' | 'cleaning_up' | 'stopped'; /** * Shutdown reason enumeration */ export type ShutdownReason = 'signal' | 'manual' | 'error' | 'timeout' | 'health_check_failed'; /** * Cleanup task function type */ export type CleanupTask = () => Promise; /** * Cleanup task registration */ export interface CleanupTaskRegistration { /** Task name for identification */ readonly name: string; /** Cleanup function */ readonly task: CleanupTask; /** Task priority (higher = runs first) */ readonly priority?: number; /** Timeout for this specific task (ms) */ readonly timeout?: number; /** Whether failure should be fatal */ readonly critical?: boolean; } /** * Graceful shutdown configuration */ export interface GracefulShutdownConfig { /** Timeout for entire shutdown process (ms) */ readonly shutdownTimeout?: number; /** Default timeout for individual tasks (ms) */ readonly taskTimeout?: number; /** Signals to handle */ readonly signals?: readonly NodeJS.Signals[]; /** Whether to force exit on timeout */ readonly forceExitOnTimeout?: boolean; /** Drain timeout for in-flight requests (ms) */ readonly drainTimeout?: number; /** Logger instance */ readonly logger?: Logger; /** Callback before shutdown starts */ readonly onShutdownStart?: (reason: ShutdownReason) => void; /** Callback after shutdown completes */ readonly onShutdownComplete?: (success: boolean, error?: Error) => void; } /** * Shutdown result */ export interface ShutdownResult { /** Whether shutdown was successful */ readonly success: boolean; /** Shutdown reason */ readonly reason: ShutdownReason; /** Total shutdown duration (ms) */ readonly duration: number; /** Individual task results */ readonly taskResults: readonly TaskResult[]; /** Error if shutdown failed */ readonly error?: Error; } /** * Individual task result */ export interface TaskResult { /** Task name */ readonly name: string; /** Whether task succeeded */ readonly success: boolean; /** Task duration (ms) */ readonly duration: number; /** Error if task failed */ readonly error?: string; } /** * Tracks in-flight requests for graceful draining */ export declare class InFlightRequestTracker { private readonly requests; private draining; /** * Register a new in-flight request * * @param requestId - Unique request identifier * @param metadata - Optional request metadata * @returns Whether the request was registered (false if draining) */ register(requestId: string, metadata?: unknown): boolean; /** * Complete an in-flight request * * @param requestId - Request identifier to complete */ complete(requestId: string): void; /** * Get the count of in-flight requests */ getCount(): number; /** * Check if there are any in-flight requests */ hasInFlight(): boolean; /** * Start draining (reject new requests) */ startDraining(): void; /** * Check if currently draining */ isDraining(): boolean; /** * Wait for all in-flight requests to complete * * @param timeout - Maximum time to wait (ms) * @returns Whether all requests completed within timeout */ waitForDrain(timeout: number): Promise; /** * Get details of all in-flight requests */ getInFlightDetails(): Array<{ requestId: string; duration: number; metadata?: unknown; }>; /** * Reset the tracker */ reset(): void; } /** * Graceful Shutdown Handler * * Manages controlled shutdown of the MCP server with proper * resource cleanup and signal handling. * * @example * ```typescript * const shutdown = new GracefulShutdownHandler({ * shutdownTimeout: 30000, * signals: ['SIGINT', 'SIGTERM'], * }); * * shutdown.registerCleanupTask({ * name: 'close-connections', * task: async () => { * await closeAllConnections(); * }, * priority: 100, * }); * * shutdown.registerCleanupTask({ * name: 'flush-logs', * task: async () => { * await flushLogBuffers(); * }, * priority: 50, * }); * * // Start handling signals * shutdown.start(); * * // Or trigger manual shutdown * await shutdown.shutdown('manual'); * ``` */ export declare class GracefulShutdownHandler { private readonly config; private readonly cleanupTasks; private readonly requestTracker; private readonly signalHandlers; private state; private shutdownPromise; /** * Create a new Graceful Shutdown Handler * * @param config - Shutdown configuration */ constructor(config?: GracefulShutdownConfig); /** * Get the current shutdown state */ getState(): ShutdownState; /** * Get the in-flight request tracker */ getRequestTracker(): InFlightRequestTracker; /** * Check if shutdown has been initiated */ isShuttingDown(): boolean; /** * Register a cleanup task * * @param registration - Task registration */ registerCleanupTask(registration: CleanupTaskRegistration): void; /** * Unregister a cleanup task * * @param name - Task name to unregister * @returns Whether the task was unregistered */ unregisterCleanupTask(name: string): boolean; /** * Start handling shutdown signals */ start(): void; /** * Stop handling shutdown signals */ stop(): void; /** * Initiate graceful shutdown * * @param reason - Reason for shutdown * @returns Shutdown result */ shutdown(reason: ShutdownReason): Promise; /** * Force immediate shutdown * * @param exitCode - Process exit code */ forceShutdown(exitCode?: number): void; /** * Perform the shutdown sequence */ private performShutdown; /** * Run the full shutdown sequence */ private runShutdownSequence; /** * Run a single cleanup task with timeout */ private runCleanupTask; /** * Create the overall shutdown timeout */ private createShutdownTimeout; } /** * Create a graceful shutdown handler with default configuration * * @param logger - Optional logger instance * @returns Configured shutdown handler */ export declare function createGracefulShutdownHandler(logger?: Logger): GracefulShutdownHandler; //# sourceMappingURL=graceful-shutdown.d.ts.map