/**
 * @module retry-strategies
 * Configurable retry strategies for enhanced reliability.
 *
 * Provides flexible retry policies with exponential backoff, jitter, circuit breakers,
 * and error-specific retry logic. Designed for production-grade fault tolerance.
 *
 * @example
 * ```typescript
 * import { RetryStrategy, CircuitBreaker } from '@private.me/xbind/retry-strategies';
 *
 * // Exponential backoff with circuit breaker
 * const strategy = RetryStrategy.exponentialBackoff({
 *   maxAttempts: 5,
 *   initialDelayMs: 1000,
 *   maxDelayMs: 30000,
 *   multiplier: 2,
 *   jitter: true
 * });
 *
 * const circuitBreaker = new CircuitBreaker({
 *   failureThreshold: 5,
 *   resetTimeoutMs: 60000
 * });
 * ```
 */
import type { Result } from '@private.me/shared';
import type { TransportError } from './transport.js';
/**
 * Retry context provides information about the current retry attempt.
 */
export interface RetryContext {
    /** Current attempt number (0-indexed) */
    readonly attempt: number;
    /** Error from the previous attempt */
    readonly error: TransportError;
    /** Timestamp of the first attempt */
    readonly startTime: number;
    /** Total elapsed time since first attempt (ms) */
    readonly elapsedMs: number;
    /** Additional metadata */
    readonly metadata?: Record<string, unknown>;
}
/**
 * Result of a retry decision.
 */
export interface RetryDecision {
    /** Whether to retry the operation */
    readonly shouldRetry: boolean;
    /** Delay before next retry (ms), if shouldRetry is true */
    readonly delayMs?: number;
    /** Reason for the decision (for logging/debugging) */
    readonly reason?: string;
}
/**
 * Configuration for exponential backoff retry strategy.
 */
export interface ExponentialBackoffConfig {
    /** Maximum number of retry attempts (default: 3) */
    maxAttempts?: number;
    /** Initial delay in milliseconds (default: 1000) */
    initialDelayMs?: number;
    /** Maximum delay cap in milliseconds (default: 30000) */
    maxDelayMs?: number;
    /** Backoff multiplier (default: 2) */
    multiplier?: number;
    /** Enable jitter randomization (default: true) */
    jitter?: boolean;
    /** Maximum jitter percentage (0-1, default: 0.2 = ±20%) */
    jitterFactor?: number;
    /** Only retry on specific errors (default: all errors) */
    retryableErrors?: ReadonlyArray<TransportError>;
}
/**
 * Configuration for linear backoff retry strategy.
 */
export interface LinearBackoffConfig {
    /** Maximum number of retry attempts (default: 3) */
    maxAttempts?: number;
    /** Fixed delay increment in milliseconds (default: 1000) */
    delayIncrementMs?: number;
    /** Initial delay in milliseconds (default: 1000) */
    initialDelayMs?: number;
    /** Maximum delay cap in milliseconds (default: 30000) */
    maxDelayMs?: number;
    /** Enable jitter randomization (default: true) */
    jitter?: boolean;
    /** Maximum jitter percentage (0-1, default: 0.1 = ±10%) */
    jitterFactor?: number;
    /** Only retry on specific errors (default: all errors) */
    retryableErrors?: ReadonlyArray<TransportError>;
}
/**
 * Configuration for fixed delay retry strategy.
 */
export interface FixedDelayConfig {
    /** Maximum number of retry attempts (default: 3) */
    maxAttempts?: number;
    /** Fixed delay in milliseconds (default: 1000) */
    delayMs?: number;
    /** Enable jitter randomization (default: false) */
    jitter?: boolean;
    /** Maximum jitter percentage (0-1, default: 0.1 = ±10%) */
    jitterFactor?: number;
    /** Only retry on specific errors (default: all errors) */
    retryableErrors?: ReadonlyArray<TransportError>;
}
/**
 * Configuration for circuit breaker.
 */
