/**
 * @module graceful-degradation
 * Enhanced Reliability Capabilities for xBind
 *
 * Provides graceful degradation mechanisms to maintain service continuity
 * when external services (registry, gateway, transport) experience issues.
 *
 * Features:
 * - Quality-of-Service (QoS) tiers for operation prioritization
 * - Fallback mechanisms with exponential backoff
 * - Intelligent caching with TTL
 * - User-friendly error messages with actionable recovery hints
 */
import type { Result } from '@private.me/shared';
import type { ACIErrorDetail } from '@private.me/ux-helpers';
import type { TrustRegistry } from './trust-registry.js';
import type { XailTransportAdapter } from './transport.js';
/**
 * Quality of Service levels for operations.
 *
 * Determines behavior when services are degraded:
 * - CRITICAL: Must succeed, fail fast if unavailable
 * - HIGH: Retry with aggressive backoff, use cache if fresh
 * - NORMAL: Retry with standard backoff, use stale cache if necessary
 * - LOW: Skip retries, use cache regardless of staleness
 */
export type QoSLevel = 'CRITICAL' | 'HIGH' | 'NORMAL' | 'LOW';
/**
 * Operation metadata for QoS decisions.
 */
export interface OperationContext {
    /** Unique operation identifier for correlation. */
    readonly operationId: string;
    /** Quality of service level. */
    readonly qos: QoSLevel;
    /** Operation type (e.g., 'registry:lookup', 'gateway:call', 'transport:send'). */
    readonly type: string;
    /** Optional timeout override in milliseconds. */
    readonly timeoutMs?: number;
}
/**
 * Cache entry with TTL and staleness tracking.
 */
interface CacheEntry<T> {
    /** Cached value. */
    readonly value: T;
    /** Timestamp when entry was created (ms since epoch). */
    readonly cachedAt: number;
    /** Time-to-live in milliseconds. */
    readonly ttl: number;
    /** Number of times this stale entry has been used. */
    usageCount: number;
}
/**
 * Cache configuration options.
 */
export interface CacheConfig {
    /** Default TTL for cache entries (milliseconds). Default: 300000 (5 minutes). */
    readonly defaultTTL?: number;
    /** Maximum cache size (entries). Default: 1000. */
    readonly maxSize?: number;
    /** Allow stale cache usage for LOW/NORMAL QoS. Default: true. */
    readonly allowStale?: boolean;
    /** Maximum staleness allowed (milliseconds). Default: 3600000 (1 hour). */
    readonly maxStaleMs?: number;
}
/**
 * Retry configuration for fallback operations.
 */
export interface RetryConfig {
    /** Maximum retry attempts. Default: 3. */
    readonly maxAttempts?: number;
    /** Initial delay in milliseconds. Default: 1000. */
    readonly initialDelayMs?: number;
    /** Backoff multiplier. Default: 2. */
    readonly backoffMultiplier?: number;
    /** Maximum delay in milliseconds. Default: 30000. */
    readonly maxDelayMs?: number;
    /** Enable jitter (randomize delays). Default: true. */
    readonly jitter?: boolean;
}
/**
 * Service health status.
 */
type ServiceHealth = 'HEALTHY' | 'DEGRADED' | 'UNAVAILABLE';
/**
 * Service health tracking.
 */
interface ServiceStatus {
    /** Current health status. */
    health: ServiceHealth;
    /** Last successful operation timestamp. */
    lastSuccess: number;
    /** Consecutive failure count. */
    failureCount: number;
    /** Last error encountered. */
    lastError?: string;
}
/**
 * Graceful Degradation Manager
 *
 * Coordinates fallback mechanisms, caching, and retry logic across
 * registry, gateway, and transport layers.
 */
