/**
 * @module circuit-breaker
 * Circuit breaker pattern for enhanced fault tolerance
 *
 * Protects external service calls (registry, gateway, S3) from cascading failures
 * by automatically opening circuits after repeated failures and closing them after
 * recovery periods.
 *
 * Architecture:
 * - CLOSED: Normal operation, all requests pass through
 * - OPEN: Circuit tripped, fast-fail all requests without calling service
 * - HALF_OPEN: Testing recovery, allow limited requests to probe service health
 *
 * Features:
 * - Automatic state transitions based on failure thresholds
 * - Exponential backoff for recovery attempts
 * - Per-service circuit isolation
 * - Metrics integration for monitoring
 * - Type-safe error handling
 *
 * @example
 * ```typescript
 * const breaker = new CircuitBreaker({
 *   failureThreshold: 5,
 *   recoveryTimeout: 60000,
 *   halfOpenMaxCalls: 3,
 * });
 *
 * const result = await breaker.execute(async () => {
 *   return await registryClient.lookup(did);
 * });
 * ```
 */
import type { Result } from '@private.me/shared';
/**
 * Circuit breaker state.
 *
 * - CLOSED: Normal operation, requests pass through
 * - OPEN: Circuit tripped, fail fast without calling service
 * - HALF_OPEN: Recovery testing, allow limited probes
 */
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
/**
 * Circuit breaker configuration options.
 */
export interface CircuitBreakerOptions {
    /**
     * Number of consecutive failures before opening circuit.
     * @default 5
     */
    readonly failureThreshold?: number;
    /**
     * Time in milliseconds to wait before transitioning from OPEN to HALF_OPEN.
     * @default 60000 (1 minute)
     */
    readonly recoveryTimeout?: number;
    /**
     * Maximum number of requests allowed in HALF_OPEN state before closing circuit.
     * @default 3
     */
    readonly halfOpenMaxCalls?: number;
    /**
     * Number of successful calls in HALF_OPEN state required to close circuit.
     * @default 2
     */
    readonly successThreshold?: number;
    /**
     * Optional name for this circuit (used in metrics and logging).
     * @default 'default'
     */
    readonly name?: string;
    /**
     * Optional callback invoked on state transitions.
     */
    readonly onStateChange?: (from: CircuitState, to: CircuitState, reason: string) => void;
    /**
     * Optional callback invoked when circuit opens.
     */
    readonly onOpen?: (reason: string) => void;
    /**
     * Optional callback invoked when circuit closes.
     */
    readonly onClose?: () => void;
    /**
     * Optional callback invoked when circuit enters half-open state.
     */
    readonly onHalfOpen?: () => void;
}
/**
 * Circuit breaker metrics.
 */
export interface CircuitBreakerMetrics {
    /** Current circuit state */
    readonly state: CircuitState;
    /** Total number of successful calls */
    readonly successCount: number;
    /** Total number of failed calls */
    readonly failureCount: number;
    /** Total number of rejected calls (circuit open) */
    readonly rejectedCount: number;
    /** Consecutive failures in current state */
    readonly consecutiveFailures: number;
    /** Consecutive successes in HALF_OPEN state */
    readonly consecutiveSuccesses: number;
    /** Timestamp when circuit last opened (undefined if never opened) */
    readonly lastOpenedAt?: number;
    /** Timestamp when circuit last closed (undefined if never closed) */
    readonly lastClosedAt?: number;
    /** Circuit name */
    readonly name: string;
}
/**
 * Error codes for circuit breaker failures.
 */
export type CircuitBreakerError = 'CIRCUIT_OPEN' | 'HALF_OPEN_LIMIT_EXCEEDED' | 'EXECUTION_FAILED' | 'TIMEOUT';
/**
 * Circuit breaker for protecting external service calls.
 *
 * Implements the circuit breaker pattern to prevent cascading failures
 * when external services (registry, gateway, S3) become unavailable.
 *
 * State transitions:
 * - CLOSED → OPEN: After failureThreshold consecutive failures
 * - OPEN → HALF_OPEN: After recoveryTimeout milliseconds
 * - HALF_OPEN → CLOSED: After successThreshold successful calls
 * - HALF_OPEN → OPEN: On any failure
 *
 * @example
 * ```typescript
 * // Create circuit breaker for registry calls
 * const registryBreaker = new CircuitBreaker({
 *   name: 'registry',
 *   failureThreshold: 5,
 *   recoveryTimeout: 60000,
 * });
 *
 * // Execute protected call
 * const result = await registryBreaker.execute(async () => {
 *   return await registry.lookup(did);
 * });
 *
 * if (!result.ok) {
 *   console.error('Circuit breaker error:', result.error);
 * }
 * ```
 */
