/** * Circuit Breaker Implementation * * Provides fault tolerance for provider operations by preventing cascading failures. * Implements the circuit breaker pattern with three states: * - CLOSED: Normal operation, requests pass through * - OPEN: Failing, requests rejected immediately * - HALF_OPEN: Testing recovery, limited requests allowed */ import { AgentRouterError } from '../types.js'; /** * Circuit breaker states. */ export declare enum CircuitState { /** Normal operation - requests pass through */ CLOSED = "CLOSED", /** Circuit is open - requests rejected immediately */ OPEN = "OPEN", /** Testing recovery - limited requests allowed */ HALF_OPEN = "HALF_OPEN" } /** * Configuration options for the circuit breaker. */ export interface CircuitBreakerOptions { /** Number of failures before opening the circuit (default: 5) */ failureThreshold: number; /** Number of successes needed to close from half-open (default: 2) */ successThreshold: number; /** Milliseconds to wait before trying half-open (default: 30000) */ timeout: number; /** Milliseconds to reset failure count in closed state (default: 60000) */ resetTimeout?: number; } /** * Callback function type for state change notifications. */ export type StateChangeCallback = (previousState: CircuitState, newState: CircuitState, metadata: StateChangeMetadata) => void; /** * Metadata provided with state change notifications. */ export interface StateChangeMetadata { /** Current failure count */ failureCount: number; /** Current success count (relevant in HALF_OPEN state) */ successCount: number; /** Timestamp of the state change */ timestamp: Date; /** The error that caused the state change (if applicable) */ error?: Error; } /** * Error thrown when the circuit is open and requests are rejected. */ export declare class CircuitOpenError extends AgentRouterError { /** Time remaining until the circuit may transition to half-open */ readonly retryAfterMs: number; constructor(retryAfterMs: number, cause?: Error); } /** * Circuit Breaker for provider resilience. * * Implements the circuit breaker pattern to prevent cascading failures * when a provider is experiencing issues. The circuit breaker monitors * failures and opens the circuit when the failure threshold is reached, * rejecting requests immediately until the timeout expires. * * State Transitions: * - CLOSED → OPEN: When failureCount >= failureThreshold * - OPEN → HALF_OPEN: When timeout expires * - HALF_OPEN → CLOSED: When successCount >= successThreshold * - HALF_OPEN → OPEN: On any failure * * @example * ```typescript * const breaker = new CircuitBreaker({ * failureThreshold: 5, * successThreshold: 2, * timeout: 30000, * }); * * // Wrap provider calls * const result = await breaker.execute(async () => { * return provider.complete(request); * }); * * // Subscribe to state changes * breaker.onStateChange((prev, next, meta) => { * console.log(`Circuit changed from ${prev} to ${next}`); * }); * ``` */ export declare class CircuitBreaker { /** Configuration options */ private readonly options; /** Internal state */ private state; /** State change subscribers */ private readonly listeners; /** * Create a new CircuitBreaker instance. * * @param options - Configuration options (all have sensible defaults) */ constructor(options?: Partial); /** * Execute an async operation through the circuit breaker. * * In CLOSED state, the operation is executed normally and failures are tracked. * In OPEN state, a CircuitOpenError is thrown immediately without executing. * In HALF_OPEN state, the operation is executed and success/failure determines * whether to close or re-open the circuit. * * @param fn - The async operation to execute * @returns The result of the operation * @throws CircuitOpenError if the circuit is open * @throws The original error if the operation fails */ execute(fn: () => Promise): Promise; /** * Get the current circuit state. * * @returns The current CircuitState */ getState(): CircuitState; /** * Manually reset the circuit breaker to CLOSED state. * * This clears all failure/success counts and allows normal operation * to resume. Use this when you know the underlying issue has been resolved. */ reset(): void; /** * Subscribe to state change notifications. * * The callback will be invoked whenever the circuit state changes. * Returns an unsubscribe function to remove the listener. * * @param callback - Function to call on state changes * @returns Unsubscribe function */ onStateChange(callback: StateChangeCallback): () => void; /** * Get current statistics about the circuit breaker. * * @returns Object with current state and counts */ getStats(): { state: CircuitState; failureCount: number; successCount: number; lastFailureTime: Date | null; }; /** * Check if we should transition from OPEN to HALF_OPEN based on timeout. */ private checkStateTransition; /** * Record a successful operation. */ private recordSuccess; /** * Record a failed operation. */ private recordFailure; /** * Transition to a new state and notify listeners. */ private transitionTo; /** * Notify all listeners of a state change. */ private notifyStateChange; } //# sourceMappingURL=circuit-breaker.d.ts.map