All files / server/services server-metrics.ts

98.88% Statements 89/90
100% Branches 30/30
92.85% Functions 13/14
98.88% Lines 89/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276                  21x                               21x           12x     12x 12x 12x 12x     12x 12x   12x 9x 9x   9x 9x 9x     9x       12x           12x                         12x                                       21x 21x 21x 21x 21x 21x 21x             40x   40x 40x 40x   40x 8x   40x 6x     40x 1x   40x 13x     40x       13x                               25x 25x 25x 25x 25x 25x 25x       21x                           21x 21x 21x 21x 21x     58x 58x 58x       52x 52x 52x       3x 3x       1x 1x       48x       16x                   25x 25x 25x 25x 25x       21x     21x                                               11x 11x 11x 1x   11x 1x   11x 1x   11x 7x   11x 1x   11x 1x   11x 1x   11x    
/**
 * Server Process Metrics
 * 
 * Tracks CPU and memory usage of the Node.js server process.
 * Uses built-in process.cpuUsage() and process.memoryUsage() APIs.
 */
 
import { Logger } from "@shared/logger";
 
const logger = new Logger("ServerMetrics");
 
interface ProcessMetrics {
  cpuPercent: number;
  memoryUsedMB: number;
  memoryTotalMB: number;
  memoryPercent: number;
  uptimeSeconds: number;
}
 
interface CpuUsageSample {
  user: number;
  system: number;
  timestamp: number;
}
 
let previousCpuSample: CpuUsageSample | null = null;
 
/**
 * Get current CPU and memory usage of the Node.js process
 */
export function getProcessMetrics(): ProcessMetrics {
  const now = Date.now();
  
  // Memory usage
  const memUsage = process.memoryUsage();
  const memoryUsedMB = memUsage.heapUsed / (1024 * 1024);
  const memoryTotalMB = osTotalMemoryMB();
  const memoryPercent = (memoryUsedMB / memoryTotalMB) * 100;
  
  // CPU usage (requires two samples)
  const cpuUsage = process.cpuUsage();
  let cpuPercent = 0;
  
  if (previousCpuSample !== null) {
    const elapsedMs = now - previousCpuSample.timestamp;
    const elapsedNs = elapsedMs * 1_000_000; // Convert to nanoseconds
    
    const userDiff = cpuUsage.user - previousCpuSample.user;
    const systemDiff = cpuUsage.system - previousCpuSample.system;
    const totalDiff = userDiff + systemDiff;
    
    // CPU percentage across all cores
    cpuPercent = (totalDiff / elapsedNs) * 100;
  }
  
  // Store sample for next calculation
  previousCpuSample = {
    user: cpuUsage.user,
    system: cpuUsage.system,
    timestamp: now,
  };
  
  return {
    cpuPercent,
    memoryUsedMB,
    memoryTotalMB,
    memoryPercent,
    uptimeSeconds: process.uptime(),
  };
}
 
/**
 * Get total system memory in MB
 */
function osTotalMemoryMB(): number {
  return os.totalmem() / (1024 * 1024);
}
 
// Import os module
import os from "node:os";
 
/**
 * Track compilation metrics (duration, queue wait time)
 */
export interface CompileMetrics {
  compileCount: number;
  compileTimeoutCount: number;
  compileErrorCount: number;
  avgCompileDurationMs: number;
  avgQueueWaitTimeMs: number;
  maxCompileDurationMs: number;
  maxQueueWaitTimeMs: number;
}
 
class CompileMetricsTracker {
  private compileCount = 0;
  private compileTimeoutCount = 0;
  private compileErrorCount = 0;
  private totalCompileDurationMs = 0;
  private totalQueueWaitTimeMs = 0;
  private maxCompileDurationMs = 0;
  private maxQueueWaitTimeMs = 0;
  
  recordCompileStart(): number {
    return Date.now();
  }
  
  recordCompileComplete(startTime: number, queueWaitTimeMs: number, success: boolean, timedOut: boolean): void {
    const duration = Date.now() - startTime;
    
    this.compileCount++;
    this.totalCompileDurationMs += duration;
    this.totalQueueWaitTimeMs += queueWaitTimeMs;
    
    if (duration > this.maxCompileDurationMs) {
      this.maxCompileDurationMs = duration;
    }
    if (queueWaitTimeMs > this.maxQueueWaitTimeMs) {
      this.maxQueueWaitTimeMs = queueWaitTimeMs;
    }
    
    if (timedOut) {
      this.compileTimeoutCount++;
    }
    if (!success) {
      this.compileErrorCount++;
    }
    
    logger.debug(`[CompileMetrics] Compile completed: ${duration.toFixed(0)}ms (queue: ${queueWaitTimeMs.toFixed(0)}ms, success: ${success})`);
  }
  
  getMetrics(): CompileMetrics {
    return {
      compileCount: this.compileCount,
      compileTimeoutCount: this.compileTimeoutCount,
      compileErrorCount: this.compileErrorCount,
      avgCompileDurationMs: this.compileCount > 0 
        ? this.totalCompileDurationMs / this.compileCount 
        : 0,
      avgQueueWaitTimeMs: this.compileCount > 0 
        ? this.totalQueueWaitTimeMs / this.compileCount 
        : 0,
      maxCompileDurationMs: this.maxCompileDurationMs,
      maxQueueWaitTimeMs: this.maxQueueWaitTimeMs,
    };
  }
  
