All files / components/shared/mobile PerformanceMonitor.ts

86.48% Statements 96/111
75.67% Branches 56/74
90.47% Functions 19/21
88.54% Lines 85/96

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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439                                                                                                                            3x   27x 27x 27x 27x 27x           27x 27x 27x 27x           27x 27x 27x   27x                             28x 1x           1x     27x 27x                                         27x       27x   27x   27x   27x   27x 27x   27x 3x     24x   24x 4x 3x   24x 4x 4x   24x   24x   24x   24x 4x                     5x   4x 4x 4x 4x   4x                 1x   1x 1x 1x                   4x 4x   4x 4x 4x   4x 4x       4x       4x           4x 4x     4x                                             4x 3x     1x             1x 1x                     5x                                 6x                   3x                               4x   2x                 1x                 1x                                 1x                   1x                   1x                 1x 1x 1x 1x                     1x                   1x                   1x                   1x    
/**
 * PerformanceMonitor
 * 
 * Device capability detection and performance monitoring
 * Provides adaptive behavior based on device performance
 * 
 * Key Features:
 * - Device performance tier detection (high, medium, low)
 * - Real-time FPS monitoring
 * - Frame drop detection
 * - Adaptive quality recommendations
 * - Memory usage tracking
 * 
 * @module components/mobile/PerformanceMonitor
 * @category Mobile Controls
 * @korean 성능 모니터
 */
 
/**
 * Device performance tier
 */
export type PerformanceTier = 'high' | 'medium' | 'low';
 
/**
 * Performance metrics
 */
export interface PerformanceMetrics {
  /** Current FPS (frames per second) */
  readonly fps: number;
  /** Average frame time in milliseconds */
  readonly avgFrameTime: number;
  /** Frame drop count in last second */
  readonly frameDrops: number;
  /** Memory usage in MB (if available) */
  readonly memoryUsage: number | null;
  /** Device performance tier */
  readonly tier: PerformanceTier;
  /** Is 60fps target being met */
  readonly isSixtyFps: boolean;
}
 
/**
 * Performance monitoring options
 */
export interface PerformanceMonitorOptions {
  /** Sample window size in frames (default: 60) */
  readonly sampleWindow?: number;
  /** Target FPS (default: 60) */
  readonly targetFps?: number;
  /** Frame time threshold for drops in ms (default: 20) */
  readonly frameDropThreshold?: number;
  /** Enable memory monitoring (default: true) */
  readonly enableMemoryMonitoring?: boolean;
}
 
/**
 * PerformanceMonitor class
 * Monitors device performance and provides adaptive recommendations
 * 
 * @korean 성능모니터
 */
export class PerformanceMonitor {
  private static instance: PerformanceMonitor | null = null;
  
  private tier: PerformanceTier = 'high';
  private fps: number = 60;
  private avgFrameTime: number = 16.67;
  private frameDrops: number = 0;
  private memoryUsage: number | null = null;
  
  private sampleWindow: number;
  private frameDropThreshold: number;
  private enableMemoryMonitoring: boolean;
  
  private frameTimes: number[] = [];
  private lastFrameTime: number = 0;
  private rafId: number | null = null;
  private isMonitoring: boolean = false;
 
  /**
   * Private constructor for singleton pattern
   */
  private constructor(options: PerformanceMonitorOptions = {}) {
    this.sampleWindow = options.sampleWindow ?? 60;
    this.frameDropThreshold = options.frameDropThreshold ?? 20;
    this.enableMemoryMonitoring = options.enableMemoryMonitoring ?? true;
    
    this.tier = this.detectPerformanceTier();
  }
 
  /**
   * Get singleton instance
   * 
   * @param options - Performance monitor options
   * @returns PerformanceMonitor instance
   * @korean 인스턴스가져오기
   * 
   * Note: Options are only applied on first initialization. Subsequent calls with
   * options will ignore them and emit a warning. Configure the PerformanceMonitor
   * on the first getInstance call only.
   */
  public static getInstance(options?: PerformanceMonitorOptions): PerformanceMonitor {
    if (this.instance !== null) {
      Iif (options && Object.keys(options).length > 0) {
        console.warn(
          'PerformanceMonitor.getInstance: options provided after initial initialization are ignored. ' +
          'Configure the PerformanceMonitor on the first getInstance call only.'
        );
      }
      return this.instance;
    }
    
    this.instance = new PerformanceMonitor(options);
    return this.instance;
  }
 
