All files / src/common/services resilience-metrics.service.ts

85.71% Statements 12/14
100% Branches 6/6
50% Functions 2/4
83.33% Lines 10/12

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 5715x 15x     15x           12x 12x                 12x 12x                 12x 12x                                       27x          
import { Injectable } from '@nestjs/common';
import { Counter, Histogram, register } from 'prom-client';
 
@Injectable()
export class ResilienceMetricsService {
  private readonly idemCounter: Counter<string>;
  private readonly retryCounter: Counter<string>;
  private readonly externalLatency: Histogram<string>;
 
  constructor() {
    const existingIdem = register.getSingleMetric('idempotency_requests_total') as Counter<string> | undefined;
    this.idemCounter =
      existingIdem ||
      new Counter({
        name: 'idempotency_requests_total',
        help: 'Idempotent request outcomes',
        labelNames: ['action', 'route'] as const,
        registers: [register],
      });
 
    const existingRetry = register.getSingleMetric('retry_attempts_total') as Counter<string> | undefined;
    this.retryCounter =
      existingRetry ||
      new Counter({
        name: 'retry_attempts_total',
        help: 'Retry attempts by subsystem',
        labelNames: ['subsystem', 'result'] as const,
        registers: [register],
      });
 
    const existingLatency = register.getSingleMetric('external_call_duration_seconds') as Histogram<string> | undefined;
    this.externalLatency =
      existingLatency ||
      new Histogram({
        name: 'external_call_duration_seconds',
        help: 'Latency for external calls',
        labelNames: ['subsystem', 'operation'] as const,
        buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2],
        registers: [register],
      });
  }
 
  incrementIdempotencyHits(action: 'hit' | 'store', route: string) {
    this.idemCounter.inc({ action, route });
  }
 
  recordRetry(subsystem: string, result: 'success' | 'failure') {
    this.retryCounter.inc({ subsystem, result });
  }
 
  startTimer(subsystem: string, operation: string) {
    return this.externalLatency.startTimer({ subsystem, operation });
  }
}