export interface CircuitBreakerConfig {
    /** Number of consecutive failures before opening circuit (default: 5) */
    failureThreshold?: number;
    /** Time to wait before attempting to close circuit (ms, default: 60000) */
    resetTimeoutMs?: number;
    /** Number of successful requests needed to close circuit (default: 2) */
    successThreshold?: number;
    /** Time window for counting failures (ms, default: 60000) */
    windowMs?: number;
}
/**
 * Circuit breaker states.
 */
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
/**
 * Statistics for circuit breaker monitoring.
 */
export interface CircuitBreakerStats {
    /** Current circuit state */
    readonly state: CircuitState;
    /** Number of consecutive failures */
    readonly consecutiveFailures: number;
    /** Number of consecutive successes in HALF_OPEN state */
    readonly consecutiveSuccesses: number;
    /** Timestamp when circuit was opened (if open) */
    readonly openedAt?: number;
    /** Total requests attempted */
    readonly totalRequests: number;
    /** Total failures */
    readonly totalFailures: number;
    /** Total successes */
    readonly totalSuccesses: number;
}
/**
 * Core retry strategy interface.
 *
 * Implementations determine retry behavior based on context.
 */
export interface IRetryStrategy {
    /**
     * Decide whether to retry the operation.
     *
     * @param context - Current retry context
     * @returns Retry decision with delay
     */
    shouldRetry(context: RetryContext): RetryDecision;
    /**
     * Get strategy name for logging.
     */
    readonly name: string;
}
/**
 * Exponential backoff retry strategy.
 *
 * Delay formula: min(initialDelay * multiplier^attempt, maxDelay) ± jitter
 *
 * Best for: Network requests, API calls, database operations.
 * Avoids overwhelming failing services with exponentially increasing delays.
 */
export declare class ExponentialBackoffStrategy implements IRetryStrategy {
    readonly name = "ExponentialBackoff";
    private readonly maxAttempts;
    private readonly initialDelayMs;
    private readonly maxDelayMs;
    private readonly multiplier;
    private readonly jitter;
    private readonly jitterFactor;
    private readonly retryableErrors;
    constructor(config?: ExponentialBackoffConfig);
    shouldRetry(context: RetryContext): RetryDecision;
    private applyJitter;
}
/**
 * Linear backoff retry strategy.
 *
 * Delay formula: min(initialDelay + attempt * increment, maxDelay) ± jitter
 *
 * Best for: Rate-limited APIs, gradual load recovery.
 * More predictable than exponential, suitable when service recovery is linear.
 */
export declare class LinearBackoffStrategy implements IRetryStrategy {
    readonly name = "LinearBackoff";
    private readonly maxAttempts;
    private readonly delayIncrementMs;
    private readonly initialDelayMs;
    private readonly maxDelayMs;
    private readonly jitter;
    private readonly jitterFactor;
    private readonly retryableErrors;
    constructor(config?: LinearBackoffConfig);
    shouldRetry(context: RetryContext): RetryDecision;
    private applyJitter;
}
/**
 * Fixed delay retry strategy.
 *
 * Delay formula: delayMs ± jitter (constant for all attempts)
 *
 * Best for: Simple retry scenarios, testing.
 * Predictable timing, no backoff complexity.
 */
export declare class FixedDelayStrategy implements IRetryStrategy {
    readonly name = "FixedDelay";
    private readonly maxAttempts;
    private readonly delayMs;
    private readonly jitter;
    private readonly jitterFactor;
    private readonly retryableErrors;
    constructor(config?: FixedDelayConfig);
    shouldRetry(context: RetryContext): RetryDecision;
    private applyJitter;
}
/**
 * No retry strategy (fail immediately).
 *
 * Best for: Operations that must succeed on first try, testing.
 */