export declare class GracefulDegradationManager {
    private readonly cacheConfig;
    private readonly retryConfig;
    private readonly cache;
    private readonly serviceStatus;
    constructor(cacheConfig?: CacheConfig, retryConfig?: RetryConfig);
    /**
     * Get cached value if available and valid for the given QoS level.
     *
     * @param key Cache key
     * @param qos Quality of service level
     * @returns Cached value or undefined
     */
    getCached<T>(key: string, qos: QoSLevel): T | undefined;
    /**
     * Store value in cache with TTL.
     *
     * @param key Cache key
     * @param value Value to cache
     * @param ttl Time-to-live in milliseconds (uses default if omitted)
     */
    setCached<T>(key: string, value: T, ttl?: number): void;
    /**
     * Invalidate cached entry.
     *
     * @param key Cache key
     */
    invalidate(key: string): void;
    /**
     * Clear all cached entries.
     */
    clearCache(): void;
    /**
     * Get cache statistics.
     */
    getCacheStats(): {
        size: number;
        maxSize: number;
        entries: Array<{
            key: string;
            age: number;
            usageCount: number;
        }>;
    };
    /**
     * Record successful operation for a service.
     *
     * @param serviceName Service identifier (e.g., 'registry', 'gateway', 'transport')
     */
    recordSuccess(serviceName: string): void;
    /**
     * Record failed operation for a service.
     *
     * @param serviceName Service identifier
     * @param error Error message
     */
    recordFailure(serviceName: string, error: string): void;
    /**
     * Get service health status.
     *
     * @param serviceName Service identifier
     * @returns Service health status
     */
    getServiceHealth(serviceName: string): ServiceHealth;
    /**
     * Get detailed service status.
     *
     * @param serviceName Service identifier
     * @returns Service status or undefined if not tracked
     */
    getServiceStatus(serviceName: string): ServiceStatus | undefined;
    /**
     * Reset service health tracking.
     *
     * @param serviceName Service identifier (all services if omitted)
     */
    resetServiceHealth(serviceName?: string): void;
    /**
     * Execute operation with retry logic based on QoS level.
     *
     * @param operation Async operation to execute
     * @param context Operation context with QoS level
     * @returns Result of operation
     */
    withRetry<T, E>(operation: () => Promise<Result<T, E>>, context: OperationContext): Promise<Result<T, E>>;
    /**
     * Get maximum retry attempts for QoS level.
     */
    private getMaxAttempts;
    /**
     * Calculate exponential backoff delay with optional jitter.
     */
    private calculateBackoff;
    /**
     * Sleep for specified milliseconds.
     */
    private sleep;
}
/**
 * Registry lookup with graceful degradation.
 *
 * Provides intelligent fallback for DID resolution:
 * 1. Try primary registry lookup
 * 2. On failure, check cache based on QoS level
 * 3. Return user-friendly error if all fallbacks exhausted
 *
 * @param registry Trust registry instance
 * @param did DID to resolve
 * @param context Operation context
 * @param manager Degradation manager
 * @returns Registry lookup result
 */
export declare function registryLookupWithFallback(registry: TrustRegistry, did: string, context: OperationContext, manager: GracefulDegradationManager): Promise<Result<{
    publicKey: string;
    endpoint?: string;
}, ACIErrorDetail>>;
/**
 * Send envelope with transport fallback.
 *
 * Tries multiple transports in order until one succeeds:
 * 1. Primary transport with retry
 * 2. Fallback transports (if configured)
 * 3. Return detailed error if all transports fail
 *
 * @param transports Array of transport adapters
 * @param envelope Envelope to send
 * @param recipientDid Recipient DID
 * @param context Operation context
 * @param manager Degradation manager
 * @returns Send result
 */
export declare function sendWithTransportFallback(transports: XailTransportAdapter[], envelope: unknown, recipientDid: string, context: OperationContext, manager: GracefulDegradationManager): Promise<Result<void, ACIErrorDetail>>;
/**
 * Enhance error with QoS-appropriate messaging.
 *
 * @param error Original error
 * @param context Operation context
 * @param manager Degradation manager
 * @returns Enhanced error with actionable hints
 */
export declare function enhanceError(error: ACIErrorDetail, context: OperationContext, manager: GracefulDegradationManager): ACIErrorDetail;
export type { CacheEntry, ServiceStatus };
