autosnippet
Version:
Extract code patterns into a knowledge base for AI coding assistants
63 lines (62 loc) • 2.15 kB
TypeScript
/**
* shutdown.ts — 统一 Graceful Shutdown 协调器
*
* 所有入口(mcp-server / api-server / cli)共用同一个 shutdown 协调器,
* 避免各入口重复编写 signal handler 并确保:
* 1. 防重入 — 多次信号只执行一轮 shutdown
* 2. 倒序执行 — 后注册的 hook 先关闭(类似栈 LIFO)
* 3. 强制超时 — 超过 TIMEOUT 强杀进程(默认 10 秒)
* 4. WAL checkpoint — DB 关闭前刷盘
* 5. hook 隔离 — 单个 hook 失败不阻断后续 hook 执行
*
* @module shared/shutdown
*
* @example
* import { shutdown } from '#shared/shutdown.js';
*
* shutdown.install();
* shutdown.register(() => db.close());
* shutdown.register(async () => await server.drain());
*/
/** Async or sync cleanup function */
type ShutdownHook = () => Promise<void> | void;
declare class ShutdownCoordinator {
#private;
/**
* Register a shutdown hook.
*
* Hooks execute in **reverse** registration order (LIFO):
* last registered = first executed.
*
* @param fn Cleanup function (sync or async)
* @param label Human-readable label for logging (e.g. 'database', 'http-server')
*/
register(fn: ShutdownHook, label?: string): void;
/**
* Set the forced-exit timeout.
* @default 10_000 (10 seconds)
*/
setTimeout(ms: number): void;
/**
* Execute all registered hooks in reverse order, then exit.
* Safe to call multiple times — only the first invocation runs.
*
* @param signal The signal or reason string (for logging)
*/
execute(signal: string): Promise<void>;
/**
* Install SIGTERM + SIGINT handlers on the current process.
* Call this once, early in the entry's lifecycle.
*/
install(): void;
/** Whether a shutdown is currently in progress */
get isShuttingDown(): boolean;
/** Number of registered hooks (for testing / diagnostics) */
get hookCount(): number;
}
/**
* Singleton shutdown coordinator.
* Import and use across all entry points and modules.
*/
export declare const shutdown: ShutdownCoordinator;
export {};