# ErrorBoundary Middleware System

Complete HTTP middleware system for automatic error boundary integration in web applications.

## Components

### Core Middleware Classes

- **`ErrorBoundaryMiddleware`** - Main middleware for web requests with graceful fallback responses
- **`ApiErrorBoundaryMiddleware`** - Specialized API middleware with detailed JSON error responses  
- **`CircuitBreakerHealthMiddleware`** - Health check endpoints for monitoring circuit breaker states

### Configuration & Management

- **`MiddlewareConfiguration`** - Centralized configuration for all middleware components
- **`ErrorBoundaryMiddlewareRegistry`** - Registration and management of middleware components
- **`MiddlewareServiceProvider`** - Dependency injection and service initialization

## Features

### Automatic Error Boundaries
- Wraps HTTP requests in error boundaries
- Provides graceful fallback responses for failed operations
- Supports both JSON (API) and HTML (web) responses
- Route-based configuration and conditional middleware application

### Circuit Breaker Integration
- Automatic circuit breaker management for routes
- Health check endpoints with comprehensive status information
- Configurable thresholds and recovery mechanisms
- Real-time monitoring and alerting capabilities

### Flexible Configuration
- Development, production, and API-only presets
- Route-pattern matching with wildcards
- Granular enable/disable controls per route type
- Debug information inclusion for development environments

## Usage Examples

### Basic Setup

```php
// In your application bootstrap
$serviceProvider = MiddlewareServiceProvider::development();
$serviceProvider->initialize($container);
```

### Custom Configuration

```php
$config = new MiddlewareConfiguration(
    enableForAllRoutes: false,
    enabledRoutes: ['/api/*', '/admin/*'],
    excludedRoutes: ['/assets/*', '/health/*'],
    enableApiMiddleware: true,
    enableHealthMiddleware: true,
    includeDebugInfo: false,
);

$serviceProvider = MiddlewareServiceProvider::custom($config);
$serviceProvider->initialize($container);
```

### Route-Specific Configuration

```php
$config = MiddlewareConfiguration::production()
    ->withRouteConfiguration('/api/payments/*', BoundaryConfig::critical())
    ->withRouteConfiguration('/api/notifications/*', BoundaryConfig::externalService());

$serviceProvider = MiddlewareServiceProvider::custom($config);
```

## Configuration Presets

### Development Mode
```php
MiddlewareConfiguration::development()
```
- Enabled for all routes
- Debug information included
- Health monitoring enabled
- Excludes only static assets

### Production Mode
```php
MiddlewareConfiguration::production()
```
- Selective route enabling
- No debug information
- Optimized for performance
- Comprehensive exclusions

### API-Only Mode
```php
MiddlewareConfiguration::apiOnly()
```
- Only API routes enabled
- JSON responses only
- GraphQL support included
- Health monitoring enabled

## Health Check Endpoints

### Circuit Breaker Status
```
GET /health/circuit-breakers
GET /api/health/circuit-breakers  
GET /admin/health/circuit-breakers
```

**Response Format:**
```json
{
  "status": "healthy|warning|critical",
  "timestamp": "2024-01-22T14:30:00+00:00",
  "summary": {
    "total_boundaries": 6,
    "healthy_boundaries": 5,
    "unhealthy_boundaries": 1,
    "overall_health_score": 85
  },
  "boundaries": {
    "api_health": {
      "is_healthy": true,
      "state": "CLOSED",
      "failure_count": 0,
      "severity": "info"
    }
  },
  "recommendations": [
    {
      "type": "database",
      "priority": "critical",
      "message": "Database connection circuit breaker is open",
      "action": "Check database connectivity and performance"
    }
  ]
}
```

## Error Response Formats

### Web Requests (HTML)
- Beautiful fallback pages with retry functionality
- User-friendly error messages
- Responsive design with modern styling
- Request tracking for debugging

### API Requests (JSON)
```json
{
  "error": {
    "code": "API_SERVICE_UNAVAILABLE",
    "message": "The API service is temporarily unavailable due to high load or maintenance.",
    "type": "service_unavailable",
    "timestamp": "2024-01-22T14:30:00+00:00",
    "request_id": "req_abc123",
    "retry_after": 60
  },
  "meta": {
    "endpoint": "/api/users",
    "method": "GET",
    "boundary_used": true,
    "fallback_response": true
  },
  "links": {
    "status": "/api/status",
    "documentation": "/api/docs", 
    "support": "/api/support"
  }
}
```

## Monitoring & Observability

### Middleware Statistics
```php
$registry = $container->get(ErrorBoundaryMiddlewareRegistry::class);
$stats = $registry->getStatistics();
```

### Event Integration
- Boundary execution events
- Circuit breaker state changes  
- Fallback execution tracking
- Performance metrics collection

## Best Practices

### Route Configuration
- Use specific patterns over broad wildcards
- Configure critical routes with appropriate boundaries
- Exclude static assets and health checks from main middleware
- Test fallback responses in development

### Circuit Breaker Tuning
- Set appropriate failure thresholds for each service type
- Configure realistic timeout values
- Monitor and adjust based on actual traffic patterns
- Implement proper alerting for circuit breaker events

### Performance Optimization
- Use conditional middleware application
- Configure appropriate middleware priorities
- Monitor middleware execution time
- Cache boundary configurations where possible

## Integration Points

### Framework Integration
- Integrates with framework's HTTP middleware system
- Uses dependency injection for component management
- Leverages event system for observability
- Compatible with existing error handling

### External Dependencies
- **ErrorBoundaryFactory** - For boundary creation
- **StateManager** - For circuit breaker persistence
- **Logger** - For operational logging
- **EventBus** - For event publishing
- **MiddlewareManager** - For HTTP middleware registration