  /**
   * Detect device performance tier
   * Uses multiple heuristics to determine device capability
   * 
   * Edge Cases:
   * - Low-end desktops (2 cores, 2GB RAM) may score as 'medium' due to desktop bonus
   * - High-end mobiles (6+ cores, 6GB+ RAM) correctly score as 'high'
   * - Very low-spec devices (≤2 cores AND ≤2GB) are always 'low' regardless of platform
   * 
   * This intentionally favors:
   * - Devices with more CPU cores and memory
   * - iOS devices (typically good performance)
   * - Better network connections (4G/5G)
   * 
   * @returns Performance tier (high, medium, low)
   * @korean 성능등급감지
   */
  private detectPerformanceTier(): PerformanceTier {
    Iif (typeof navigator === 'undefined') {
      return 'medium';
    }
 
    const cores = navigator.hardwareConcurrency ?? 4;
    
    const memory = (navigator as Navigator & { deviceMemory?: number }).deviceMemory ?? 4;
    
    const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
    
    const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    
    const connection = (navigator as Navigator & { connection?: { effectiveType?: string } }).connection;
    const connectionType = connection?.effectiveType;
    
    if (cores <= 2 && memory <= 2) {
      return 'low';
    }
    
    let score = 0;
    
    if (cores >= 8) score += 3;
    else if (cores >= 6) score += 2;
    else Eif (cores >= 4) score += 1;
    
    if (memory >= 8) score += 3;
    else Iif (memory >= 6) score += 2;
    else Eif (memory >= 4) score += 1;
    
    if (!isMobile) score += 1;
    
    if (isIOS) score += 1;
    
    if (connectionType === '4g' || connectionType === '5g') score += 1;
    
    if (score >= 6) return 'high';
    Eif (score >= 3) return 'medium';
    return 'low';
  }
 
  /**
   * Start monitoring performance
   * Begins tracking FPS and frame times
   * 
   * @korean 모니터링시작
   */
  public startMonitoring(): void {
    if (this.isMonitoring) return;
    
    this.isMonitoring = true;
    this.lastFrameTime = performance.now();
    this.frameTimes = [];
    this.frameDrops = 0;
    
    this.monitorFrame();
  }
 
  /**
   * Stop monitoring performance
   * 
   * @korean 모니터링중지
   */
  public stopMonitoring(): void {
    this.isMonitoring = false;
    
    Eif (this.rafId !== null) {
      cancelAnimationFrame(this.rafId);
      this.rafId = null;
    }
  }
 
  /**
   * Monitor frame timing
   * Called on every animation frame
   * 
   * @korean 프레임모니터링
   */
  private monitorFrame = (): void => {
    Iif (!this.isMonitoring) return;
 
    const now = performance.now();
    const frameTime = now - this.lastFrameTime;
    this.lastFrameTime = now;
 
    this.frameTimes.push(frameTime);
    Iif (this.frameTimes.length > this.sampleWindow) {
      this.frameTimes.shift();
    }
 
    Iif (frameTime > this.frameDropThreshold) {
      this.frameDrops++;
    }
 
    Iif (this.frameTimes.length === this.sampleWindow) {
      this.calculateMetrics();
      
      this.frameDrops = 0;
    }
 
    Eif (this.enableMemoryMonitoring) {
      this.updateMemoryUsage();
    }
 
    this.rafId = requestAnimationFrame(this.monitorFrame);
  };
 
  /**
   * Calculate performance metrics from frame times
   * 
   * @korean 메트릭계산
   */
  private calculateMetrics(): void {
    if (this.frameTimes.length === 0) return;
 
    const sum = this.frameTimes.reduce((acc, time) => acc + time, 0);
    this.avgFrameTime = sum / this.frameTimes.length;
 
    this.fps = 1000 / this.avgFrameTime;
  }
 
