/** * API Metrics * * Collects and reports API performance metrics including * latency, error rates, and throughput. * * @module api/advanced/api-metrics */ /** * Single request metric. */ export interface RequestMetric { /** Request URL/endpoint */ endpoint: string; /** HTTP method */ method: string; /** Response status code */ status: number; /** Request duration in milliseconds */ duration: number; /** Request timestamp */ timestamp: number; /** Whether request succeeded */ success: boolean; /** Error message if failed */ error?: string; /** Request size in bytes */ requestSize?: number; /** Response size in bytes */ responseSize?: number; /** Correlation ID */ correlationId?: string; /** Custom tags */ tags?: Record; } /** * Aggregated metrics for an endpoint. */ export interface EndpointMetrics { /** Endpoint path */ endpoint: string; /** Total request count */ totalRequests: number; /** Successful requests */ successCount: number; /** Failed requests */ errorCount: number; /** Success rate (0-1) */ successRate: number; /** Average duration in ms */ avgDuration: number; /** Minimum duration in ms */ minDuration: number; /** Maximum duration in ms */ maxDuration: number; /** P50 latency in ms */ p50Latency: number; /** P90 latency in ms */ p90Latency: number; /** P95 latency in ms */ p95Latency: number; /** P99 latency in ms */ p99Latency: number; /** Status code distribution */ statusCodes: Record; /** Error distribution */ errors: Record; /** Last request timestamp */ lastRequestAt: number; /** Requests per second (recent) */ requestsPerSecond: number; } /** * Overall API metrics. */ export interface OverallMetrics { /** Total requests across all endpoints */ totalRequests: number; /** Total successful requests */ totalSuccess: number; /** Total failed requests */ totalErrors: number; /** Overall success rate */ successRate: number; /** Overall average duration */ avgDuration: number; /** Overall P95 latency */ p95Latency: number; /** Total requests per second */ requestsPerSecond: number; /** Unique endpoints count */ endpointCount: number; /** Metrics collection start time */ collectionStartedAt: number; /** Time window in milliseconds */ windowMs: number; } /** * Metrics collector configuration. */ export interface MetricsConfig { /** Maximum number of metrics to store */ maxMetrics?: number; /** Time window for aggregation (ms) */ windowMs?: number; /** Flush interval for reporters (ms) */ flushInterval?: number; /** Enable detailed per-request storage */ enableDetailedMetrics?: boolean; /** Endpoints to exclude from collection */ excludeEndpoints?: string[]; /** Custom metric reporter */ reporter?: MetricsReporter; } /** * Metrics reporter interface. */ export interface MetricsReporter { /** Report a single metric */ report: (metric: RequestMetric) => void; /** Flush all metrics */ flush: (metrics: RequestMetric[]) => void; /** Report aggregated metrics */ reportAggregated?: (metrics: OverallMetrics) => void; } /** * API Metrics Collector for performance monitoring. * * @example * ```typescript * const metrics = new APIMetricsCollector({ * maxMetrics: 10000, * windowMs: 60000, * reporter: { * report: (metric) => console.log(metric), * flush: (metrics) => sendToAnalytics(metrics), * }, * }); * * // Record a metric * metrics.record({ * endpoint: '/users', * method: 'GET', * status: 200, * duration: 150, * timestamp: Date.now(), * success: true, * }); * * // Get endpoint metrics * const userMetrics = metrics.getEndpointMetrics('/users'); * console.log(`P95 latency: ${userMetrics.p95Latency}ms`); * ``` */ export declare class APIMetricsCollector { private config; private metrics; private endpointCache; private collectionStartedAt; private readonly flushTimer?; /** * Create a new metrics collector. * * @param config - Collector configuration */ constructor(config?: MetricsConfig); /** * Record a request metric. * * @param metric - Metric to record */ record(metric: RequestMetric): void; /** * Create a timing wrapper for requests. * * @param endpoint - Request endpoint * @param method - HTTP method * @param tags - Custom tags * @returns Timing functions */ startTiming(endpoint: string, method: string, tags?: Record): { success: (status: number, responseSize?: number) => void; error: (error: Error, status?: number) => void; }; /** * Get metrics for a specific endpoint. * * @param endpoint - Endpoint path * @param method - Optional HTTP method filter * @returns Aggregated endpoint metrics */ getEndpointMetrics(endpoint: string, method?: string): EndpointMetrics; /** * Get overall API metrics. */ getOverallMetrics(): OverallMetrics; /** * Get metrics for all endpoints. */ getAllEndpointMetrics(): EndpointMetrics[]; /** * Get slow requests. * * @param threshold - Duration threshold in ms * @param limit - Maximum results */ getSlowRequests(threshold: number, limit?: number): RequestMetric[]; /** * Get recent errors. * * @param limit - Maximum results */ getRecentErrors(limit?: number): RequestMetric[]; /** * Get error distribution. */ getErrorDistribution(): Record; /** * Flush metrics to reporter. */ flush(): void; /** * Export metrics as JSON. */ exportJSON(): string; /** * Export metrics as CSV. */ exportCSV(): string; /** * Clear all metrics. */ clear(): void; /** * Dispose of the collector. */ dispose(): void; /** * Check if endpoint should be excluded. */ private shouldExclude; /** * Get cache key for endpoint. */ private getEndpointKey; /** * Aggregate metrics for an endpoint. */ private aggregateMetrics; /** * Create empty endpoint metrics. */ private emptyEndpointMetrics; /** * Calculate percentile. */ private percentile; } /** * Create a new metrics collector. * * @param config - Collector configuration * @returns APIMetricsCollector instance */ export declare function createMetricsCollector(config?: MetricsConfig): APIMetricsCollector; /** * Console reporter for debugging. */ export declare const consoleReporter: MetricsReporter; /** * Create a batched reporter that accumulates metrics. */ export declare function createBatchedReporter(onBatch: (metrics: RequestMetric[]) => void, options?: { batchSize?: number; maxWait?: number; }): MetricsReporter;