{"version":3,"sources":["../src/performance.ts"],"sourcesContent":["import type { SecretManager } from './manager';\n\nexport type PerformanceMetrics = {\n  operationLatency: {\n    create: number[];\n    read: number[];\n    update: number[];\n    delete: number[];\n    rotate: number[];\n  };\n  throughput: {\n    operationsPerSecond: number;\n    bytesProcessedPerSecond: number;\n  };\n  resourceUsage: {\n    memoryUsage: number;\n    cpuUsage: number;\n  };\n  cacheMetrics: {\n    hitRate: number;\n    missRate: number;\n    size: number;\n  };\n  errorRates: {\n    total: number;\n    byOperation: Record<string, number>;\n  };\n};\n\nexport type PerformanceConfig = {\n  metricsRetentionMs: number;\n  samplingRate: number; // 0.0 to 1.0\n  alertThresholds: {\n    maxLatencyMs: number;\n    maxErrorRate: number;\n    minThroughput: number;\n  };\n};\n\nexport class PerformanceMonitor {\n  private readonly metrics: PerformanceMetrics = {\n    operationLatency: {\n      create: [],\n      read: [],\n      update: [],\n      delete: [],\n      rotate: [],\n    },\n    throughput: {\n      operationsPerSecond: 0,\n      bytesProcessedPerSecond: 0,\n    },\n    resourceUsage: {\n      memoryUsage: 0,\n      cpuUsage: 0,\n    },\n    cacheMetrics: {\n      hitRate: 0,\n      missRate: 0,\n      size: 0,\n    },\n    errorRates: {\n      total: 0,\n      byOperation: {},\n    },\n  };\n\n  private readonly operationCounts = new Map<string, number>();\n  private readonly errorCounts = new Map<string, number>();\n  private readonly startTime = Date.now();\n\n  constructor(\n    _manager: SecretManager,\n    private readonly config: PerformanceConfig\n  ) {\n    this.startMonitoring();\n  }\n\n  private startMonitoring(): void {\n    // Monitor resource usage every 30 seconds\n    setInterval(() => {\n      this.updateResourceMetrics();\n    }, 30000);\n\n    // Calculate throughput every minute\n    setInterval(() => {\n      this.updateThroughputMetrics();\n    }, 60000);\n\n    // Cleanup old metrics\n    setInterval(() => {\n      this.cleanupOldMetrics();\n    }, this.config.metricsRetentionMs / 4);\n  }\n\n  recordOperation(operation: string, duration: number, success = true): void {\n    if (Math.random() > this.config.samplingRate) {\n      return;\n    }\n\n    // Record latency\n    if (this.metrics.operationLatency[operation as keyof typeof this.metrics.operationLatency]) {\n      this.metrics.operationLatency[operation as keyof typeof this.metrics.operationLatency].push(\n        duration\n      );\n    }\n\n    // Record operation count\n    this.operationCounts.set(operation, (this.operationCounts.get(operation) ?? 0) + 1);\n\n    // Record errors\n    if (!success) {\n      this.errorCounts.set(operation, (this.errorCounts.get(operation) ?? 0) + 1);\n    }\n  }\n\n  recordCacheHit(): void {\n    // This would be called by the caching layer\n    this.metrics.cacheMetrics.hitRate += 1;\n  }\n\n  recordCacheMiss(): void {\n    // This would be called by the caching layer\n    this.metrics.cacheMetrics.missRate += 1;\n  }\n\n  getMetrics(): PerformanceMetrics {\n    this.updateErrorRates();\n    return { ...this.metrics };\n  }\n\n  getHealthScore(): number {\n    // Calculate a health score from 0-100 based on performance\n    const latencyScore = this.calculateLatencyScore();\n    const errorScore = this.calculateErrorScore();\n    const throughputScore = this.calculateThroughputScore();\n\n    return Math.round((latencyScore + errorScore + throughputScore) / 3);\n  }\n\n  private calculateLatencyScore(): number {\n    const allLatencies = [\n      ...this.metrics.operationLatency.create,\n      ...this.metrics.operationLatency.read,\n      ...this.metrics.operationLatency.update,\n      ...this.metrics.operationLatency.delete,\n      ...this.metrics.operationLatency.rotate,\n    ];\n\n    if (allLatencies.length === 0) {\n      return 100;\n    }\n\n    const avgLatency = allLatencies.reduce((a, b) => a + b, 0) / allLatencies.length;\n    const score = Math.max(0, 100 - (avgLatency / this.config.alertThresholds.maxLatencyMs) * 100);\n    return Math.min(100, score);\n  }\n\n  private calculateErrorScore(): number {\n    const totalOperations = Array.from(this.operationCounts.values()).reduce((a, b) => a + b, 0);\n    const totalErrors = Array.from(this.errorCounts.values()).reduce((a, b) => a + b, 0);\n\n    if (totalOperations === 0) {\n      return 100;\n    }\n\n    const errorRate = totalErrors / totalOperations;\n    const score = Math.max(0, 100 - (errorRate / this.config.alertThresholds.maxErrorRate) * 100);\n    return Math.min(100, score);\n  }\n\n  private calculateThroughputScore(): number {\n    const score = Math.min(\n      100,\n      (this.metrics.throughput.operationsPerSecond / this.config.alertThresholds.minThroughput) *\n        100\n    );\n    return Math.max(0, score);\n  }\n\n  private updateResourceMetrics(): void {\n    // Get memory usage\n    const memUsage = process.memoryUsage();\n    this.metrics.resourceUsage.memoryUsage = memUsage.heapUsed / memUsage.heapTotal;\n\n    // CPU usage would require additional monitoring (like node-os-utils)\n    this.metrics.resourceUsage.cpuUsage = 0; // Placeholder\n  }\n\n  private updateThroughputMetrics(): void {\n    const elapsedSeconds = (Date.now() - this.startTime) / 1000;\n    const totalOperations = Array.from(this.operationCounts.values()).reduce((a, b) => a + b, 0);\n\n    this.metrics.throughput.operationsPerSecond = totalOperations / elapsedSeconds;\n    // bytesProcessedPerSecond would need to be tracked separately\n  }\n\n  private updateErrorRates(): void {\n    const totalOperations = Array.from(this.operationCounts.values()).reduce((a, b) => a + b, 0);\n    const totalErrors = Array.from(this.errorCounts.values()).reduce((a, b) => a + b, 0);\n\n    this.metrics.errorRates.total = totalOperations > 0 ? totalErrors / totalOperations : 0;\n\n    for (const [operation, count] of this.operationCounts) {\n      const errors = this.errorCounts.get(operation) ?? 0;\n      this.metrics.errorRates.byOperation[operation] = count > 0 ? errors / count : 0;\n    }\n  }\n\n  private cleanupOldMetrics(): void {\n    // const cutoffTime = Date.now() - this.config.metricsRetentionMs;\n\n    // Keep only recent latency measurements\n    const maxSamples = 1000; // Keep last 1000 samples per operation type\n    for (const operation of Object.keys(this.metrics.operationLatency) as Array<\n      keyof typeof this.metrics.operationLatency\n    >) {\n      if (this.metrics.operationLatency[operation].length > maxSamples) {\n        this.metrics.operationLatency[operation] =\n          this.metrics.operationLatency[operation].slice(-maxSamples);\n      }\n    }\n  }\n\n  getAlerts(): string[] {\n    const alerts: string[] = [];\n    const metrics = this.getMetrics();\n\n    // Check latency threshold\n    const avgLatency = this.getAverageLatency();\n    if (avgLatency > this.config.alertThresholds.maxLatencyMs) {\n      alerts.push(\n        `High latency detected: ${avgLatency.toFixed(2)}ms (threshold: ${this.config.alertThresholds.maxLatencyMs}ms)`\n      );\n    }\n\n    // Check error rate threshold\n    if (metrics.errorRates.total > this.config.alertThresholds.maxErrorRate) {\n      alerts.push(\n        `High error rate detected: ${(metrics.errorRates.total * 100).toFixed(2)}% (threshold: ${(this.config.alertThresholds.maxErrorRate * 100).toFixed(2)}%)`\n      );\n    }\n\n    // Check throughput threshold\n    if (metrics.throughput.operationsPerSecond < this.config.alertThresholds.minThroughput) {\n      alerts.push(\n        `Low throughput detected: ${metrics.throughput.operationsPerSecond.toFixed(2)} ops/sec (threshold: ${this.config.alertThresholds.minThroughput} ops/sec)`\n      );\n    }\n\n    return alerts;\n  }\n\n  private getAverageLatency(): number {\n    const allLatencies = [\n      ...this.metrics.operationLatency.create,\n      ...this.metrics.operationLatency.read,\n      ...this.metrics.operationLatency.update,\n      ...this.metrics.operationLatency.delete,\n      ...this.metrics.operationLatency.rotate,\n    ];\n\n    return allLatencies.length > 0\n      ? allLatencies.reduce((a, b) => a + b, 0) / allLatencies.length\n      : 0;\n  }\n}\n\nexport class ConnectionPool<TConnection> {\n  private pool: TConnection[] = [];\n  private activeConnections = 0;\n  private readonly waitingQueue: Array<(connection: TConnection) => void> = [];\n\n  constructor(\n    private readonly maxConnections: number,\n    private readonly createConnection: () => Promise<TConnection>,\n    private readonly destroyConnection: (connection: TConnection) => Promise<void>\n  ) {}\n\n  async getConnection(): Promise<TConnection> {\n    if (this.pool.length > 0) {\n      const connection = this.pool.pop();\n      if (!connection) {\n        this.activeConnections++;\n        return await this.createConnection();\n      }\n      this.activeConnections++;\n      return connection;\n    }\n\n    if (this.activeConnections < this.maxConnections) {\n      this.activeConnections++;\n      return await this.createConnection();\n    }\n\n    // Wait for a connection to become available\n    return new Promise((resolve) => {\n      this.waitingQueue.push(resolve);\n    });\n  }\n\n  releaseConnection(connection: TConnection): Promise<void> {\n    this.activeConnections--;\n\n    if (this.waitingQueue.length > 0) {\n      const waitingResolver = this.waitingQueue.shift();\n      if (waitingResolver) {\n        waitingResolver(connection);\n        return Promise.resolve();\n      }\n    }\n    this.pool.push(connection);\n    return Promise.resolve();\n  }\n\n  async close(): Promise<void> {\n    await Promise.all(this.pool.map((connection) => this.destroyConnection(connection)));\n    this.pool = [];\n    this.activeConnections = 0;\n  }\n\n  getStats(): { active: number; idle: number; waiting: number } {\n    return {\n      active: this.activeConnections,\n      idle: this.pool.length,\n      waiting: this.waitingQueue.length,\n    };\n  }\n}\n"],"mappings":";;;;;AAuCO,IAAM,qBAAN,MAAyB;AAAA,EAgC9B,YACE,UACiB,QACjB;AADiB;AAjCnB,wBAAiB,WAA8B;AAAA,MAC7C,kBAAkB;AAAA,QAChB,QAAQ,CAAC;AAAA,QACT,MAAM,CAAC;AAAA,QACP,QAAQ,CAAC;AAAA,QACT,QAAQ,CAAC;AAAA,QACT,QAAQ,CAAC;AAAA,MACX;AAAA,MACA,YAAY;AAAA,QACV,qBAAqB;AAAA,QACrB,yBAAyB;AAAA,MAC3B;AAAA,MACA,eAAe;AAAA,QACb,aAAa;AAAA,QACb,UAAU;AAAA,MACZ;AAAA,MACA,cAAc;AAAA,QACZ,SAAS;AAAA,QACT,UAAU;AAAA,QACV,MAAM;AAAA,MACR;AAAA,MACA,YAAY;AAAA,QACV,OAAO;AAAA,QACP,aAAa,CAAC;AAAA,MAChB;AAAA,IACF;AAEA,wBAAiB,mBAAkB,oBAAI,IAAoB;AAC3D,wBAAiB,eAAc,oBAAI,IAAoB;AACvD,wBAAiB,aAAY,KAAK,IAAI;AAMpC,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEQ,kBAAwB;AAE9B,gBAAY,MAAM;AAChB,WAAK,sBAAsB;AAAA,IAC7B,GAAG,GAAK;AAGR,gBAAY,MAAM;AAChB,WAAK,wBAAwB;AAAA,IAC/B,GAAG,GAAK;AAGR,gBAAY,MAAM;AAChB,WAAK,kBAAkB;AAAA,IACzB,GAAG,KAAK,OAAO,qBAAqB,CAAC;AAAA,EACvC;AA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