UNPKG

@sailboat-computer/resilience

Version:

Enhanced resilience patterns for sailboat computer v3 with marine-specific adaptations

240 lines (208 loc) 7.09 kB
/** * Core types for the resilience framework */ // Import types directly from sailboat-types package import { CircuitBreakerState, MarineFailureType, OperationalContext, MarineEnvironmentStatus } from '@sailboat-computer/sailboat-types'; // Export imported types export { CircuitBreakerState, MarineFailureType, OperationalContext, MarineEnvironmentStatus }; // Type aliases for enum types export type CircuitBreakerStateType = CircuitBreakerState; export type MarineFailureTypeType = MarineFailureType; export type OperationalContextType = OperationalContext; /** * Circuit breaker configuration */ export interface CircuitBreakerConfig { // Failure thresholds failureThreshold: number; // Number of failures before opening successThreshold: number; // Number of successes to close from half-open timeout: number; // Time to wait before trying half-open (ms) // Marine-specific settings operationalContext: OperationalContextType; failureTypes: MarineFailureTypeType[]; environmentalAdjustments: { roughSeas: boolean; // Increase tolerance in rough conditions lowPower: boolean; // Adjust for power conservation limitedConnectivity: boolean; // Handle intermittent connectivity }; // Advanced settings volumeThreshold: number; // Minimum requests before circuit can open errorPercentageThreshold: number; // Percentage of errors to trigger opening slowCallDurationThreshold: number; // Duration to consider a call "slow" (ms) slowCallRateThreshold: number; // Percentage of slow calls to trigger opening } /** * Circuit breaker metrics */ export interface CircuitBreakerMetrics { state: CircuitBreakerStateType; totalRequests: number; successfulRequests: number; failedRequests: number; rejectedRequests: number; averageResponseTime: number; slowCalls: number; // Marine-specific metrics environmentalFailures: number; powerRelatedFailures: number; connectivityFailures: number; sensorFailures: number; // Timing lastFailureTime?: Date; lastSuccessTime?: Date; stateChangedAt: Date; nextAttemptAt?: Date; } /** * Bulkhead resource pool configuration */ export interface BulkheadConfig { poolName: string; maxConcurrentRequests: number; maxWaitTime: number; // Max time to wait for resource (ms) priority: 'critical' | 'normal' | 'low'; // Marine-specific settings marineSystemType: 'navigation' | 'safety' | 'comfort' | 'maintenance'; powerConsumption: 'high' | 'medium' | 'low'; operationalDependency: 'essential' | 'important' | 'optional'; } /** * Resource pool metrics */ export interface ResourcePoolMetrics { poolName: string; totalCapacity: number; availableResources: number; activeRequests: number; queuedRequests: number; rejectedRequests: number; averageWaitTime: number; maxWaitTime: number; // Marine-specific metrics powerImpact: number; // Current power consumption criticalRequestsActive: number; systemHealthImpact: number; // Impact on overall system health (0-1) } /** * Timeout configuration with hierarchical structure */ export interface TimeoutConfig { // Basic timeout settings operationTimeout: number; // Individual operation timeout (ms) serviceTimeout: number; // Service-level timeout (ms) systemTimeout: number; // System-level timeout (ms) // Marine environment adjustments environmentalMultiplier: number; // Adjust timeouts based on conditions (0.5-3.0) operationalContext: OperationalContextType; // Retry settings maxRetries: number; retryBackoffMultiplier: number; maxRetryDelay: number; // Marine-specific settings criticalOperationTimeout: number; // Timeout for safety-critical operations sensorReadTimeout: number; // Timeout for sensor readings networkOperationTimeout: number; // Timeout for network operations } /** * Timeout metrics */ export interface TimeoutMetrics { totalOperations: number; timedOutOperations: number; averageOperationTime: number; maxOperationTime: number; // Retry metrics totalRetries: number; successfulRetries: number; failedRetries: number; // Marine-specific metrics environmentalTimeouts: number; // Timeouts due to environmental conditions criticalOperationTimeouts: number; // Timeouts in critical operations sensorTimeouts: number; // Sensor read timeouts } /** * Resilience operation result */ export interface ResilienceResult<T> { success: boolean; data?: T; error?: Error; metrics: { executionTime: number; retryCount: number; circuitBreakerState?: CircuitBreakerStateType; resourcePoolUsed?: string; timeoutApplied?: number; }; marineContext: { operationalContext: OperationalContextType; environmentalConditions: Record<string, any>; powerStatus: 'normal' | 'conservation' | 'critical'; connectivityStatus: 'online' | 'intermittent' | 'offline'; }; } /** * Resilience event for monitoring and logging */ export interface ResilienceEvent { timestamp: Date; eventType: 'circuit_breaker_opened' | 'circuit_breaker_closed' | 'timeout' | 'retry' | 'bulkhead_rejection' | 'recovery'; component: string; details: Record<string, any>; severity: 'info' | 'warning' | 'error' | 'critical'; marineContext: { operationalContext: OperationalContextType; failureType?: MarineFailureTypeType; environmentalImpact?: boolean; safetyImpact?: boolean; }; } /** * Resilience strategy configuration */ export interface ResilienceStrategy { name: string; description: string; // Component configurations circuitBreaker?: CircuitBreakerConfig; bulkhead?: BulkheadConfig; timeout?: TimeoutConfig; // Marine-specific settings marineEnvironmentAdaptation: boolean; safetyFirst: boolean; // Prioritize safety over performance powerAware: boolean; // Consider power consumption // Conditions for applying this strategy applicableContexts: OperationalContextType[]; applicableFailureTypes: MarineFailureTypeType[]; minimumSystemHealth: number; // 0-1, minimum health to use this strategy } /** * System resilience status */ export interface SystemResilienceStatus { overallHealth: number; // 0-1 overall system resilience health componentStatus: { circuitBreakers: Record<string, CircuitBreakerMetrics>; resourcePools: Record<string, ResourcePoolMetrics>; timeouts: Record<string, TimeoutMetrics>; }; marineStatus: MarineEnvironmentStatus; activeStrategies: string[]; // Currently active resilience strategies recentEvents: ResilienceEvent[]; // Recent resilience events recommendations: { adjustTimeouts: boolean; enablePowerConservation: boolean; activateEmergencyMode: boolean; performMaintenance: string[]; // Components needing maintenance }; }