# Performance Module Architecture

## Overview

This document describes the architecture and component structure of the Performance Module after the refactoring from a monolithic to a modular middleware-based system.

## Directory Structure

```
src/Framework/Performance/
├── README.md                    # Main documentation
├── ARCHITECTURE.md             # This file - Architecture overview
├── PerformanceCategory.php     # Enum for performance categories
├── PerformanceCollector.php    # Central metrics collection
├── PerformanceConfig.php       # Configuration for tracking settings
├── PerformanceMetric.php       # Individual metric data structure
├── PerformanceReporter.php     # Report generation (HTML/JSON/Text)
├── PerformanceService.php      # Simplified API for developers
└── Middleware/                 # Specialized middleware components
    ├── RequestPerformanceMiddleware.php
    ├── ControllerPerformanceMiddleware.php
    ├── RoutingPerformanceMiddleware.php
    ├── DatabasePerformanceMiddleware.php
    ├── CachePerformanceMiddleware.php
    └── PerformanceDebugMiddleware.php
```

## Component Relationships

### Data Flow

```
Request → RequestPerformanceMiddleware
       → RoutingPerformanceMiddleware
       → ControllerPerformanceMiddleware
       → [Database/Cache Operations via their Middleware]
       → PerformanceDebugMiddleware
       → Response with Performance Data
```

### Core Components

#### PerformanceCollector
- **Purpose**: Central collection point for all metrics
- **Responsibilities**:
  - Store timing data
  - Track memory usage
  - Manage active measurements
  - Provide metric retrieval APIs
- **Usage**: Used by all middleware components to store metrics

#### PerformanceMetric
- **Purpose**: Represents a single performance metric
- **Data Stored**:
  - Timing measurements (duration, start/end times)
  - Memory usage
  - Count statistics
  - Context information
- **Features**:
  - Statistical calculations (min, max, average)
  - Serialization support

#### PerformanceConfig
- **Purpose**: Configuration for the entire performance system
- **Settings**:
  - Enable/disable tracking per category
  - Slow query thresholds
  - Excluded paths
  - Output formats
- **Flexibility**: Allows fine-grained control over what gets tracked

#### PerformanceReporter
- **Purpose**: Generate performance reports in multiple formats
- **Formats Supported**:
  - HTML (with interactive debugging)
  - JSON (for APIs and external tools)
  - Text (for logs and CLI)
  - Array (for programmatic use)

#### PerformanceService
- **Purpose**: Simplified API for application developers
- **Features**:
  - Convenience methods for common operations
  - High-level abstractions
  - Easy integration into existing code

### Middleware Components

#### HTTP Layer Middleware

**RequestPerformanceMiddleware**
- **Priority**: `FIRST` (runs earliest)
- **Tracks**: Overall request performance, memory usage
- **Metrics**: Request time, memory consumption, success/failure rates

**RoutingPerformanceMiddleware**
- **Priority**: `ROUTING + 10` (after routing)
- **Tracks**: Route resolution performance
- **Metrics**: Route matching time, pattern usage, 404 rates

**ControllerPerformanceMiddleware**
- **Priority**: `CONTROLLER - 10` (before controller execution)
- **Tracks**: Controller and action performance
- **Metrics**: Controller execution time, action-specific performance

**PerformanceDebugMiddleware**
- **Priority**: `LAST` (runs latest)
- **Purpose**: Inject debug reports into responses
- **Features**: HTML injection, HTTP headers, AJAX support

#### Data Layer Middleware

**DatabasePerformanceMiddleware**
- **Interface**: Implements `Database\Middleware`
- **Tracks**: Database query performance
- **Metrics**: Query types, execution time, slow queries
- **Features**: Query sanitization, sensitive data protection

**CachePerformanceMiddleware**
- **Interface**: Implements `Cache\CacheMiddleware`
- **Tracks**: Cache operation performance
- **Metrics**: Hit/miss ratios, operation timing, data sizes

## Design Principles

### Modularity
- Each middleware focuses on a specific concern
- Components can be enabled/disabled independently
- Clear separation of responsibilities

### Performance
- Minimal overhead when disabled
- Efficient data structures
- Lazy report generation

### Flexibility
- Multiple output formats
- Configurable tracking levels
- Extensible middleware system

### Framework Integration
- Uses existing middleware patterns
- Follows framework conventions
- Integrates with DI container

## Migration from Old System

### Removed Components
- `PerformanceMeter` → Replaced by `PerformanceCollector`
- `PerformanceMarker` → Integrated into `PerformanceMetric`
- `PerformanceMeasurement` → Integrated into `PerformanceMetric`
- `MemoryUsageTracker` → Functionality moved to `PerformanceCollector`
- `PerformanceMiddleware` → Split into specialized middleware
- Example files → Replaced by comprehensive documentation
- Job-based logging → Simplified to in-memory collection

### Backwards Compatibility
- `PerformanceCategory` enum maintained
- Core concepts preserved
- API improvements without breaking changes

### Benefits of New Architecture
1. **Better Separation of Concerns**: Each middleware handles specific metrics
2. **Improved Performance**: More efficient data collection and storage
3. **Enhanced Flexibility**: Fine-grained control over tracking
4. **Better Integration**: Follows framework middleware patterns
5. **Easier Testing**: Smaller, focused components
6. **Reduced Complexity**: Eliminated redundant code
7. **Better Documentation**: Comprehensive guides and examples

## Extension Points

### Adding New Middleware
```php
class CustomPerformanceMiddleware implements HttpMiddleware
{
    public function __construct(
        private PerformanceCollector $collector,
        private PerformanceConfig $config
    ) {}

    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        if (!$this->config->isTrackingEnabled(PerformanceCategory::CUSTOM)) {
            return $next($context);
        }

        $this->collector->startTiming('custom_operation', PerformanceCategory::CUSTOM);
        $result = $next($context);
        $this->collector->endTiming('custom_operation');

        return $result;
    }
}
```

### Adding New Categories
```php
// Extend PerformanceCategory enum
enum PerformanceCategory: string
{
    // ... existing cases
    case THIRD_PARTY = 'third_party';
    case EXTERNAL_API = 'external_api';
}

// Update PerformanceConfig to handle new categories
public function isTrackingEnabled(PerformanceCategory $category): bool
{
    return match ($category) {
        // ... existing cases
        PerformanceCategory::THIRD_PARTY => $this->thirdPartyTracking,
        PerformanceCategory::EXTERNAL_API => $this->externalApiTracking,
    };
}
```

### Custom Report Formats
```php
// Extend PerformanceReporter
public function generateCustomReport(): string
{
    $data = $this->collectReportData();
    return $this->formatAsCustomFormat($data);
}
```

## Future Enhancements

- **Persistent Storage**: Optional database storage for metrics
- **Real-time Monitoring**: WebSocket-based live performance data
- **Alerting**: Threshold-based notifications
- **Aggregation**: Cross-request performance analysis
- **Export Integration**: Prometheus, Grafana, etc.
- **Machine Learning**: Anomaly detection and predictions