| 1 | import { exec } from "child_process"; |
| 2 | import * as os from "os"; |
| 3 | import { promisify } from "util"; |
| 4 | |
| 5 | import { logger } from "../util/logger.js"; |
| 6 | |
| 7 | const execAsync = promisify(exec); |
| 8 | |
| 9 | export interface ResourceUsage { |
| 10 | timestamp: number; |
| 11 | memory: { |
| 12 | rss: number; // Resident Set Size |
| 13 | heapTotal: number; |
| 14 | heapUsed: number; |
| 15 | external: number; |
| 16 | arrayBuffers: number; |
| 17 | }; |
| 18 | cpu: { |
| 19 | user: number; |
| 20 | system: number; |
| 21 | percent?: number; // CPU percentage (calculated) |
| 22 | }; |
| 23 | system: { |
| 24 | loadAverage: number[]; |
| 25 | uptime: number; |
| 26 | freeMemory: number; |
| 27 | totalMemory: number; |
| 28 | }; |
| 29 | eventLoop: { |
| 30 | lag: number; |
| 31 | }; |
| 32 | fileDescriptors?: number; |
| 33 | } |
| 34 | |
| 35 | export interface ResourceMonitoringState { |
| 36 | isMonitoring: boolean; |
| 37 | resourceHistory: ResourceUsage[]; |
| 38 | } |
| 39 | |
| 40 | class ResourceMonitoringService { |
| 41 | private isMonitoring = false; |
| 42 | private monitoringInterval?: NodeJS.Timeout; |
| 43 | private intervalMs = 1000; // Default 1 second |
| 44 | private resourceHistory: ResourceUsage[] = []; |
| 45 | private maxHistorySize = 300; // Keep 5 minutes at 1s intervals |
| 46 | private lastCpuUsage = process.cpuUsage(); |
| 47 | private lastTimestamp = Date.now(); |
| 48 | |
| 49 | async initialize(): Promise<void> { |
| 50 | // Start monitoring if verbose mode is enabled |
| 51 | if (process.argv.includes("--verbose")) { |
| 52 | this.startMonitoring(); |
| 53 | } |
| 54 | |
| 55 | // Cleanup on exit |
| 56 | process.on("exit", () => this.cleanup()); |
| 57 | process.on("SIGINT", () => this.cleanup()); |
| 58 | process.on("SIGTERM", () => this.cleanup()); |
| 59 | } |
| 60 | |
| 61 | async cleanup(): Promise<void> { |
| 62 | this.stopMonitoring(); |
| 63 | } |
| 64 | |
| 65 | public startMonitoring(intervalMs = 1000): void { |
| 66 | if (this.isMonitoring) return; |
| 67 | |
| 68 | this.intervalMs = intervalMs; |
| 69 | this.isMonitoring = true; |
| 70 | this.lastCpuUsage = process.cpuUsage(); |
| 71 | this.lastTimestamp = Date.now(); |
| 72 | |
| 73 | this.monitoringInterval = setInterval(() => { |
| 74 | this.collectResourceUsage(); |
| 75 | }, this.intervalMs); |
| 76 | |
| 77 | logger.debug("Resource monitoring started", { intervalMs }); |
| 78 | } |
| 79 | |
| 80 | public stopMonitoring(): void { |
| 81 | if (!this.isMonitoring) return; |
| 82 | |
| 83 | this.isMonitoring = false; |
| 84 | if (this.monitoringInterval) { |
| 85 | clearInterval(this.monitoringInterval); |
| 86 | this.monitoringInterval = undefined; |
| 87 | } |
| 88 | |
| 89 | logger.debug("Resource monitoring stopped"); |
| 90 | } |
| 91 | |
| 92 | public getCurrentResourceUsage(): ResourceUsage { |
| 93 | const now = Date.now(); |
| 94 | const currentCpuUsage = process.cpuUsage(); |
| 95 | const timeDiff = now - this.lastTimestamp; |
| 96 | |
| 97 | // Calculate CPU percentage |
| 98 | const userDiff = currentCpuUsage.user - this.lastCpuUsage.user; |
| 99 | const systemDiff = currentCpuUsage.system - this.lastCpuUsage.system; |
| 100 | const totalDiff = userDiff + systemDiff; |
| 101 | const cpuPercent = timeDiff > 0 ? (totalDiff / (timeDiff * 1000)) * 100 : 0; |
| 102 | |
| 103 | const memoryUsage = process.memoryUsage(); |
| 104 | |
| 105 | const usage: ResourceUsage = { |
| 106 | timestamp: now, |
| 107 | memory: { |
| 108 | rss: memoryUsage.rss, |
| 109 | heapTotal: memoryUsage.heapTotal, |
| 110 | heapUsed: memoryUsage.heapUsed, |
| 111 | external: memoryUsage.external, |
| 112 | arrayBuffers: memoryUsage.arrayBuffers, |
| 113 | }, |
| 114 | cpu: { |
| 115 | user: currentCpuUsage.user, |
| 116 | system: currentCpuUsage.system, |
| 117 | percent: Math.min(cpuPercent, 100), // Cap at 100% |
| 118 | }, |
| 119 | system: { |
| 120 | loadAverage: this.getLoadAverage(), |
| 121 | uptime: this.getProcessUptime(), |
| 122 | freeMemory: this.getFreeMemory(), |
| 123 | totalMemory: this.getTotalMemory(), |
| 124 | }, |
| 125 | eventLoop: { |
| 126 | lag: this.measureEventLoopLag(), |
| 127 | }, |
| 128 | }; |
| 129 | |
| 130 | // Try to get file descriptor count (Unix only) |
| 131 | this.getFileDescriptorCount() |
| 132 | .then((count) => { |
| 133 | if (count !== null) { |
| 134 | usage.fileDescriptors = count; |
| 135 | } |
| 136 | }) |
| 137 | .catch(() => { |
| 138 | // Ignore errors for file descriptor counting |
| 139 | }); |
| 140 | |
| 141 | return usage; |
| 142 | } |
| 143 | |
| 144 | public getResourceHistory(): ResourceUsage[] { |
| 145 | return [...this.resourceHistory]; |
| 146 | } |
| 147 | |
| 148 | public getResourceSummary(): { |
| 149 | current: ResourceUsage; |
| 150 | peak: { |
| 151 | memory: number; |
| 152 | cpu: number; |
| 153 | }; |
| 154 | average: { |
| 155 | memory: number; |
| 156 | cpu: number; |
| 157 | }; |
| 158 | } { |
| 159 | const current = this.getCurrentResourceUsage(); |
| 160 | |
| 161 | if (this.resourceHistory.length === 0) { |
| 162 | return { |
| 163 | current, |
| 164 | peak: { |
| 165 | memory: current.memory.rss, |
| 166 | cpu: current.cpu.percent || 0, |
| 167 | }, |
| 168 | average: { |
| 169 | memory: current.memory.rss, |
| 170 | cpu: current.cpu.percent || 0, |
| 171 | }, |
| 172 | }; |
| 173 | } |
| 174 | |
| 175 | const peakMemory = Math.max( |
| 176 | ...this.resourceHistory.map((r) => r.memory.rss), |
| 177 | ); |
| 178 | const peakCpu = Math.max( |
| 179 | ...this.resourceHistory.map((r) => r.cpu.percent || 0), |
| 180 | ); |
| 181 | |
| 182 | const avgMemory = |
| 183 | this.resourceHistory.reduce((sum, r) => sum + r.memory.rss, 0) / |
| 184 | this.resourceHistory.length; |
| 185 | const avgCpu = |
| 186 | this.resourceHistory.reduce((sum, r) => sum + (r.cpu.percent || 0), 0) / |
| 187 | this.resourceHistory.length; |
| 188 | |
| 189 | return { |
| 190 | current, |
| 191 | peak: { |
| 192 | memory: Math.max(peakMemory, current.memory.rss), |
| 193 | cpu: Math.max(peakCpu, current.cpu.percent || 0), |
| 194 | }, |
| 195 | average: { |
| 196 | memory: avgMemory, |
| 197 | cpu: avgCpu, |
| 198 | }, |
| 199 | }; |
| 200 | } |
| 201 | |
| 202 | private collectResourceUsage(): void { |
| 203 | try { |
| 204 | const usage = this.getCurrentResourceUsage(); |
| 205 | |
| 206 | // Update for next CPU calculation |
| 207 | this.lastCpuUsage = process.cpuUsage(); |
| 208 | this.lastTimestamp = usage.timestamp; |
| 209 | |
| 210 | // Add to history |
| 211 | this.resourceHistory.push(usage); |
| 212 | |
| 213 | // Trim history if too large |
| 214 | if (this.resourceHistory.length > this.maxHistorySize) { |
| 215 | this.resourceHistory = this.resourceHistory.slice(-this.maxHistorySize); |
| 216 | } |
| 217 | |
| 218 | // Check for potential issues and log warnings |
| 219 | this.checkResourceThresholds(usage); |
| 220 | } catch (error) { |
| 221 | logger.error("Error collecting resource usage", error); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | private checkResourceThresholds(usage: ResourceUsage): void { |
| 226 | const memoryUsageMB = usage.memory.rss / 1024 / 1024; |
| 227 | const cpuPercent = usage.cpu.percent || 0; |
| 228 | |
| 229 | // Memory threshold: 500MB |
| 230 | if (memoryUsageMB > 500) { |
| 231 | logger.warn("High memory usage detected", { |
| 232 | memoryMB: Math.round(memoryUsageMB), |
| 233 | threshold: 500, |
| 234 | }); |
| 235 | } |
| 236 | |
| 237 | // CPU threshold: 80% |
| 238 | if (cpuPercent > 80) { |
| 239 | logger.warn("High CPU usage detected", { |
| 240 | cpuPercent: Math.round(cpuPercent), |
| 241 | threshold: 80, |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | // Event loop lag threshold: 100ms |
| 246 | if (usage.eventLoop.lag > 100) { |
| 247 | logger.warn("High event loop lag detected", { |
| 248 | lagMs: Math.round(usage.eventLoop.lag), |
| 249 | threshold: 100, |
| 250 | }); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | private async getFileDescriptorCount(): Promise<number | null> { |
| 255 | if (process.platform === "win32") { |
| 256 | return null; // Not supported on Windows |
| 257 | } |
| 258 | |
| 259 | try { |
| 260 | const { stdout } = await execAsync(`lsof -p ${process.pid} | wc -l`); |
| 261 | return parseInt(stdout.trim(), 10) - 1; // Subtract 1 for header line |
| 262 | } catch { |
| 263 | return null; |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | private getLoadAverage(): number[] { |
| 268 | try { |
| 269 | return process.platform === "win32" ? [0, 0, 0] : os.loadavg(); |
| 270 | } catch { |
| 271 | return [0, 0, 0]; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | private getProcessUptime(): number { |
| 276 | try { |
| 277 | return typeof process.uptime === "function" ? process.uptime() : 0; |
| 278 | } catch { |
| 279 | return 0; |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | private getFreeMemory(): number { |
| 284 | try { |
| 285 | return os.freemem(); |
| 286 | } catch { |
| 287 | return 0; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | private getTotalMemory(): number { |
| 292 | try { |
| 293 | return os.totalmem(); |
| 294 | } catch { |
| 295 | return 1024 * 1024 * 1024; // 1GB default fallback |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | // Synchronous approximation of event loop lag |
| 300 | private measureEventLoopLag(): number { |
| 301 | // Return a simple approximation based on load average on Unix systems |
| 302 | const loadAvg = this.getLoadAverage(); |
| 303 | if (loadAvg[0] > 0) { |
| 304 | // Rough approximation: higher load = higher lag |
| 305 | return Math.min(loadAvg[0] * 10, 200); // Cap at 200ms |
| 306 | } |
| 307 | |
| 308 | return 0; |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | export { ResourceMonitoringService }; |