npm package: @sailboat-computer/resilience
Description: Enhanced resilience patterns for sailboat computer v3 with marine-specific adaptations
Author: Sailboat Computer Team
Latest version: 1.1.56

# @sailboat-computer/resilience

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

## Overview

This package provides comprehensive resilience patterns designed specifically for marine environments. It includes circuit breakers, bulkhead patterns, timeout management, and graceful degradation strategies optimized for the challenges of operating in harsh marine conditions.

## Current Status

✅ **Phase 1 Complete**: Marine Circuit Breaker implementation
🔄 **Phase 2 In Progress**: Bulkhead patterns and timeout management
🔄 **Phase 3 Planned**: Self-healing mechanisms and integration

### Completed Features

- **MarineCircuitBreaker**: Enhanced circuit breaker with marine-specific adaptations
- **Marine Failure Classification**: Automatic classification of marine-specific failures
- **Environmental Adaptation**: Dynamic adjustment based on sea conditions
- **Operational Context Awareness**: Different behavior for sailing, anchored, emergency modes
- **Pre-configured Patterns**: Ready-to-use configurations for common scenarios

### Planned Features

- [x] Bulkhead pattern for resource isolation
- [x] Hierarchical timeout management
- [x] Retry mechanism with marine adaptations
- [x] Graceful degradation strategies
- [ ] Self-healing mechanisms
- [ ] Health monitoring integration
- [ ] Performance optimization features

## Installation

```bash
npm install @sailboat-computer/resilience
```

## Usage

### Basic Circuit Breaker

```typescript
import { MarineCircuitBreaker, OperationalContext, MarineFailureType } from '@sailboat-computer/resilience';

// Create a circuit breaker for sensor operations
const sensorCircuitBreaker = new MarineCircuitBreaker('gps-sensor', {
  failureThreshold: 3,
  successThreshold: 2,
  timeout: 30000,
  operationalContext: OperationalContext.SAILING,
  failureTypes: [MarineFailureType.SENSOR_FAILURE, MarineFailureType.TIMEOUT]
});

// Execute operation with circuit breaker protection
const result = await sensorCircuitBreaker.execute(async () => {
  // Your sensor reading operation
  return await readGPSData();
}, 'gps-reading');

if (result.success) {
  console.log('GPS data:', result.data);
} else {
  console.error('GPS reading failed:', result.error);
}
```

### Pre-configured Circuit Breakers

```typescript
import { MarineCircuitBreakers } from '@sailboat-computer/resilience';

// Use pre-configured circuit breakers for common scenarios
const gpsCircuitBreaker = MarineCircuitBreakers.sensor('gps');
const networkCircuitBreaker = MarineCircuitBreakers.network('api');
const safetyCircuitBreaker = MarineCircuitBreakers.safety('anchor-alarm');

// Execute operations
const gpsResult = await gpsCircuitBreaker.execute(() => readGPS());
const apiResult = await networkCircuitBreaker.execute(() => fetchWeatherData());
const alarmResult = await safetyCircuitBreaker.execute(() => checkAnchorPosition());
```

### Retry Mechanism

```typescript
import { executeWithRetry, RetryContexts, OperationalContext } from '@sailboat-computer/resilience';

// Execute operation with retry using pre-configured contexts
const gpsResult = await executeWithRetry(
  readGPSSensor,
  RetryContexts.navigationSensor('gps-position', OperationalContext.SAILING)
);

const networkResult = await executeWithRetry(
  fetchWeatherData,
  RetryContexts.networkOperation('weather-api')
);

// Check result
if (gpsResult.success) {
  console.log('GPS data:', gpsResult.data);
  console.log(`Took ${gpsResult.retryCount} retries`);
} else {
  console.error('GPS read failed after retries:', gpsResult.error.message);
}
```

### Marine Environment Adaptation