  reset(): void {
    this.compileCount = 0;
    this.compileTimeoutCount = 0;
    this.compileErrorCount = 0;
    this.totalCompileDurationMs = 0;
    this.totalQueueWaitTimeMs = 0;
    this.maxCompileDurationMs = 0;
    this.maxQueueWaitTimeMs = 0;
  }
}
 
export const compileMetricsTracker = new CompileMetricsTracker();
 
/**
 * Track WebSocket session metrics
 */
export interface WebSocketMetrics {
  activeSessions: number;
  runningSessions: number;
  pausedSessions: number;
  totalConnections: number;
  totalDisconnections: number;
}
 
class WebSocketMetricsTracker {
  private activeSessions = 0;
  private runningSessions = 0;
  private pausedSessions = 0;
  private totalConnections = 0;
  private totalDisconnections = 0;
  
  onConnection(): void {
    this.activeSessions++;
    this.totalConnections++;
    logger.debug(`[WebSocketMetrics] Connection: ${this.activeSessions} active, ${this.totalConnections} total`);
  }
  
  onDisconnection(): void {
    this.activeSessions = Math.max(0, this.activeSessions - 1);
    this.totalDisconnections++;
    logger.debug(`[WebSocketMetrics] Disconnection: ${this.activeSessions} active, ${this.totalDisconnections} total`);
  }
  
  onSessionStart(): void {
    this.runningSessions++;
    this.pausedSessions = Math.max(0, this.pausedSessions - 1);
  }
  
  onSessionPause(): void {
    this.runningSessions = Math.max(0, this.runningSessions - 1);
    this.pausedSessions++;
  }
  
  onSessionStop(): void {
    this.runningSessions = Math.max(0, this.runningSessions - 1);
  }
  
  getMetrics(): WebSocketMetrics {
    return {
      activeSessions: this.activeSessions,
      runningSessions: this.runningSessions,
      pausedSessions: this.pausedSessions,
      totalConnections: this.totalConnections,
      totalDisconnections: this.totalDisconnections,
    };
  }
  
  reset(): void {
    this.activeSessions = 0;
    this.runningSessions = 0;
    this.pausedSessions = 0;
    this.totalConnections = 0;
    this.totalDisconnections = 0;
  }
}
 
export const webSocketMetricsTracker = new WebSocketMetricsTracker();
 
/** Operational thresholds used by the status endpoint and alerting adapters. */
export const OBSERVABILITY_THRESHOLDS = {
  compileQueueWaitMs: 60_000,
  compileDurationMs: 60_000,
  runnerQueueMultiplier: 10,
  processMemoryPercent: 90,
  processCpuPercent: 90,
} as const;
 
export interface ObservabilityAlert {
  code: string;
  severity: "warning" | "critical";
  message: string;
}
 
export interface ObservabilitySnapshot {
  compileMetrics: CompileMetrics;
  compileQueueDepth: number;
  runnerQueueDepth: number;
  runnerCapacity: number;
  processMetrics: ProcessMetrics;
}
 
/** Evaluate stable, operator-facing alerts without coupling to a monitoring vendor. */
export function evaluateObservabilityAlerts(snapshot: ObservabilitySnapshot): ObservabilityAlert[] {
  const alerts: ObservabilityAlert[] = [];
  const { compileMetrics, processMetrics } = snapshot;
  if (compileMetrics.compileTimeoutCount > 0) {
    alerts.push({ code: "compile_timeout", severity: "critical", message: "At least one compile timed out" });
  }
  if (compileMetrics.maxQueueWaitTimeMs >= OBSERVABILITY_THRESHOLDS.compileQueueWaitMs) {
    alerts.push({ code: "compile_queue_wait_high", severity: "warning", message: "Compile queue wait exceeded 60 seconds" });
  }
  if (compileMetrics.maxCompileDurationMs >= OBSERVABILITY_THRESHOLDS.compileDurationMs) {
    alerts.push({ code: "compile_duration_high", severity: "warning", message: "Compile duration exceeded 60 seconds" });
  }
  if (snapshot.compileQueueDepth > 0) {
    alerts.push({ code: "compile_queue_nonempty", severity: "warning", message: "Compile slots have queued work" });
  }
  if (snapshot.runnerCapacity > 0 && snapshot.runnerQueueDepth > snapshot.runnerCapacity * OBSERVABILITY_THRESHOLDS.runnerQueueMultiplier) {
    alerts.push({ code: "runner_queue_high", severity: "warning", message: "Runner queue exceeds ten times runner capacity" });
  }
  if (processMetrics.memoryPercent >= OBSERVABILITY_THRESHOLDS.processMemoryPercent) {
    alerts.push({ code: "process_memory_high", severity: "critical", message: "Process memory usage exceeded 90 percent" });
  }
  if (processMetrics.cpuPercent >= OBSERVABILITY_THRESHOLDS.processCpuPercent) {
    alerts.push({ code: "process_cpu_high", severity: "warning", message: "Process CPU usage exceeded 90 percent" });
  }
  return alerts;
}