  /**
   * Update memory usage metrics
   * 
   * @korean 메모리사용량업데이트
   */
  private updateMemoryUsage(): void {
    if (typeof performance === 'undefined' || !('memory' in performance)) {
      return;
    }
 
    const memory = (performance as Performance & { 
      memory?: { 
        usedJSHeapSize?: number;
        totalJSHeapSize?: number;
      } 
    }).memory;
 
    Eif (memory?.usedJSHeapSize) {
      this.memoryUsage = Math.round(memory.usedJSHeapSize / (1024 * 1024));
    }
  }
 
  /**
   * Get current performance metrics
   * 
   * @returns Current performance metrics
   * @korean 메트릭가져오기
   */
  public getMetrics(): PerformanceMetrics {
    return {
      fps: Math.round(this.fps),
      avgFrameTime: Math.round(this.avgFrameTime * 100) / 100,
      frameDrops: this.frameDrops,
      memoryUsage: this.memoryUsage,
      tier: this.tier,
      isSixtyFps: this.fps >= 58, // Allow 2fps tolerance
    };
  }
 
  /**
   * Get device performance tier
   * 
   * @returns Performance tier
   * @korean 성능등급가져오기
   */
  public getPerformanceTier(): PerformanceTier {
    return this.tier;
  }
 
  /**
   * Check if device can handle 60fps
   * 
   * @returns True if 60fps is achievable
   * @korean 60fps가능여부
   */
  public canHandle60Fps(): boolean {
    return this.tier !== 'low' && this.fps >= 58;
  }
 
  /**
   * Get recommended quality settings based on performance
   * 
   * @returns Quality recommendations
   * @korean 품질권장사항가져오기
   */
  public getQualityRecommendations(): {
    enableHaptics: boolean;
    enableParticles: boolean;
    enableShadows: boolean;
    targetFps: number;
    coalescingRate: number;
  } {
    switch (this.tier) {
      case 'high':
        return {
          enableHaptics: true,
          enableParticles: true,
          enableShadows: true,
          targetFps: 60,
          coalescingRate: 5, // Sample more events
        };
      
      case 'medium':
        return {
          enableHaptics: true,
          enableParticles: true,
          enableShadows: false,
          targetFps: 60,
          coalescingRate: 3, // Moderate sampling
        };
      
      case 'low':
        return {
          enableHaptics: false,
          enableParticles: false,
          enableShadows: false,
          targetFps: 30,
          coalescingRate: 1, // Minimal sampling
        };
    }
  }
 
  /**
   * Check if frame drops are occurring
   * 
   * @returns True if frame drops detected
   * @korean 프레임드롭감지
   */
  public hasFrameDrops(): boolean {
    return this.frameDrops > 3; // More than 3 drops per sample window
  }
 
  /**
   * Get current FPS
   * 
   * @returns Current FPS
   * @korean FPS가져오기
   */
  public getCurrentFps(): number {
    return Math.round(this.fps);
  }
 
  /**
   * Get average frame time
   * 
   * @returns Average frame time in milliseconds
   * @korean 평균프레임타임가져오기
   */
  public getAvgFrameTime(): number {
    return Math.round(this.avgFrameTime * 100) / 100;
  }
 
  /**
   * Reset performance metrics
   * 
   * @korean 메트릭리셋
   */
  public reset(): void {
    this.frameTimes = [];
    this.frameDrops = 0;
    this.fps = 60;
    this.avgFrameTime = 16.67;
  }
}
 
/**
 * Convenience function to get performance monitor instance
 * 
 * @returns PerformanceMonitor instance
 * @korean 성능모니터가져오기
 */
export function getPerformanceMonitor(): PerformanceMonitor {
  return PerformanceMonitor.getInstance();
}
 
/**
 * Convenience function to get current performance tier
 * 
 * @returns Performance tier
 * @korean 성능등급가져오기
 */
export function getPerformanceTier(): PerformanceTier {
  return PerformanceMonitor.getInstance().getPerformanceTier();
}
 
/**
 * Convenience function to check if device can handle 60fps
 * 
 * @returns True if 60fps is achievable
 * @korean 60fps가능여부
 */
export function canHandle60Fps(): boolean {
  return PerformanceMonitor.getInstance().canHandle60Fps();
}
 
/**
 * Convenience function to get quality recommendations
 * 
 * @returns Quality recommendations
 * @korean 품질권장사항가져오기
 */
export function getQualityRecommendations() {
  return PerformanceMonitor.getInstance().getQualityRecommendations();
}