```typescript
import { 
  MarineEnvironmentStatus, 
  defaultCircuitBreaker,
  defaultRetryManager,
  defaultTimeoutManager,
  defaultBulkheadManager,
  DegradationManager
} from '@sailboat-computer/resilience';

// Update resilience components with current marine conditions
const marineEnvironment: MarineEnvironmentStatus = {
  seaState: 'rough',
  weather: 'storm',
  windSpeed: 35,
  temperature: 15,
  powerStatus: 'conservation',
  connectivityQuality: 0.3,
  expectedFailureRate: 2.0,
  recommendedTimeoutMultiplier: 2.5,
  criticalOperationsOnly: true
};

// All resilience components will automatically adjust their behavior
circuitBreaker.updateMarineEnvironment(marineEnvironment);
defaultRetryManager.updateMarineEnvironment(marineEnvironment);
defaultTimeoutManager.updateMarineEnvironment(marineEnvironment);
defaultBulkheadManager.updateMarineEnvironment(marineEnvironment);

// Degradation manager will automatically adjust service quality level
const degradationManager = new DegradationManager();
degradationManager.updateMarineEnvironment(marineEnvironment);
```

### Graceful Degradation

```typescript
import { 
  DegradationManager, 
  ServiceQualityLevel, 
  FeaturePriority, 
  FeatureToggle 
} from '@sailboat-computer/resilience';

// Create a degradation manager
const degradationManager = new DegradationManager();

// Register features with different priorities
degradationManager.registerFeature({
  id: 'high-res-charts',
  name: 'High Resolution Charts',
  description: 'Displays charts in high resolution',
  priority: FeaturePriority.USEFUL,
  enabled: true,
  manualToggleAllowed: true,
  powerConsumption: 5,
  cpuUsage: 15,
  memoryUsage: 250,
  bandwidthUsage: 50,
  storageIops: 20,
  marineSettings: {
    requiredInRoughSeas: false,
    requiredForNavigation: false,
    requiredForSafety: false,
    requiresGoodConnectivity: true
  }
});

degradationManager.registerFeature({
  id: 'collision-avoidance',
  name: 'Collision Avoidance System',
  description: 'Monitors for potential collisions',
  priority: FeaturePriority.CRITICAL,
  enabled: true,
  manualToggleAllowed: false,
  powerConsumption: 8,
  cpuUsage: 20,
  memoryUsage: 150,
  bandwidthUsage: 5,
  storageIops: 30,
  marineSettings: {
    requiredInRoughSeas: true,
    requiredForNavigation: true,
    requiredForSafety: true,
    requiresGoodConnectivity: false
  }
});

// Check if features are enabled
const chartsEnabled = degradationManager.isFeatureEnabled('high-res-charts');
const collisionAvoidanceEnabled = degradationManager.isFeatureEnabled('collision-avoidance');

// Manually set service quality level
degradationManager.setQualityLevel(ServiceQualityLevel.MINIMAL);

// Get current resource usage metrics
const metrics = degradationManager.getMetrics();
console.log('CPU usage:', metrics.resourceUsage.cpu);
console.log('Power consumption:', metrics.resourceUsage.power);
```

### Event Monitoring

```typescript
// Listen for circuit breaker events
circuitBreaker.onEvent((event) => {
  console.log(`Circuit breaker event: ${event.eventType}`, {
    component: event.component,
    severity: event.severity,
    operationalContext: event.marineContext.operationalContext,
    environmentalImpact: event.marineContext.environmentalImpact
  });
});

// Listen for degradation events
degradationManager.onEvent((event) => {
  console.log(`Degradation event: ${event.eventType}`, {
    component: event.component,
    details: event.details,
    severity: event.severity
  });
});
```

## Marine-Specific Features

### Environmental Adaptation
- **Sea State Awareness**: Adjusts failure thresholds based on sea conditions
- **Weather Impact**: Considers weather conditions in timeout calculations
- **Power Conservation**: Adapts behavior during power conservation modes
- **Connectivity Resilience**: Handles intermittent connectivity gracefully

