import { Func } from '../types.ts'; /** * Represents the three states of a circuit breaker. */ declare enum CircuitBreakerState { /** Normal operation - all calls pass through and failures are counted */ Closed = 0, /** Circuit is tripped - all calls fail immediately without invoking the function */ Open = 1, /** Testing recovery - allows limited test calls to check if service has recovered */ HalfOpen = 2 } /** * Internal state store for circuit breaker operations. */ declare class CircuitBreakerStore { /** Current state of the circuit breaker */ state: CircuitBreakerState; /** Number of consecutive failures in closed state */ failures: number; /** Number of attempts made in half-open state */ halfOpenAttempts: number; /** Timestamp when circuit was last tripped (opened) */ trippedAt: number | null; /** Flag indicating if a test call is currently in progress in half-open state */ testInProgress: boolean; /** Timestamp when the circuit breaker will be available again */ nextAvailable: number | null; } /** * Configuration options for circuit breaker behavior. * * @template T - The function type being protected */ export type CircuitBreakerOptions = { /** * Maximum number of consecutive failures before tripping the circuit * * @default 3 */ maxFailures?: number; /** * Maximum number of test attempts allowed in half-open state * * @default 1 */ halfOpenMaxAttempts?: number; /** * Time in milliseconds to wait before testing recovery * * @default 1000 */ resetAfter?: number; /** * Callback invoked when circuit breaker trips (opens) */ onTripped?: (error: CircuitBreakerError, store: CircuitBreakerStore) => void; /** * Callback invoked when the protected function throws an error */ onError?: (error: Error, args: Parameters) => void; /** * Callback invoked when circuit breaker resets (closes) */ onReset?: () => void; /** * Callback invoked when circuit breaker enters half-open state */ onHalfOpen?: (store: CircuitBreakerStore) => void; /** * Predicate function to determine if an error should trip the circuit * * @default all errors trip */ shouldTripOnError?: (error: Error) => boolean; }; /** * Error thrown when circuit breaker is in open state and prevents function execution. */ export declare class CircuitBreakerError extends Error { /** * Creates a new CircuitBreakerError. * * @param message - Error message describing the circuit breaker state */ constructor(message: string); } export declare const isCircuitBreakerError: (error: unknown) => error is CircuitBreakerError; /** * Circuit breaker that protects a function from failing too many times. * * Implements the Circuit Breaker design pattern to improve system resilience and fault tolerance * by preventing cascading failures in distributed systems. The circuit breaker monitors function * calls and automatically "trips" (opens) when failures exceed a threshold, preventing further * calls to the failing function until it has time to recover. * * The circuit breaker operates in three states: * - **Closed**: Normal operation, all calls pass through. Failures are counted. * - **Open**: Circuit is tripped, all calls fail immediately without invoking the function. * - **Half-Open**: After a timeout, allows limited test calls to check if the service has recovered. * * Key features: * - Configurable failure thresholds and recovery timeouts * - Concurrency control during half-open testing * - Selective error handling via `shouldTripOnError` predicate * - Comprehensive callback system for monitoring and alerting * - Thread-safe operation * * @param fn - Function to protect with circuit breaker * @param opts - Configuration options for the circuit breaker * @returns Protected function that implements circuit breaker logic * * @see {@link https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern Circuit Breaker Design Pattern} * * @example * ```typescript * const unstableService = () => { * if (Math.random() > 0.7) throw new Error('Service failed'); * return 'Success'; * }; * * const protectedService = circuitBreakerSync(unstableService, { * maxFailures: 3, // Trip after 3 consecutive failures * resetAfter: 5000, // Test recovery after 5 seconds * onTripped: (error) => console.log('Circuit breaker tripped:', error.message), * onReset: () => console.log('Circuit breaker reset - service recovered') * }); * * // Usage * try { * const result = protectedService(); // May throw CircuitBreakerError if open * console.log(result); * } catch (error) { * if (error instanceof CircuitBreakerError) { * console.log('Circuit breaker is open - service unavailable'); * } else { * console.log('Service error:', error.message); * } * } * ``` */ export declare const circuitBreakerSync: (fn: T, opts?: CircuitBreakerOptions) => (...args: Parameters) => ReturnType | null | undefined; /** * Async circuit breaker that protects a function from failing too many times. * * Implements the Circuit Breaker design pattern to improve system resilience and fault tolerance * by preventing cascading failures in distributed systems. The circuit breaker monitors async * function calls and automatically "trips" (opens) when failures exceed a threshold, preventing * further calls to the failing function until it has time to recover. * * The circuit breaker operates in three states: * - **Closed**: Normal operation, all calls pass through. Failures are counted. * - **Open**: Circuit is tripped, all calls fail immediately without invoking the function. * - **Half-Open**: After a timeout, allows limited test calls to check if the service has recovered. * * Key features: * - Configurable failure thresholds and recovery timeouts * - Concurrency control during half-open testing * - Selective error handling via `shouldTripOnError` predicate * - Comprehensive callback system for monitoring and alerting * - Thread-safe operation for async environments * * @param fn - Async function to protect with circuit breaker * @param opts - Configuration options for the circuit breaker * @returns Protected async function that implements circuit breaker logic * * @see {@link https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern Circuit Breaker Design Pattern} * * @example * ```typescript * const unstableApiCall = async (url: string) => { * const response = await fetch(url); * if (!response.ok) throw new Error(`HTTP ${response.status}`); * return response.json(); * }; * * const protectedApiCall = circuitBreaker(unstableApiCall, { * maxFailures: 5, * resetAfter: 10000, * shouldTripOnError: (error) => { * // Only trip on server errors, not client errors * return error.message.includes('HTTP 5') || error.name === 'NetworkError'; * }, * onTripped: (error, store) => { * console.log(`Circuit breaker tripped after ${store.failures} failures`); * }, * onHalfOpen: () => console.log('Testing service recovery...'), * onReset: () => console.log('Service recovered - circuit breaker reset') * }); * * // Usage * try { * const data = await protectedApiCall('/api/users'); * console.log('API response:', data); * } catch (error) { * if (error instanceof CircuitBreakerError) { * console.log('API temporarily unavailable - circuit breaker is open'); * // Implement fallback logic here * } else { * console.log('API error:', error.message); * } * } * ``` */ export declare const circuitBreaker: (fn: T, opts?: CircuitBreakerOptions) => (...args: Parameters) => Promise | null | undefined>; export {};