# Master/Slave Router with Load Balancing

Der Master/Slave Router bietet fortgeschrittene Load Balancing und Monitoring Funktionen für optimale Database-Performance in High-Availability Setups.

## ✅ Implemented Features

### Weighted Selection Algorithm
- **Dynamic Weight Adjustment**: Gewichte basierend auf aktueller Connection-Last und Response Time
- **Load Factor**: Reduziert Gewichtung bei hoher Connection-Auslastung (min. 10% Gewichtung)
- **Response Time Factor**: Bevorzugt schnelle Replicas basierend auf Moving Average
- **Minimum Weight Protection**: Alle Replicas behalten mindestens 1% Gewichtung

### Connection Metrics & Monitoring
- **Real-time Connection Counting**: Tracking aktiver Connections pro Replica
- **Response Time History**: Moving Average der letzten 100 Response Times pro Replica
- **Health Monitoring**: Automatische Health Checks mit konfigurierbaren Intervallen
- **Comprehensive Statistics**: Detaillierte Routing-Statistiken für Monitoring

### Load Balancing Strategies
- **WEIGHTED**: Intelligente gewichtete Auswahl mit Performance-Adjustierung
- **LEAST_CONNECTIONS**: Auswahl der Replica mit wenigsten aktiven Connections
- **RESPONSE_TIME**: Auswahl basierend auf bester durchschnittlicher Response Time
- **ROUND_ROBIN**: Traditionelle zyklische Auswahl
- **RANDOM**: Zufällige Auswahl für gleichmäßige Verteilung

## Configuration

### DriverConfig Extension
```php
public readonly class DriverConfig
{
    public function __construct(
        // ... existing parameters ...
        public int $weight = 100,           // Load balancing weight
        public int $maxConnections = 100    // Max concurrent connections
    ) {}
}
```

### ReadWriteConfig Methods
```php
$config->getConnectionWeight($index);     // Get weight for replica
$config->getMaxConnections($index);      // Get max connections for replica
$config->getAllWeights();                // Get all weights indexed by position
```

## Usage Examples

### Weighted Load Balancing Setup
```php
$readWriteConfig = new ReadWriteConfig(
    enabled: true,
    readConnections: [
        DriverConfig::fromArray([
            'host' => 'replica1.db.local',
            'weight' => 100,           // Normal weight
            'max_connections' => 50
        ]),
        DriverConfig::fromArray([
            'host' => 'replica2.db.local', 
            'weight' => 200,           // 2x higher capacity
            'max_connections' => 100
        ]),
        DriverConfig::fromArray([
            'host' => 'replica3.db.local',
            'weight' => 50,            // Lower capacity
            'max_connections' => 25
        ])
    ],
    loadBalancingStrategy: LoadBalancingStrategy::WEIGHTED
);
```

### Connection Tracking
```php
// Router tracks connections automatically
$replica = $router->route($sql);

// Manual connection management (if needed)
$router->incrementConnectionCount($replica);
// ... use connection ...
$router->decrementConnectionCount($replica);

// Track query performance
$startTime = microtime(true);
$result = $replica->query($sql);
$responseTime = (microtime(true) - $startTime) * 1000;
$router->recordResponseTime($replica, $responseTime);
```

## Monitoring & Statistics

### Comprehensive Routing Statistics
```php
$stats = $router->getRoutingStatistics();
// Returns:
[
    'total_replicas' => 3,
    'healthy_replicas' => 2,
    'load_balancing_strategy' => 'WEIGHTED',
    'sticky_sessions' => false,
    'replica_details' => [
        0 => [
            'healthy' => true,
            'current_connections' => 15,
            'max_connections' => 50,
            'load_percentage' => 30.0,
            'config_weight' => 100,
            'adjusted_weight' => 85,      // Reduced due to load
            'weight_adjustment_factor' => 0.85,
            'avg_response_time_ms' => 120.5,
            'total_queries' => 1540,
            'failed_queries' => 3,
            'success_rate' => 99.81,
            'recent_response_samples' => 100
        ],
        // ... other replicas
    ]
]
```

### Weight Distribution Analysis
```php
$distribution = $router->getWeightDistribution();
// Returns current weight distribution for healthy replicas:
[
    0 => [
        'config_weight' => 100,
        'adjusted_weight' => 85,
        'current_connections' => 15,
        'avg_response_time' => 120.5,
        'weight_percentage' => 35.2    // % of total weight
    ],
    // ... other healthy replicas
]
```

## Performance Benefits

### Intelligent Load Distribution
- **Load-based Adjustment**: Überlastete Replicas erhalten weniger Traffic
- **Performance-based Routing**: Schnelle Replicas werden bevorzugt
- **Connection Pool Optimization**: Verhindert Connection-Überlastung
- **Failover Protection**: Automatischer Fallback bei Replica-Ausfallen

### Monitoring Integration
- **Real-time Metrics**: Live-Statistiken für Performance-Monitoring
- **Health Tracking**: Continuous Health Checks mit Response Time Tracking
- **Success Rate Monitoring**: Tracking von Query Success/Failure Rates
- **Load Analysis**: Detaillierte Load-Verteilung für Capacity Planning

## Weight Calculation Algorithm

```php
// Dynamic weight adjustment based on current performance
$loadFactor = max(0.1, 1 - ($currentConnections / $maxConnections));
$responseFactor = max(0.1, min(1.0, 100 / $avgResponseTime));
$adjustedWeight = max(1, round($baseWeight * $loadFactor * $responseFactor));
```

**Factors:**
- **Load Factor**: 10-100% basierend auf Connection-Auslastung
- **Response Factor**: 10-100% basierend auf Response Time (100ms = Baseline)
- **Minimum Protection**: Jede Replica behält mindestens 10% Gewichtung

## Testing

Comprehensive test suite covering:
- ✅ Weighted selection distribution accuracy
- ✅ Load factor calculation with edge cases
- ✅ Response time factor adjustment
- ✅ Connection counting accuracy
- ✅ Response time history window management
- ✅ Load balancing strategy logic
- ✅ Routing statistics generation

All tests pass with 78 assertions validating the complete implementation.

## Migration from Simple Round Robin

```php
// Vorher: Simple Round Robin
$router = new MasterSlaveRouter(
    $master, 
    $replicas, 
    new ReadWriteConfig(
        enabled: true,
        loadBalancingStrategy: LoadBalancingStrategy::ROUND_ROBIN
    )
);

// Nachher: Intelligent Weighted Balancing
$router = new MasterSlaveRouter(
    $master,
    $replicas,
    new ReadWriteConfig(
        enabled: true,
        readConnections: $configsWithWeights,
        loadBalancingStrategy: LoadBalancingStrategy::WEIGHTED
    )
);
```

Die Implementierung bietet vollständige Backward-Compatibility mit bestehenden Setups.