/**
 * Circuit Breaker pattern implementation for distributed systems
 *
 * Provides resilience for external service calls by:
 * - Tracking failure rates and opening the circuit when threshold is exceeded
 * - Failing fast when circuit is open to prevent cascading failures
 * - Testing recovery with half-open state after reset timeout
 *
 * State transitions:
 * CLOSED -> OPEN: When failure count reaches threshold
 * OPEN -> HALF_OPEN: After reset timeout expires
 * HALF_OPEN -> CLOSED: On successful call
 * HALF_OPEN -> OPEN: On failed call
 *
 * Per-service configurations allow tuning circuit breaker behavior
 * based on service characteristics (e.g., database vs. webhook).
 */
import type { Redis } from 'ioredis';
/**
 * Circuit breaker states
 */
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
/**
 * Per-service circuit breaker configuration
 */
export interface CircuitBreakerConfig {
    /** Service name identifier */
    name: string;
    /** Number of failures before opening the circuit */
    failureThreshold: number;
    /** Time in ms before attempting to close the circuit */
    resetTimeoutMs: number;
    /** Maximum attempts in half-open state before reopening */
    halfOpenMaxAttempts: number;
    /** Time window in ms to monitor for failures */
    monitorWindowMs: number;
}
/**
 * Default configurations per service type.
 * These can be overridden via environment variables in config.ts.
 */
export declare const CIRCUIT_BREAKER_CONFIGS: Record<string, CircuitBreakerConfig>;
/**
 * Circuit breaker configuration options
 */
export interface CircuitBreakerOptions {
    /** Unique name for this circuit breaker (used as Redis key prefix) */
    name: string;
    /** Number of failures before opening the circuit (default: 5) */
    failureThreshold?: number;
    /** Time in ms before attempting to close the circuit (default: 30000) */
    resetTimeoutMs?: number;
    /** Maximum attempts in half-open state before reopening (default: 3) */
    halfOpenMaxAttempts?: number;
    /** Time window in ms to monitor for failures (default: 60000) */
    monitorWindowMs?: number;
    /** Optional Redis client (uses shared client if not provided) */
    redis?: Redis;
    /** Callback when circuit state changes */
    onStateChange?: (from: CircuitState, to: CircuitState, breaker: CircuitBreaker) => void;
}
/**
 * Result of circuit breaker execution
 */
export interface CircuitBreakerResult<T> {
    success: boolean;
    result?: T;
    error?: Error;
    circuitOpen: boolean;
}
/**
 * Circuit Breaker implementation with Redis-backed state for distributed systems
 *
 * @example
 * ```typescript
 * const breaker = new CircuitBreaker({
 *   name: 'policy-evaluator',
 *   failureThreshold: 5,
 *   resetTimeoutMs: 30000,
 * });
 *
 * const result = await breaker.execute(async () => {
 *   return await policyEvaluator.evaluateMultiple(policies, context);
 * });
 *
 * if (result.circuitOpen) {
 *   // Use fallback logic
 * }
 * ```
 */
export declare class CircuitBreaker {
    private readonly name;
    private readonly failureThreshold;
    private readonly resetTimeoutMs;
    private readonly halfOpenMaxAttempts;
    private readonly monitorWindowMs;
    private readonly redis;
    private readonly onStateChange?;
    private localStateCache;
    private localStateCacheTime;
    private readonly localStateCacheTtlMs;
    constructor(options: CircuitBreakerOptions);
    /**
     * Get Redis key for this circuit breaker
     */
    private getRedisKey;
    /**
     * Get the current state from Redis
     */
    private getState;
    /**
     * Save state to Redis
     */
    private setState;
    /**
     * Get the current circuit state
     */
    getCircuitState(): Promise<CircuitState>;
    /**
     * Check if the circuit is currently open (failing fast)
     */
    isOpen(): Promise<boolean>;
    /**
     * Record a successful call
     */
    recordSuccess(): Promise<void>;
    /**
     * Record a failed call
     */
    recordFailure(): Promise<void>;
    /**
     * Execute a function with circuit breaker protection
     *
     * @param fn - The function to execute
     * @returns Result including whether circuit was open
     */
    execute<T>(fn: () => Promise<T>): Promise<CircuitBreakerResult<T>>;
    /**
     * Force the circuit to open state
     * Useful for manual intervention or testing
     */
    forceOpen(): Promise<void>;
    /**
     * Force the circuit to closed state
     * Useful for manual intervention or testing
     */
    forceClose(): Promise<void>;
    /**
     * Reset the circuit breaker state completely
     */
    reset(): Promise<void>;
    /**
     * Get detailed status information for monitoring
     */
    getStatus(): Promise<{
        name: string;
        state: CircuitState;
        failureCount: number;
        failureThreshold: number;
        resetTimeoutMs: number;
        halfOpenMaxAttempts: number;
        halfOpenAttempts: number;
        monitorWindowMs: number;
        lastFailureTime: Date | null;
        openedAt: Date | null;
        timeUntilReset: number | null;
        windowStartTime: Date | null;
    }>;
    /**
     * Notify state change callback
     */
    private notifyStateChange;
}
/**
 * Factory function to create a circuit breaker with common defaults
 */