export declare class CircuitBreaker {
    private state;
    private consecutiveFailures;
    private consecutiveSuccesses;
    private successCount;
    private failureCount;
    private rejectedCount;
    private lastOpenedAt?;
    private lastClosedAt?;
    private recoveryTimer?;
    private readonly failureThreshold;
    private readonly recoveryTimeout;
    private readonly halfOpenMaxCalls;
    private readonly successThreshold;
    private readonly name;
    private readonly onStateChange?;
    private readonly onOpen?;
    private readonly onClose?;
    private readonly onHalfOpen?;
    /**
     * Create a new circuit breaker.
     *
     * @param options - Circuit breaker configuration
     */
    constructor(options?: CircuitBreakerOptions);
    /**
     * Execute a function with circuit breaker protection.
     *
     * If the circuit is OPEN, immediately returns an error without calling the function.
     * If the circuit is HALF_OPEN, limits the number of concurrent calls.
     * If the circuit is CLOSED, executes the function normally.
     *
     * @param fn - Async function to execute
     * @returns Result of function execution or circuit breaker error
     */
    execute<T>(fn: () => Promise<T>): Promise<Result<T, CircuitBreakerError | string>>;
    /**
     * Get current circuit breaker metrics.
     *
     * @returns Current metrics snapshot
     */
    getMetrics(): CircuitBreakerMetrics;
    /**
     * Get current circuit state.
     *
     * @returns Current state (CLOSED, OPEN, or HALF_OPEN)
     */
    getState(): CircuitState;
    /**
     * Manually reset the circuit breaker to CLOSED state.
     *
     * Useful for testing or manual recovery scenarios.
     * Clears all counters and timers.
     */
    reset(): void;
    /**
     * Manually open the circuit breaker.
     *
     * Useful for maintenance windows or manual intervention.
     *
     * @param reason - Optional reason for opening circuit
     */
    forceOpen(reason?: string): void;
    /**
     * Dispose of the circuit breaker and clean up resources.
     *
     * Clears any pending recovery timers.
     */
    dispose(): void;
    /**
     * Handle successful execution.
     */
    private onSuccess;
    /**
     * Handle failed execution.
     *
     * @param _error - Error that occurred (unused but kept for potential future logging)
     */
    private onFailure;
    /**
     * Transition to a new state.
     *
     * @param newState - Target state
     * @param reason - Reason for transition
     */
    private transitionTo;
    /**
     * Schedule automatic recovery from OPEN to HALF_OPEN state.
     */
    private scheduleRecovery;
    /**
     * Clear any pending recovery timer.
     */
    private clearRecoveryTimer;
}
/**
 * Create a circuit breaker configured for registry operations.
 *
 * Registry operations have:
 * - Higher failure threshold (10) - registry is critical, tolerate transient failures
 * - Longer recovery timeout (2 minutes) - DNS/network issues take time
 * - More half-open probes (5) - verify stability before full recovery
 *
 * @param options - Optional overrides
 * @returns Configured circuit breaker for registry calls
 */
export declare function createRegistryCircuitBreaker(options?: Partial<CircuitBreakerOptions>): CircuitBreaker;
/**
 * Create a circuit breaker configured for gateway operations.
 *
 * Gateway operations have:
 * - Medium failure threshold (5) - gateway should be reliable
 * - Standard recovery timeout (1 minute)
 * - Standard half-open probes (3)
 *
 * @param options - Optional overrides
 * @returns Configured circuit breaker for gateway calls
 */
export declare function createGatewayCircuitBreaker(options?: Partial<CircuitBreakerOptions>): CircuitBreaker;
/**
 * Create a circuit breaker configured for S3 storage operations.
 *
 * S3 operations have:
 * - Lower failure threshold (3) - storage failures are serious
 * - Shorter recovery timeout (30 seconds) - AWS S3 recovers quickly
 * - Fewer half-open probes (2) - S3 is usually reliable
 *
 * @param options - Optional overrides
 * @returns Configured circuit breaker for S3 calls
 */
export declare function createS3CircuitBreaker(options?: Partial<CircuitBreakerOptions>): CircuitBreaker;
/**
 * Manages multiple circuit breakers for different services.
 *
 * Provides centralized access to service-specific circuit breakers
 * and aggregated metrics across all circuits.
 *
 * @example
 * ```typescript
 * const manager = new CircuitBreakerManager();
 *
 * // Execute registry call with protection
 * const result = await manager.executeRegistry(async () => {
 *   return await registry.lookup(did);
 * });
 *
 * // Get all metrics
 * const metrics = manager.getAllMetrics();
 * console.log('Registry state:', metrics.registry.state);
 * ```
 */
export declare class CircuitBreakerManager {
    private readonly breakers;
    constructor();
    /**
     * Execute a function with registry circuit breaker protection.
     *
     * @param fn - Async function to execute
     * @returns Result of function execution or circuit breaker error
     */
    executeRegistry<T>(fn: () => Promise<T>): Promise<Result<T, CircuitBreakerError | string>>;
    /**
     * Execute a function with gateway circuit breaker protection.
     *
     * @param fn - Async function to execute
     * @returns Result of function execution or circuit breaker error
     */
    executeGateway<T>(fn: () => Promise<T>): Promise<Result<T, CircuitBreakerError | string>>;
    /**
     * Execute a function with S3 circuit breaker protection.
     *
     * @param fn - Async function to execute
     * @returns Result of function execution or circuit breaker error
     */
    executeS3<T>(fn: () => Promise<T>): Promise<Result<T, CircuitBreakerError | string>>;
    /**
     * Get metrics for a specific circuit breaker.
     *
     * @param name - Circuit breaker name
     * @returns Metrics or undefined if breaker not found
     */
    getMetrics(name: string): CircuitBreakerMetrics | undefined;
    /**
     * Get metrics for all circuit breakers.
     *
     * @returns Map of circuit name to metrics
     */
    getAllMetrics(): Record<string, CircuitBreakerMetrics>;
    /**
     * Get or create a custom circuit breaker.
     *
     * @param name - Circuit breaker name
     * @param options - Optional configuration (used only on first access)
     * @returns Circuit breaker instance
     */
    getOrCreate(name: string, options?: CircuitBreakerOptions): CircuitBreaker;
    /**
     * Reset all circuit breakers to CLOSED state.
     */
    resetAll(): void;
    /**
     * Dispose of all circuit breakers and clean up resources.
     */
    dispose(): void;
}
