import { CircuitState, CircuitBreakerConfig } from '../utils/resilience'; /** * Service health status */ export type ServiceHealth = 'healthy' | 'degraded' | 'unhealthy' | 'unknown'; /** * Service configuration extending circuit breaker config */ export interface ServiceConfig extends CircuitBreakerConfig { /** Unique service name */ name: string; /** Service base URL */ baseUrl?: string; /** Health check endpoint (relative to baseUrl) */ healthCheckEndpoint?: string; /** Health check interval in ms */ healthCheckInterval?: number; /** Fallback function when circuit is open */ fallback?: () => T | Promise; /** Whether to start health checks automatically */ autoStartHealthChecks?: boolean; /** Custom health check function */ customHealthCheck?: () => Promise; } /** * Service status for monitoring */ export interface ServiceStatus { /** Service name */ name: string; /** Current health status */ health: ServiceHealth; /** Circuit breaker state */ circuitState: CircuitState; /** Last health check time */ lastCheck: Date | null; /** Last error message if any */ lastError: string | null; /** Success rate (0-1) */ successRate: number; /** Average response time in ms */ avgResponseTime: number; /** Total request count */ requestCount: number; } /** * Service state change event */ export interface ServiceStateChangeEvent { service: string; from: CircuitState; to: CircuitState; health: ServiceHealth; } /** * Circuit breaker for a specific service with health monitoring * * @example * ```tsx * const apiBreaker = new ServiceCircuitBreaker({ * name: 'api', * baseUrl: 'https://api.example.com', * healthCheckEndpoint: '/health', * failureThreshold: 5, * resetTimeout: 30000, * }); * * // Execute requests through the circuit breaker * const result = await apiBreaker.execute(() => fetch('/api/users')); * ``` */ export declare class ServiceCircuitBreaker { private breaker; private config; private healthCheckTimer; private metrics; constructor(config: ServiceConfig); /** * Execute a request through the circuit breaker * * @param fn - Async function to execute * @returns Result of the function * @throws Error if circuit is open and no fallback available */ execute(fn: () => Promise): Promise; /** * Execute with automatic retry on failure * * @param fn - Async function to execute * @param maxRetries - Maximum retry attempts * @param delay - Base delay between retries in ms */ executeWithRetry(fn: () => Promise, maxRetries?: number, delay?: number): Promise; /** * Get service health based on circuit state and metrics */ getHealth(): ServiceHealth; /** * Get success rate (0-1) */ getSuccessRate(): number; /** * Get average response time in ms */ getAvgResponseTime(): number; /** * Get complete service status */ getStatus(): ServiceStatus; /** * Get circuit breaker state */ getState(): CircuitState; /** * Check if circuit is allowing requests */ isAvailable(): boolean; /** * Start periodic health checks */ startHealthChecks(): void; /** * Stop periodic health checks */ stopHealthChecks(): void; /** * Perform a single health check * * Note: This method intentionally uses raw fetch() rather than apiClient because: * 1. Health checks are infrastructure-level, not application API calls * 2. The circuit breaker monitors services that apiClient itself depends on * 3. Using apiClient would create circular dependency/infinite loops * * @see {@link @/lib/api/api-client} for application API calls */ performHealthCheck(): Promise; /** * Manually record a success (for external success tracking) */ recordSuccess(): void; /** * Manually record a failure (for external failure tracking) */ recordFailure(error?: string): void; /** * Reset circuit breaker and metrics */ reset(): void; /** * Dispose and cleanup resources */ dispose(): void; /** * Handle circuit state change */ private handleStateChange; } /** * Registry for managing multiple service circuit breakers */ declare class ServiceRegistry { private services; /** * Get registry size */ get size(): number; /** * Register a new service * * @param config - Service configuration * @returns The created circuit breaker */ register(config: ServiceConfig): ServiceCircuitBreaker; /** * Get a service circuit breaker by name */ get(name: string): ServiceCircuitBreaker | undefined; /** * Get or create a service circuit breaker */ getOrCreate(config: ServiceConfig): ServiceCircuitBreaker; /** * Check if a service is registered */ has(name: string): boolean; /** * Unregister a service */ unregister(name: string): void; /** * Get status for all registered services */ getAllStatuses(): ServiceStatus[]; /** * Get overall system health based on all services */ getOverallHealth(): ServiceHealth; /** * Get names of all unhealthy services */ getUnhealthyServices(): string[]; /** * Start health checks for all services */ startAllHealthChecks(): void; /** * Stop health checks for all services */ stopAllHealthChecks(): void; /** * Reset all circuit breakers */ resetAll(): void; /** * Dispose all services and cleanup */ dispose(): void; /** * Get all service names */ getServiceNames(): string[]; } /** * Global service registry instance */ export declare const serviceRegistry: ServiceRegistry; /** * Setup default services with common configuration * * @param apiBaseUrl - Base URL for API services * @param options - Additional configuration options */ export declare function setupDefaultServices(apiBaseUrl: string, options?: { authBaseUrl?: string; healthCheckInterval?: number; autoStart?: boolean; }): void; /** * Create a wrapped fetch function that uses the service circuit breaker * * @param serviceName - Name of the service to use * @returns Wrapped fetch function */ export declare function createServiceFetch(serviceName: string): (input: RequestInfo | URL, init?: RequestInit) => Promise; export {};