export declare function createCircuitBreaker(options: CircuitBreakerOptions): CircuitBreaker;
/**
 * Set configuration overrides for circuit breakers.
 * This should be called during application initialization before any circuit breakers are used.
 *
 * @example
 * ```typescript
 * setCircuitBreakerConfigOverrides({
 *   database: { failureThreshold: 10, resetTimeoutMs: 60000 },
 *   redis: { failureThreshold: 20 },
 * });
 * ```
 */
export declare function setCircuitBreakerConfigOverrides(overrides: Record<string, Partial<CircuitBreakerConfig>>): void;
/**
 * Get or create a circuit breaker for a specific service.
 * Uses the default configuration for the service type, with optional overrides.
 *
 * @param serviceName - The name of the service (e.g., 'database', 'redis', 'webhook')
 * @param onStateChange - Optional callback for state changes
 * @returns The circuit breaker instance for the service
 *
 * @example
 * ```typescript
 * const dbBreaker = getCircuitBreaker('database');
 * const result = await dbBreaker.execute(async () => {
 *   return await db.query('SELECT * FROM users');
 * });
 * ```
 */
export declare function getCircuitBreaker(serviceName: string, onStateChange?: (from: CircuitState, to: CircuitState, breaker: CircuitBreaker) => void): CircuitBreaker;
/**
 * Get all registered circuit breakers with their current status.
 * Useful for health checks and monitoring dashboards.
 *
 * @returns Map of service names to their circuit breaker status
 */
export declare function getAllCircuitBreakerStatuses(): Promise<Map<string, Awaited<ReturnType<CircuitBreaker['getStatus']>>>>;
/**
 * Reset a specific circuit breaker by service name.
 * Useful for manual recovery during incidents.
 *
 * @param serviceName - The service name to reset
 * @returns True if the circuit breaker was found and reset
 */
export declare function resetCircuitBreaker(serviceName: string): Promise<boolean>;
/**
 * Clear all circuit breakers from the registry.
 * Primarily for testing purposes.
 */
export declare function clearCircuitBreakerRegistry(): void;
/**
 * Error thrown when a circuit breaker is open and blocking execution.
 * This error allows callers to distinguish circuit breaker rejections
 * from actual execution failures.
 */
export declare class CircuitBreakerOpenError extends Error {
    readonly serviceName: string;
    readonly circuitState: CircuitState;
    constructor(serviceName: string, circuitState?: CircuitState);
}
/**
 * Callback type for recording circuit breaker metrics.
 * This allows the circuit breaker module to emit metrics without
 * depending directly on the metrics module (avoiding circular deps).
 */
export type CircuitBreakerMetricsCallback = {
    recordStateChange: (serviceName: string, fromState: CircuitState, toState: CircuitState) => void;
    recordFailure: (serviceName: string) => void;
    recordSuccess: (serviceName: string) => void;
    updateState: (serviceName: string, state: CircuitState) => void;
};
/**
 * Set the metrics callback for circuit breaker operations.
 * This should be called during application initialization to wire up
 * Prometheus metrics without creating circular dependencies.
 *
 * @param callback - The metrics callback functions
 */
export declare function setCircuitBreakerMetricsCallback(callback: CircuitBreakerMetricsCallback): void;
/**
 * Execute a function with circuit breaker protection.
 *
 * This is a convenience wrapper that:
 * 1. Gets or creates the appropriate circuit breaker for the service
 * 2. Executes the function through the circuit breaker
 * 3. Records metrics for state changes, successes, and failures
 * 4. Throws CircuitBreakerOpenError when the circuit is open
 *
 * @param serviceName - The service name identifier (must match CIRCUIT_BREAKER_CONFIGS keys)
 * @param fn - The async function to execute
 * @returns The result of the function
 * @throws CircuitBreakerOpenError when the circuit is open
 * @throws The original error if the function fails
 *
 * @example
 * ```typescript
 * // Protect a database call
 * const result = await withCircuitBreaker('database', async () => {
 *   return await db.query('SELECT * FROM users WHERE id = $1', [userId]);
 * });
 *
 * // Protect an external API call
 * try {
 *   const data = await withCircuitBreaker('gdprService', async () => {
 *     return await gdprApi.exportUserData(userId);
 *   });
 * } catch (error) {
 *   if (error instanceof CircuitBreakerOpenError) {
 *     // Handle circuit open - use fallback or return cached data
 *     return cachedData;
 *   }
 *   throw error;
 * }
 * ```
 */
export declare function withCircuitBreaker<T>(serviceName: string, fn: () => Promise<T>): Promise<T>;
/**
 * Execute a function with circuit breaker protection, returning a result object
 * instead of throwing on circuit open.
 *
 * This variant is useful when you want to handle circuit open gracefully
 * without try/catch.
 *
 * @param serviceName - The service name identifier
 * @param fn - The async function to execute
 * @returns Result object with success flag, result/error, and circuitOpen indicator
 *
 * @example
 * ```typescript
 * const result = await withCircuitBreakerResult('auditService', async () => {
 *   return await auditService.record(event);
 * });
 *
 * if (result.circuitOpen) {
 *   // Queue for retry later
 *   await queueForRetry(event);
 * } else if (!result.success) {
 *   logger.error({ error: result.error }, 'Audit failed');
 * }
 * ```
 */
export declare function withCircuitBreakerResult<T>(serviceName: string, fn: () => Promise<T>): Promise<CircuitBreakerResult<T>>;
//# sourceMappingURL=circuit-breaker.d.ts.map