### Operational Context
- **Sailing vs Motoring**: Different resilience patterns for different operations
- **Anchored vs Underway**: Context-specific behavior adjustments
- **Emergency Mode**: Immediate failover and maximum resilience
- **Maintenance Mode**: Relaxed thresholds for maintenance operations

### Marine Failure Types
- **Sensor Failures**: GPS, compass, wind, depth sensor issues
- **Connectivity Loss**: Network outages common in marine environment
- **Power Fluctuations**: Battery and charging system variations
- **Environmental**: Weather and sea condition impacts
- **Data Quality**: Validation failures from harsh conditions

### Pre-configured Scenarios

#### Sensor Operations
- Optimized for sensor reading failures
- Quick recovery for intermittent issues
- Environmental condition awareness

#### Network Operations
- Handles connectivity loss gracefully
- Power-aware for satellite communications
- Extended timeouts for marine networks

#### Safety Operations
- Immediate failover for critical systems
- Minimal tolerance for failures
- Emergency operation prioritization

#### Power Operations
- Battery and charging system protection
- Resource exhaustion handling
- Power conservation awareness

#### Maintenance Operations
- Relaxed thresholds during maintenance
- Extended timeouts for complex operations
- Non-critical failure tolerance

## Architecture

### Circuit Breaker States
- **CLOSED**: Normal operation, requests pass through
- **OPEN**: Failing state, requests are blocked
- **HALF_OPEN**: Testing recovery, limited requests allowed

### Marine Adaptations
- **Dynamic Thresholds**: Adjust based on environmental conditions
- **Failure Classification**: Marine-specific failure type detection
- **Context Awareness**: Operational state influences behavior
- **Environmental Monitoring**: Real-time condition adaptation

### Metrics and Monitoring
- **Request Metrics**: Success/failure rates, response times
- **Marine Metrics**: Environmental failures, power-related issues
- **Operational Metrics**: Context-specific performance data
- **Health Indicators**: Overall system resilience health

## Configuration

### Circuit Breaker Configuration
```typescript
interface CircuitBreakerConfig {
  failureThreshold: number;           // Failures before opening
  successThreshold: number;           // Successes to close from half-open
  timeout: number;                    // Recovery attempt interval
  operationalContext: OperationalContext;
  failureTypes: MarineFailureType[];
  environmentalAdjustments: {
    roughSeas: boolean;
    lowPower: boolean;
    limitedConnectivity: boolean;
  };
  volumeThreshold: number;            // Minimum requests before opening
  errorPercentageThreshold: number;   // Error percentage trigger
  slowCallDurationThreshold: number;  // Slow call definition
  slowCallRateThreshold: number;      // Slow call percentage trigger
}
```

### Marine Environment Status
```typescript
interface MarineEnvironmentStatus {
  seaState: 'calm' | 'moderate' | 'rough' | 'very_rough';
  weather: 'clear' | 'cloudy' | 'rain' | 'storm';
  windSpeed: number;                  // Knots
  temperature: number;                // Celsius
  powerStatus: 'normal' | 'conservation' | 'critical';
  connectivityQuality: number;        // 0-1 quality score
  expectedFailureRate: number;        // Failure rate multiplier
  recommendedTimeoutMultiplier: number;
  criticalOperationsOnly: boolean;
}
```

## Development

```bash
# Build the package
npm run build

# Run tests
npm test

# Watch mode for development
npm run build:watch
```

## Integration

This package integrates with other sailboat computer v3 components:

- **@sailboat-computer/validation**: Resilience for validation failures
- **@sailboat-computer/data-storage**: Database operation resilience
- **@sailboat-computer/health-monitoring**: Health status integration

## Contributing

This package is part of the sailboat computer v3 project. Please follow the contract-first development approach and ensure all changes are properly tested in marine conditions.

## License

MIT