UNPKG

@vfarcic/dot-ai

Version:

AI-powered development productivity platform that enhances software development workflows through intelligent automation and AI-driven assistance

164 lines 4.73 kB
/** * Circuit Breaker Implementation * * Provides resilience for external service calls by preventing cascading failures. * Implements the circuit breaker pattern with three states: * - CLOSED: Normal operation, requests flow through * - OPEN: Failure threshold reached, requests are blocked * - HALF_OPEN: Testing recovery, limited requests allowed */ import { Logger } from './error-handling'; /** * Circuit breaker states */ export declare enum CircuitState { CLOSED = "closed", OPEN = "open", HALF_OPEN = "half_open" } /** * Configuration options for circuit breaker */ export interface CircuitBreakerConfig { /** Number of consecutive failures before opening circuit (default: 3) */ failureThreshold?: number; /** Time in milliseconds to wait before transitioning from OPEN to HALF_OPEN (default: 30000) */ cooldownPeriodMs?: number; /** Number of requests to allow in HALF_OPEN state before deciding (default: 1) */ halfOpenMaxAttempts?: number; /** Callback when state changes */ onStateChange?: (from: CircuitState, to: CircuitState, name: string) => void; } /** * Statistics about circuit breaker state */ export interface CircuitBreakerStats { state: CircuitState; consecutiveFailures: number; totalFailures: number; totalSuccesses: number; lastFailureTime?: Date; lastSuccessTime?: Date; openedAt?: Date; halfOpenAttempts: number; } /** * Error thrown when circuit is open and blocking requests */ export declare class CircuitOpenError extends Error { readonly circuitName: string; readonly remainingCooldownMs: number; readonly state: CircuitState; constructor(circuitName: string, remainingCooldownMs: number); } /** * Circuit Breaker implementation * * Usage: * ```typescript * const breaker = new CircuitBreaker('embedding-api', { failureThreshold: 3 }); * * try { * const result = await breaker.execute(() => fetchFromAPI()); * } catch (error) { * if (error instanceof CircuitOpenError) { * // Circuit is open, handle gracefully * } * } * ``` */ export declare class CircuitBreaker { private readonly name; private readonly config; private readonly logger; private state; private consecutiveFailures; private totalFailures; private totalSuccesses; private lastFailureTime?; private lastSuccessTime?; private openedAt?; private halfOpenAttempts; private lastCircuitOpenLogTime?; private lastFailureLogTime?; private suppressedFailureLogCount; /** Minimum interval between failure WARN logs (ms) */ private static readonly FAILURE_LOG_INTERVAL_MS; constructor(name: string, config?: CircuitBreakerConfig, logger?: Logger); /** * Execute an operation through the circuit breaker * @throws CircuitOpenError if circuit is open * @throws Original error if operation fails */ execute<T>(operation: () => Promise<T>): Promise<T>; /** * Record a successful operation */ recordSuccess(): void; /** * Record a failed operation */ recordFailure(error?: Error): void; /** * Reset the circuit breaker to initial state */ reset(): void; /** * Get the current circuit state */ getState(): CircuitState; /** * Get circuit breaker statistics */ getStats(): CircuitBreakerStats; /** * Check if circuit is currently open (blocking requests) */ isOpen(): boolean; /** * Get the circuit breaker name */ getName(): string; /** * Check if a request can be executed */ private canExecute; /** * Check if cooldown period has elapsed */ private shouldTransitionToHalfOpen; /** * Get remaining cooldown time in milliseconds */ private getRemainingCooldown; /** * Transition to a new state */ private transitionTo; } /** * Factory for creating circuit breakers with shared configuration */ export declare class CircuitBreakerFactory { private readonly defaultConfig; private readonly logger; private readonly breakers; constructor(defaultConfig?: CircuitBreakerConfig, logger?: Logger); /** * Get or create a circuit breaker by name */ getOrCreate(name: string, config?: CircuitBreakerConfig): CircuitBreaker; /** * Get a circuit breaker by name (returns undefined if not exists) */ get(name: string): CircuitBreaker | undefined; /** * Reset all circuit breakers */ resetAll(): void; /** * Get stats for all circuit breakers */ getAllStats(): Record<string, CircuitBreakerStats>; } //# sourceMappingURL=circuit-breaker.d.ts.map