/** * Circuit Breaker and Metrics * * Implements the circuit breaker pattern to protect against repeated failures * and provides comprehensive metrics tracking for guardian operations. */ import type { CircuitBreakerConfig, CircuitBreakerState, GuardianMetrics, Violation } from './types'; /** * Circuit breaker event types */ export type CircuitBreakerEvent = 'open' | 'close' | 'half-open' | 'violation' | 'success'; /** * Circuit breaker event handler */ export type CircuitBreakerEventHandler = (event: CircuitBreakerEvent, data?: Record) => void; /** * Circuit Breaker implementation * * Protects against cascading failures by opening the circuit * when too many violations occur within a time window. */ export declare class CircuitBreaker { private config; private state; private violations; private lastOpenTime; private halfOpenSuccesses; private eventHandlers; constructor(config: CircuitBreakerConfig); /** * Check if the circuit is open (requests should be blocked) */ isOpen(): boolean; /** * Check if the circuit allows requests * @deprecated Use isOpen() instead - this method duplicates functionality. * Guardian uses isOpen() exclusively for circuit breaker checks. */ allowRequest(): boolean; /** * Record a violation */ recordViolation(violation: Violation): void; /** * Record a successful request (no violations) */ recordSuccess(): void; /** * Trip the circuit breaker (open it) */ trip(): void; /** * Reset the circuit breaker (close it) */ reset(): void; /** * Force the circuit to a specific state. * When forcing to 'open', also updates lastOpenTime so the cooldown * period starts from now (matching trip() behavior). */ forceState(state: CircuitBreakerState): void; /** * Get the current state */ getState(): CircuitBreakerState; /** * Get violation count in current window */ getViolationCount(): number; /** * Get time until the circuit breaker resets (if open) */ getTimeUntilReset(): number; /** * Register an event handler */ onEvent(handler: CircuitBreakerEventHandler): void; /** * Remove an event handler */ offEvent(handler: CircuitBreakerEventHandler): void; /** * Transition to a new state */ private transition; /** * Emit an event to all handlers */ private emit; } /** * Metrics collector for guardian operations */ export declare class MetricsCollector { private currentWindow; private windowDurationMs; private history; private maxHistoryWindows; private currency; constructor(options?: { windowDurationMs?: number; maxHistoryWindows?: number; currency?: string; }); /** * Record a request */ recordRequest(options: { blocked: boolean; warned: boolean; latencyMs: number; violations: Violation[]; cost?: number; }): void; /** * Get current metrics */ getMetrics(circuitBreakerState?: CircuitBreakerState): GuardianMetrics; /** * Get metrics for the current window only */ getCurrentWindowMetrics(): Partial; /** * Reset all metrics */ reset(): void; /** * Get cost per minute (actual rate based on elapsed time) * * To avoid extreme extrapolated values immediately after window rotation, * we require a minimum duration of data before extrapolating. If insufficient * data is available in the current window, we fall back to historical data. */ private getCostPerMinute; /** * Get hourly cost */ private getHourlyCost; /** * Get daily cost (estimated based on available data) */ private getDailyCost; /** * Create a new metrics window */ private createWindow; /** * Rotate to a new window if needed */ private rotateWindowIfNeeded; } /** * Rate limiter configuration */ export interface RateLimiterConfig { requestsPerMinute?: number; requestsPerHour?: number; requestsPerDay?: number; burstLimit?: number; } /** * Token bucket rate limiter */ export declare class RateLimiter { private config; private minuteWindow; private hourWindow; private dayWindow; private burstTokens; private lastBurstRefill; constructor(config: RateLimiterConfig); /** * Check if a request is allowed */ allowRequest(): { allowed: boolean; reason?: string; retryAfterMs?: number; }; /** * Get current rate limit status */ getStatus(): { minuteUsed: number; minuteLimit?: number; hourUsed: number; hourLimit?: number; dayUsed: number; dayLimit?: number; burstTokens: number; burstLimit?: number; }; /** * Reset all rate limits */ reset(): void; /** * Refill burst tokens */ private refillBurstTokens; /** * Rotate time windows using sliding window approximation. * * To prevent the fixed-window burst vulnerability (allowing 2× the limit at * window boundaries), we use a sliding window approximation: when a window * rotates, we carry over a proportional count from the previous window based * on how much of the new window overlaps with the old one. */ private rotateWindows; } //# sourceMappingURL=circuit-breaker.d.ts.map