|
| 1 | +/** |
| 2 | + * 优雅退出管理器 |
| 3 | + * |
| 4 | + * 负责: |
| 5 | + * 1. 全局崩溃捕获 (uncaughtException/unhandledRejection) |
| 6 | + * 2. 信号处理 (SIGINT/SIGTERM) |
| 7 | + * 3. 资源清理和会话保存 |
| 8 | + */ |
| 9 | + |
| 10 | +import { createLogger, LogCategory } from '../logging/Logger.js'; |
| 11 | + |
| 12 | +const logger = createLogger(LogCategory.SERVICE); |
| 13 | + |
| 14 | +/** 清理函数类型 */ |
| 15 | +type CleanupHandler = () => void | Promise<void>; |
| 16 | + |
| 17 | +/** 退出原因 */ |
| 18 | +type ExitReason = |
| 19 | + | 'uncaughtException' |
| 20 | + | 'unhandledRejection' |
| 21 | + | 'SIGINT' |
| 22 | + | 'SIGTERM' |
| 23 | + | 'normal'; |
| 24 | + |
| 25 | +/** |
| 26 | + * 优雅退出管理器 |
| 27 | + * 单例模式,确保全局只有一个实例处理退出逻辑 |
| 28 | + */ |
| 29 | +class GracefulShutdownManager { |
| 30 | + private static instance: GracefulShutdownManager | null = null; |
| 31 | + |
| 32 | + private cleanupHandlers: CleanupHandler[] = []; |
| 33 | + private isShuttingDown = false; |
| 34 | + private initialized = false; |
| 35 | + |
| 36 | + private constructor() {} |
| 37 | + |
| 38 | + static getInstance(): GracefulShutdownManager { |
| 39 | + if (!GracefulShutdownManager.instance) { |
| 40 | + GracefulShutdownManager.instance = new GracefulShutdownManager(); |
| 41 | + } |
| 42 | + return GracefulShutdownManager.instance; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * 初始化全局错误处理器 |
| 47 | + * 应该在应用启动时调用一次 |
| 48 | + */ |
| 49 | + initialize(): void { |
| 50 | + if (this.initialized) { |
| 51 | + logger.debug('[GracefulShutdown] 已初始化,跳过重复初始化'); |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + // 捕获未处理的异常 |
| 56 | + process.on('uncaughtException', (error: Error) => { |
| 57 | + this.handleFatalError('uncaughtException', error); |
| 58 | + }); |
| 59 | + |
| 60 | + // 捕获未处理的 Promise 拒绝 |
| 61 | + process.on('unhandledRejection', (reason: unknown) => { |
| 62 | + const error = reason instanceof Error ? reason : new Error(String(reason)); |
| 63 | + this.handleFatalError('unhandledRejection', error); |
| 64 | + }); |
| 65 | + |
| 66 | + // 处理 SIGTERM(通常由进程管理器发送,如 Docker、PM2) |
| 67 | + process.on('SIGTERM', () => { |
| 68 | + logger.info('[GracefulShutdown] 收到 SIGTERM 信号'); |
| 69 | + this.shutdown('SIGTERM', 0); |
| 70 | + }); |
| 71 | + |
| 72 | + // 注意:SIGINT 由 useCtrlCHandler 处理,这里不重复处理 |
| 73 | + // 但如果是非 UI 模式(如 print 模式),需要处理 SIGINT |
| 74 | + if (process.env.BLADE_NON_INTERACTIVE === 'true') { |
| 75 | + process.on('SIGINT', () => { |
| 76 | + logger.info('[GracefulShutdown] 收到 SIGINT 信号(非交互模式)'); |
| 77 | + this.shutdown('SIGINT', 0); |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + this.initialized = true; |
| 82 | + logger.debug('[GracefulShutdown] 全局错误处理器已初始化'); |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * 注册清理函数 |
| 87 | + * 在退出时按注册的逆序执行(后注册的先执行) |
| 88 | + */ |
| 89 | + registerCleanup(handler: CleanupHandler): () => void { |
| 90 | + this.cleanupHandlers.push(handler); |
| 91 | + logger.debug( |
| 92 | + `[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个` |
| 93 | + ); |
| 94 | + |
| 95 | + // 返回取消注册的函数 |
| 96 | + return () => { |
| 97 | + const index = this.cleanupHandlers.indexOf(handler); |
| 98 | + if (index !== -1) { |
| 99 | + this.cleanupHandlers.splice(index, 1); |
| 100 | + logger.debug( |
| 101 | + `[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个` |
| 102 | + ); |
| 103 | + } |
| 104 | + }; |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * 处理致命错误 |
| 109 | + */ |
| 110 | + private handleFatalError(type: ExitReason, error: Error): void { |
| 111 | + // 防止递归错误 |
| 112 | + if (this.isShuttingDown) { |
| 113 | + console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${type}):`, error); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + console.error(''); |
| 118 | + console.error('═'.repeat(60)); |
| 119 | + console.error(`💥 发生未捕获的错误 (${type})`); |
| 120 | + console.error('═'.repeat(60)); |
| 121 | + console.error(''); |
| 122 | + console.error('错误信息:', error.message); |
| 123 | + console.error(''); |
| 124 | + if (error.stack) { |
| 125 | + console.error('堆栈跟踪:'); |
| 126 | + console.error(error.stack); |
| 127 | + } |
| 128 | + console.error(''); |
| 129 | + console.error('═'.repeat(60)); |
| 130 | + console.error(''); |
| 131 | + |
| 132 | + // 执行清理并退出 |
| 133 | + this.shutdown(type, 1); |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * 执行优雅退出 |
| 138 | + */ |
| 139 | + async shutdown(reason: ExitReason, exitCode: number = 0): Promise<void> { |
| 140 | + if (this.isShuttingDown) { |
| 141 | + logger.debug('[GracefulShutdown] 已在退出过程中,跳过重复退出'); |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + this.isShuttingDown = true; |
| 146 | + |
| 147 | + logger.info(`[GracefulShutdown] 开始优雅退出 (原因: ${reason})`); |
| 148 | + |
| 149 | + // 设置超时保护,防止清理函数卡住 |
| 150 | + const timeoutMs = 5000; |
| 151 | + const timeoutPromise = new Promise<void>((_, reject) => { |
| 152 | + setTimeout(() => { |
| 153 | + reject(new Error(`清理超时 (${timeoutMs}ms)`)); |
| 154 | + }, timeoutMs); |
| 155 | + }); |
| 156 | + |
| 157 | + try { |
| 158 | + // 按逆序执行清理函数(后注册的先执行) |
| 159 | + const cleanupPromise = this.runCleanupHandlers(); |
| 160 | + |
| 161 | + await Promise.race([cleanupPromise, timeoutPromise]); |
| 162 | + |
| 163 | + logger.info('[GracefulShutdown] 所有清理函数执行完成'); |
| 164 | + } catch (error) { |
| 165 | + console.error('[GracefulShutdown] 清理过程中发生错误:', error); |
| 166 | + } finally { |
| 167 | + // 给 Ink 一点时间完成终端清理 |
| 168 | + setTimeout(() => { |
| 169 | + process.exit(exitCode); |
| 170 | + }, 100); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * 执行所有清理函数 |
| 176 | + */ |
| 177 | + private async runCleanupHandlers(): Promise<void> { |
| 178 | + // 逆序执行 |
| 179 | + const handlers = [...this.cleanupHandlers].reverse(); |
| 180 | + |
| 181 | + for (const handler of handlers) { |
| 182 | + try { |
| 183 | + const result = handler(); |
| 184 | + if (result instanceof Promise) { |
| 185 | + await result; |
| 186 | + } |
| 187 | + } catch (error) { |
| 188 | + console.error('[GracefulShutdown] 清理函数执行失败:', error); |
| 189 | + // 继续执行其他清理函数 |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + /** |
| 195 | + * 检查是否正在退出 |
| 196 | + */ |
| 197 | + isExiting(): boolean { |
| 198 | + return this.isShuttingDown; |
| 199 | + } |
| 200 | + |
| 201 | + /** |
| 202 | + * 重置状态(仅用于测试) |
| 203 | + */ |
| 204 | + reset(): void { |
| 205 | + this.isShuttingDown = false; |
| 206 | + this.cleanupHandlers = []; |
| 207 | + this.initialized = false; |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +// 导出单例获取函数 |
| 212 | +export const getGracefulShutdown = (): GracefulShutdownManager => { |
| 213 | + return GracefulShutdownManager.getInstance(); |
| 214 | +}; |
| 215 | + |
| 216 | +// 导出便捷函数 |
| 217 | +export const registerCleanup = (handler: CleanupHandler): (() => void) => { |
| 218 | + return getGracefulShutdown().registerCleanup(handler); |
| 219 | +}; |
| 220 | + |
| 221 | +export const initializeGracefulShutdown = (): void => { |
| 222 | + getGracefulShutdown().initialize(); |
| 223 | +}; |
| 224 | + |
| 225 | +export const isExiting = (): boolean => { |
| 226 | + return getGracefulShutdown().isExiting(); |
| 227 | +}; |
0 commit comments