export declare class NoRetryStrategy implements IRetryStrategy {
    readonly name = "NoRetry";
    shouldRetry(_context: RetryContext): RetryDecision;
}
/**
 * Circuit breaker for preventing cascading failures.
 *
 * States:
 * - CLOSED: Normal operation, requests pass through
 * - OPEN: Circuit tripped, requests fail immediately
 * - HALF_OPEN: Testing recovery, limited requests allowed
 *
 * Best practices:
 * - Use with retry strategies for comprehensive fault tolerance
 * - Monitor circuit state changes for alerting
 * - Tune thresholds based on service characteristics
 *
 * @example
 * ```typescript
 * const breaker = new CircuitBreaker({
 *   failureThreshold: 5,
 *   resetTimeoutMs: 60000,
 *   successThreshold: 2
 * });
 *
 * // Check before operation
 * if (breaker.allowRequest()) {
 *   const result = await operation();
 *   if (result.ok) {
 *     breaker.recordSuccess();
 *   } else {
 *     breaker.recordFailure();
 *   }
 * }
 * ```
 */
export declare class CircuitBreaker {
    private state;
    private consecutiveFailures;
    private consecutiveSuccesses;
    private openedAt?;
    private totalRequests;
    private totalFailures;
    private totalSuccesses;
    private failureTimestamps;
    private readonly failureThreshold;
    private readonly resetTimeoutMs;
    private readonly successThreshold;
    private readonly windowMs;
    constructor(config?: CircuitBreakerConfig);
    /**
     * Check if request should be allowed through circuit.
     *
     * @returns True if request should proceed, false if circuit is open
     */
    allowRequest(): boolean;
    /**
     * Record a successful operation.
     */
    recordSuccess(): void;
    /**
     * Record a failed operation.
     */
    recordFailure(): void;
    /**
     * Get current circuit breaker statistics.
     */
    getStats(): CircuitBreakerStats;
    /**
     * Reset circuit breaker to initial state.
     */
    reset(): void;
    /**
     * Force circuit to open (for testing or manual intervention).
     */
    forceOpen(): void;
    /**
     * Force circuit to close (for testing or manual recovery).
     */
    forceClose(): void;
}
/**
 * Factory for creating retry strategies with common configurations.
 */
export declare class RetryStrategy {
    /**
     * Create exponential backoff strategy.
     *
     * @param config - Configuration options
     * @returns Exponential backoff strategy
     */
    static exponentialBackoff(config?: ExponentialBackoffConfig): IRetryStrategy;
    /**
     * Create linear backoff strategy.
     *
     * @param config - Configuration options
     * @returns Linear backoff strategy
     */
    static linearBackoff(config?: LinearBackoffConfig): IRetryStrategy;
    /**
     * Create fixed delay strategy.
     *
     * @param config - Configuration options
     * @returns Fixed delay strategy
     */
    static fixedDelay(config?: FixedDelayConfig): IRetryStrategy;
    /**
     * Create no retry strategy (fail immediately).
     *
     * @returns No retry strategy
     */
    static noRetry(): IRetryStrategy;
    /**
     * Create aggressive retry strategy for critical operations.
     *
     * Config: 5 attempts, 500ms initial, max 10s, exponential backoff.
     *
     * @returns Aggressive retry strategy
     */
    static aggressive(): IRetryStrategy;
    /**
     * Create conservative retry strategy for non-critical operations.
     *
     * Config: 2 attempts, 2s initial, max 5s, linear backoff.
     *
     * @returns Conservative retry strategy
     */
    static conservative(): IRetryStrategy;
    /**
     * Create default retry strategy (balanced).
     *
     * Config: 3 attempts, 1s initial, max 30s, exponential backoff.
     *
     * @returns Default retry strategy
     */
    static default(): IRetryStrategy;
}
/**
 * Execute an operation with retry strategy and optional circuit breaker.
 *
 * @param operation - Async operation to execute
 * @param strategy - Retry strategy to use
 * @param circuitBreaker - Optional circuit breaker
 * @returns Result of the operation
 *
 * @example
 * ```typescript
 * const result = await executeWithRetry(
 *   async () => transport.send(envelope, did),
 *   RetryStrategy.exponentialBackoff(),
 *   circuitBreaker
 * );
 * ```
 */
export declare function executeWithRetry<T>(operation: () => Promise<Result<T, TransportError>>, strategy: IRetryStrategy, circuitBreaker?: CircuitBreaker): Promise<Result<T, TransportError>>;
