feat(Production): Complete production deployment infrastructure

- Add comprehensive health check system with multiple endpoints
- Add Prometheus metrics endpoint
- Add production logging configurations (5 strategies)
- Add complete deployment documentation suite:
  * QUICKSTART.md - 30-minute deployment guide
  * DEPLOYMENT_CHECKLIST.md - Printable verification checklist
  * DEPLOYMENT_WORKFLOW.md - Complete deployment lifecycle
  * PRODUCTION_DEPLOYMENT.md - Comprehensive technical reference
  * production-logging.md - Logging configuration guide
  * ANSIBLE_DEPLOYMENT.md - Infrastructure as Code automation
  * README.md - Navigation hub
  * DEPLOYMENT_SUMMARY.md - Executive summary
- Add deployment scripts and automation
- Add DEPLOYMENT_PLAN.md - Concrete plan for immediate deployment
- Update README with production-ready features

All production infrastructure is now complete and ready for deployment.
This commit is contained in:
2025-10-25 19:18:37 +02:00
parent caa85db796
commit fc3d7e6357
83016 changed files with 378904 additions and 20919 deletions

237
examples/README.md Normal file
View File

@@ -0,0 +1,237 @@
# Usage Examples
Praktische Beispiele für verschiedene Framework-Features.
## Verfügbare Examples
### Performance Profiling (`performance-profiling-usage.php`)
Demonstriert die Verwendung des NestedPerformanceTracker für:
- Nested Performance Tracking
- Flamegraph-Visualisierung (Brendan Gregg Format)
- Chrome DevTools Timeline Export
- Performance Budget Validation
- Automatische Bottleneck-Erkennung
- Memory Usage Analysis
**Ausführung**:
```bash
php examples/performance-profiling-usage.php
```
**Generierte Dateien**:
- `tests/tmp/flamegraph.txt` - Flamegraph-Daten für flamegraph.pl
- `tests/tmp/chrome-trace.json` - Chrome DevTools Timeline Format
**Visualisierung**:
```bash
# SVG mit flamegraph.pl generieren
flamegraph.pl tests/tmp/flamegraph.txt > tests/tmp/flamegraph.svg
# In Chrome DevTools öffnen
# 1. Chrome öffnen: chrome://tracing
# 2. Load → tests/tmp/chrome-trace.json auswählen
```
### LiveComponent Performance Profiling (`livecomponent-profiling-usage.php`)
Demonstriert Performance-Profiling für LiveComponents:
- Component Lifecycle Profiling (onMount, onUpdate, action execution)
- Component Render Pipeline Profiling (cache → render → template)
- Nested Template Processor Profiling
- Performance Budget Validation für Components
- Chrome DevTools Timeline für Component-Lifecycle
**Ausführung**:
```bash
php examples/livecomponent-profiling-usage.php
```
**Generierte Dateien**:
- `tests/tmp/livecomponent-trace.json` - Chrome DevTools Timeline für LiveComponents
**Use Cases**:
- Identifizierung langsamer Component Actions
- Optimierung des Render-Pipelines
- Validierung von Performance-Budgets
- Analyse der Template-Verarbeitung
- Lifecycle Hook Performance
### Action Execution Profiling (`action-profiling-usage.php`)
Demonstriert erweiterte Action-Profiling-Funktionen mit ActionProfiler:
- Detaillierte Security-Check-Profiling (CSRF, Authorization, Rate Limiting)
- Parameter Binding Performance Analysis
- Action Execution Metrics (Min, Max, Avg)
- Component Performance Summaries
- System-Wide Performance Reports
- Idempotency Cache Effectiveness Measurement
**Ausführung**:
```bash
php examples/action-profiling-usage.php
```
**Features**:
- Einzelne Action Phase Profiling
- Aggregierte Action Metrics über mehrere Executions
- Component-basierte Performance Summaries
- System-weite Performance Reports
- Idempotency Cache Impact Analysis
**Use Cases**:
- Identifizierung von Security-Check-Overhead
- Parameter Binding Optimization
- Action Execution Performance Monitoring
- Cache Effectiveness Validation
- Production Performance Reporting
### Memory Profiling (`memory-profiling-usage.php`)
Demonstriert erweiterte Memory-Profiling-Funktionen mit MemoryProfiler:
- Memory Hotspot Identification (top memory-consuming operations)
- Memory Leak Detection mit konfigurierbaren Thresholds
- Memory Efficiency Scoring (0-100 scale mit Rating)
- Comprehensive Memory Reports (by category, with hotspots)
- Memory Tracking Over Time mit Trend Analysis
- Memory Budget Validation für kritische Operations
- A/B Comparison für Memory Optimizations
**Ausführung**:
```bash
php examples/memory-profiling-usage.php
```
**Features**:
- Leak-Erkennung mit kumulativer Memory-Tracking
- Efficiency Scoring (Memory vs. Execution Time)
- Budget Violation Reporting
- Trend Analysis (rapidly_growing, stable, decreasing)
- Operation A/B Testing für Optimierungen
**Use Cases**:
- Identifizierung von Memory Hotspots
- Erkennung und Verhinderung von Memory Leaks
- Memory Efficiency Monitoring über Zeit
- Validierung von Memory Budgets in Production
- Vergleich von Memory-Verbrauch zwischen Implementierungen
### DOM Parser (`dom-parser-usage.php`)
Demonstriert die Verwendung des DOM Parser Systems.
**Ausführung**:
```bash
php examples/dom-parser-usage.php
```
### StateManager + LiveComponentState Integration (`tests/debug/test-statemanager-livecomponent-integration.php`)
Demonstriert die Integration von LiveComponentState mit dem Framework's StateManagement-Modul:
- Type-safe State Management für LiveComponents
- Persistent State Storage mit TTL Support
- Atomic State Updates
- Generic Type Parameter System für vollständige Typisierung
- Seamless Integration zwischen Application Layer (LiveComponentState) und Framework Layer (StateManager)
- **NEU**: `LiveComponentStateManager` - Domain-specific wrapper für component-aware API
- **NEU**: `ComponentStateCache` nutzt jetzt StateManager für type-safe caching
- **NEU**: `StateManagerFactory::createForLiveComponents()` für einfache StateManager-Erstellung
**Ausführung**:
```bash
docker exec php php tests/debug/test-statemanager-livecomponent-integration.php
```
**Features**:
- LiveComponentState extends SerializableState für StateManager-Kompatibilität
- ComponentState implements SerializableState für Framework-Cache-Integration
- Vollständige Type Safety: Components behalten konkrete State-Typen (z.B. ShoppingCartState, nicht LiveComponentState)
- IDE Auto-Completion funktioniert für alle domain-spezifischen Properties und Methods
- StateManager mit Generic Type Parameters (@template T of SerializableState)
- Factory Methods für typsichere StateManager-Instanzen
- In-Memory und Cache-based Implementations verfügbar
- **CacheKey Value Object** für type-safe key generation (Format: `{componentName}:{instanceId}`)
- **Comprehensive Test Coverage**: 32 Pest tests validieren die gesamte Integration
**Type Safety Demonstration**:
```php
// Option 1: Direct StateManager usage
$stateManager = InMemoryStateManager::for(ShoppingCartState::class);
$cartState = ShoppingCartState::fromArray([...]);
$stateManager->setState('user-123', $cartState, Duration::fromHours(1));
$retrieved = $stateManager->getState('user-123');
// $retrieved is ShoppingCartState, not mixed or LiveComponentState!
// Option 2: LiveComponentStateManager (NEW - Recommended)
$factory = new StateManagerFactory($cache, $logger);
$stateManager = $factory->createForLiveComponents(
stateClass: ShoppingCartState::class,
componentName: 'shopping-cart',
defaultTtl: Duration::fromHours(24)
);
$manager = new LiveComponentStateManager($stateManager);
$componentId = ComponentId::create('shopping-cart', 'user-123');
// Store with component-aware API
$manager->setComponentState($componentId, $cartState);
// Retrieve - TYPE PRESERVED!
$retrieved = $manager->getComponentState($componentId);
// $retrieved is ShoppingCartState! IDE auto-completion works!
$retrieved->discountCode; // ✅ Works
$retrieved->items; // ✅ Works
// Atomic updates - race-condition free
$updated = $manager->updateComponentState(
$componentId,
fn($cart) => $cart->withDiscountCode('SAVE20', 20)
);
// Statistics
$stats = $manager->getStatistics();
echo "Hit rate: {$stats->hitRate}%\n";
```
**ComponentStateCache Integration** (NEW):
```php
use App\Framework\LiveComponents\Cache\ComponentStateCache;
use App\Framework\LiveComponents\ValueObjects\ComponentId;
use App\Framework\LiveComponents\ValueObjects\ComponentState;
// ComponentStateCache now uses StateManager internally
$cache = new ComponentStateCache($stateManager);
$componentId = ComponentId::create('counter', 'instance-1');
$state = ComponentState::fromArray(['count' => 5]);
// Store with automatic TTL based on component type
$cache->storeWithAutoTTL($componentId, $state, 'counter'); // 5 min TTL
$cache->storeWithAutoTTL($componentId, $state, 'chart'); // 30 min TTL
$cache->storeWithAutoTTL($componentId, $state, 'card'); // 2 hour TTL
// Atomic updates
$updated = $cache->update(
$componentId,
fn($s) => ComponentState::fromArray([
'count' => $s->toArray()['count'] + 1
])
);
// CacheKey is used internally: "counter:instance-1"
```
**Integration Benefits**:
- Domain-specific states (ShoppingCartState, CounterState, etc.) können StateManager nutzen
- Persistent state storage mit automatic serialization/deserialization
- TTL support für state expiration
- Atomic updates via StateManager::updateState()
- Performance metrics via StateManager::getStatistics()
- Framework-compliant: readonly, final, Value Object patterns
- Testing: InMemoryStateManager für Unit Tests, CacheBasedStateManager für Production
## Weitere Ressourcen
- **Dokumentation**: `docs/claude/performance-profiling.md`
- **Tests**: `tests/Unit/Framework/Performance/`
- **MCP Integration**: `docs/claude/mcp-integration.md`

View File

@@ -0,0 +1,309 @@
<?php
declare(strict_types=1);
/**
* LiveComponent Action Profiling Usage Examples
*
* Dieses Script demonstriert die erweiterten Action-Profiling-Funktionen
* mit dem ActionProfiler für detaillierte Performance-Analyse.
*
* Ausführung: php examples/action-profiling-usage.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\LiveComponents\Performance\ActionProfiler;
use App\Framework\LiveComponents\ValueObjects\ComponentId;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
// Initialize tracker and profiler
$tracker = new NestedPerformanceTracker(
new SystemClock(),
new SystemHighResolutionClock(),
new MemoryMonitor()
);
$profiler = new ActionProfiler($tracker);
echo "=== LiveComponent Action Profiling Examples ===\n\n";
// Example 1: Profiling einzelner Action Execution
echo "Example 1: Detailed Action Execution Profiling\n";
echo str_repeat('-', 50) . "\n";
$componentId = ComponentId::create('counter', 'demo-123');
// Simuliere vollständige Action Execution mit allen Sicherheits-Checks
$profiler->profileCsrfValidation(
$componentId,
'increment',
function () {
usleep(200); // 0.2ms - CSRF validation
}
);
$profiler->profileAuthorizationCheck(
$componentId,
'increment',
function () {
usleep(300); // 0.3ms - Authorization check
}
);
$profiler->profileRateLimitCheck(
$componentId,
'increment',
function () {
usleep(150); // 0.15ms - Rate limit check
}
);
$profiler->profileParameterBinding(
$componentId,
'increment',
function () {
usleep(400); // 0.4ms - Parameter binding with reflection
return ['value' => 1];
}
);
// Haupte Action execution (simuliert in executeActionAndBuildUpdate)
$tracker->measure(
"livecomponent.counter.increment",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () use ($tracker) {
$tracker->measure(
"livecomponent.action.execute",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () {
usleep(2000); // 2ms - Business logic
}
);
$tracker->measure(
"livecomponent.state.validate",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () {
usleep(500); // 0.5ms - State validation
}
);
},
['component' => 'counter', 'action' => 'increment']
);
echo "\nAction Execution Timeline:\n";
$timeline = $tracker->generateTimeline();
foreach ($timeline as $event) {
$indent = str_repeat(' ', $event['depth']);
echo sprintf(
" %s[%s] %s (%.2fms)\n",
$indent,
$event['category'],
$event['name'],
$event['duration_ms']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 2: Action Metrics Analysis
echo "Example 2: Action Metrics Analysis\n";
echo str_repeat('-', 50) . "\n";
// Simuliere mehrere Action Executions
for ($i = 0; $i < 3; $i++) {
$profiler->profileCsrfValidation($componentId, 'increment', fn() => usleep(200));
$profiler->profileAuthorizationCheck($componentId, 'increment', fn() => usleep(300));
$profiler->profileParameterBinding($componentId, 'increment', fn() => usleep(400));
$tracker->measure(
"livecomponent.counter.increment",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () use ($tracker) {
$tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(2000));
$tracker->measure("livecomponent.state.validate", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(500));
},
['component' => 'counter', 'action' => 'increment']
);
}
$metrics = $profiler->getActionMetrics('counter', 'increment');
echo "\nAction Metrics for counter.increment:\n";
echo " Executions: {$metrics['executions']}\n";
echo " Total Time: " . number_format($metrics['total_time_ms'], 2) . "ms\n";
echo " Avg Time per Execution: " . number_format($metrics['avg_time_per_execution_ms'], 2) . "ms\n";
echo "\n Phase Timings:\n";
foreach ($metrics['phase_timings'] as $phase => $timing) {
echo sprintf(
" • %s: %.2fms avg (%d calls)\n",
$phase,
$timing['avg_ms'],
$timing['count']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 3: Component Summary
echo "Example 3: Component Performance Summary\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere verschiedene Operations für mehrere Components
$components = ['counter', 'search', 'user-card'];
$actions = ['increment', 'updateQuery', 'refresh'];
foreach ($components as $index => $componentName) {
$compId = ComponentId::create($componentName, "instance-{$index}");
$action = $actions[$index];
// Simuliere 2-3 Action executions
for ($i = 0; $i < rand(2, 3); $i++) {
$profiler->profileCsrfValidation($compId, $action, fn() => usleep(rand(150, 250)));
$profiler->profileAuthorizationCheck($compId, $action, fn() => usleep(rand(250, 350)));
$tracker->measure(
"livecomponent.{$componentName}.{$action}",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () use ($tracker) {
$tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(rand(1500, 2500)));
},
['component' => $componentName, 'action' => $action]
);
}
}
echo "\nComponent Performance Summaries:\n\n";
foreach ($components as $componentName) {
$summary = $profiler->getComponentSummary($componentName);
echo " {$summary['component']}:\n";
echo " Total Operations: {$summary['total_operations']}\n";
echo " Total Time: " . number_format($summary['total_time_ms'], 2) . "ms\n";
echo " Operations:\n";
foreach ($summary['operations'] as $opName => $stats) {
echo sprintf(
" • %s: %.2fms avg (min: %.2fms, max: %.2fms, count: %d)\n",
basename($opName),
$stats['avg_time_ms'],
$stats['min_time_ms'],
$stats['max_time_ms'],
$stats['count']
);
}
echo "\n";
}
echo str_repeat('=', 50) . "\n\n";
// Example 4: System-Wide Performance Report
echo "Example 4: System-Wide Performance Report\n";
echo str_repeat('-', 50) . "\n";
$report = $profiler->generatePerformanceReport();
echo "\nSystem-Wide Performance Report\n";
echo " Generated at: {$report['generated_at']}\n";
echo " Total Components: {$report['total_components']}\n";
echo " Total Operations: {$report['total_operations']}\n\n";
echo " Component Breakdown:\n";
foreach ($report['components'] as $componentName => $data) {
echo " {$componentName}:\n";
echo " Operations: {$data['operations']}\n";
echo " Total Time: " . number_format($data['total_time_ms'], 2) . "ms\n";
echo " Actions: " . implode(', ', array_keys($data['actions'])) . "\n";
echo "\n";
}
echo str_repeat('=', 50) . "\n\n";
// Example 5: Profiling mit Idempotency
echo "Example 5: Idempotency Profiling\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
$componentId = ComponentId::create('payment', 'order-456');
// Erste Ausführung - kein Cache
$profiler->profileIdempotencyCheck(
$componentId,
'processPayment',
function () {
usleep(500); // 0.5ms - Check cache, not found
return null;
}
);
$tracker->measure(
"livecomponent.payment.processPayment",
\App\Framework\Performance\PerformanceCategory::CUSTOM,
function () use ($tracker) {
$tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(5000)); // 5ms - Actual processing
},
['component' => 'payment', 'action' => 'processPayment']
);
// Zweite Ausführung - Cache Hit
$profiler->profileIdempotencyCheck(
$componentId,
'processPayment',
function () {
usleep(200); // 0.2ms - Cache hit, return cached result
return ['cached' => true];
}
);
echo "\nIdempotency Profiling Timeline:\n";
$idempotencyTimeline = $tracker->generateTimeline();
foreach ($idempotencyTimeline as $event) {
$indent = str_repeat(' ', $event['depth']);
echo sprintf(
" %s[%s] %s (%.2fms)\n",
$indent,
$event['category'],
$event['name'],
$event['duration_ms']
);
}
echo "\n 💡 Cache hit reduced execution from 5.5ms to 0.2ms (96% faster)\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Summary
echo "✅ Action Profiling Examples completed!\n\n";
echo "Key Insights:\n";
echo " • Security checks (CSRF, Auth, Rate Limit) add ~0.5-0.7ms overhead\n";
echo " • Parameter binding with reflection typically ~0.4ms\n";
echo " • Action execution is the main bottleneck (varies by business logic)\n";
echo " • Idempotency caching can provide 90%+ performance improvement\n";
echo " • ActionProfiler provides detailed metrics for optimization\n\n";
echo "Use Cases:\n";
echo " 1. Identify slow security checks\n";
echo " 2. Optimize parameter binding for complex DTOs\n";
echo " 3. Monitor action execution performance over time\n";
echo " 4. Validate idempotency cache effectiveness\n";
echo " 5. Generate system-wide performance reports\n\n";
echo "Next Steps:\n";
echo " 1. Integrate ActionProfiler into production monitoring\n";
echo " 2. Set performance budgets for each action phase\n";
echo " 3. Alert on performance degradation\n";
echo " 4. Use metrics for optimization priority\n\n";

View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Async\AsyncStream;
use App\Framework\Async\AsyncChannel;
use App\Framework\Async\FiberManager;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemTimer;
$clock = new SystemClock();
$timer = new SystemTimer();
$fiberManager = new FiberManager($clock, $timer);
echo "=== AsyncStream Examples ===\n\n";
// Example 1: Simple data transformation pipeline
echo "1. Data Transformation Pipeline:\n";
$result = AsyncStream::range(1, 10, $fiberManager)
->filter(fn($x) => $x % 2 === 0)
->map(fn($x) => $x * $x)
->toArray();
echo "Even numbers squared: " . json_encode($result) . "\n\n";
// Example 2: Large dataset processing with chunking
echo "2. Large Dataset with Chunking:\n";
AsyncStream::range(1, 100, $fiberManager)
->chunk(20)
->map(fn($chunk) => array_sum($chunk))
->forEach(fn($sum) => echo "Chunk sum: $sum\n");
echo "\n";
// Example 3: Data aggregation
echo "3. Data Aggregation:\n";
$users = [
['name' => 'Alice', 'age' => 30, 'city' => 'Berlin'],
['name' => 'Bob', 'age' => 25, 'city' => 'Munich'],
['name' => 'Charlie', 'age' => 35, 'city' => 'Berlin'],
['name' => 'Diana', 'age' => 28, 'city' => 'Munich'],
];
$byCity = AsyncStream::from($users, $fiberManager)
->groupBy(fn($user) => $user['city']);
foreach ($byCity as $city => $users) {
echo "$city: " . count($users) . " users\n";
}
echo "\n";
// Example 4: Complex transformation
echo "4. Complex Transformation:\n";
$avgAge = AsyncStream::from($users, $fiberManager)
->filter(fn($u) => $u['city'] === 'Berlin')
->map(fn($u) => $u['age'])
->reduce(fn($sum, $age) => $sum + $age, 0) / 2;
echo "Average age in Berlin: $avgAge\n\n";
// Example 5: Channel integration
echo "5. Channel Integration:\n";
$channel = new AsyncChannel(capacity: 5);
// Producer fiber
$producer = $fiberManager->asyncCooperative(function () use ($channel, $fiberManager) {
AsyncStream::range(1, 5, $fiberManager)
->map(fn($x) => "Message-$x")
->toChannel($channel);
});
// Consumer using stream
$consumer = $fiberManager->asyncCooperative(function () use ($channel, $fiberManager) {
$messages = AsyncStream::fromChannel($channel, $fiberManager)
->toArray();
echo "Received: " . json_encode($messages) . "\n";
});
$producer->start();
$consumer->start();
while (!$producer->isTerminated() || !$consumer->isTerminated()) {
if ($producer->isSuspended()) $producer->resume();
if ($consumer->isSuspended()) $consumer->resume();
}
echo "\n=== All Examples Completed ===\n";

244
examples/curl-oop-usage.php Normal file
View File

@@ -0,0 +1,244 @@
<?php
declare(strict_types=1);
/**
* Examples for cURL OOP API usage
*
* Based on PHP RFC: Object-oriented curl API v2
* @link https://wiki.php.net/rfc/curl_oop_v2
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\HttpClient\Curl\Handle;
use App\Framework\HttpClient\Curl\HandleOption;
use App\Framework\HttpClient\Curl\Info;
use App\Framework\HttpClient\Curl\MultiHandle;
use App\Framework\HttpClient\Curl\Exception\HandleException;
// ============================================================================
// Example 1: Simple GET Request
// ============================================================================
echo "=== Example 1: Simple GET Request ===\n";
try {
$handle = new Handle('https://api.github.com/users/anthropics');
// Set options using fluent API
$handle->setOption(HandleOption::UserAgent, 'CustomPHP-Framework/1.0')
->setOption(HandleOption::Timeout, 10);
// Execute and get response
$response = $handle->fetch();
echo "Response received: " . strlen($response) . " bytes\n";
echo "HTTP Code: " . $handle->getInfo(Info::ResponseCode) . "\n";
echo "Total Time: " . $handle->getInfo(Info::TotalTime) . " seconds\n\n";
} catch (HandleException $e) {
echo "Error: " . $e->getMessage() . "\n";
echo "Error Number: " . $handle->errorNumber . "\n";
echo "Error Message: " . $handle->errorMessage . "\n\n";
}
// ============================================================================
// Example 2: POST Request with JSON Body
// ============================================================================
echo "=== Example 2: POST Request with JSON ===\n";
try {
$handle = new Handle('https://httpbin.org/post');
$data = ['name' => 'Test User', 'email' => 'test@example.com'];
$handle->setOptions([
HandleOption::Post => true,
HandleOption::PostFields => json_encode($data),
HandleOption::HttpHeader => [
'Content-Type: application/json',
'Accept: application/json',
],
HandleOption::Timeout => 10,
]);
$response = $handle->fetch();
echo "POST successful\n";
echo "Response Code: " . $handle->getInfo(Info::ResponseCode) . "\n\n";
} catch (HandleException $e) {
echo "POST failed: " . $e->getMessage() . "\n\n";
}
// ============================================================================
// Example 3: Multiple Options with Method Chaining
// ============================================================================
echo "=== Example 3: Fluent API with Method Chaining ===\n";
try {
$handle = new Handle();
$response = $handle
->setOption(HandleOption::Url, 'https://api.github.com/zen')
->setOption(HandleOption::UserAgent, 'PHP-Curl-OOP/1.0')
->setOption(HandleOption::Timeout, 10)
->setOption(HandleOption::FollowLocation, true)
->setOption(HandleOption::MaxRedirs, 5)
->fetch();
echo "GitHub Zen: " . trim($response) . "\n\n";
} catch (HandleException $e) {
echo "Error: " . $e->getMessage() . "\n\n";
}
// ============================================================================
// Example 4: Parallel Requests with MultiHandle
// ============================================================================
echo "=== Example 4: Parallel Requests ===\n";
try {
$multi = new MultiHandle();
// Create multiple handles
$urls = [
'https://api.github.com/users/github',
'https://api.github.com/users/microsoft',
'https://api.github.com/users/google',
];
$handles = [];
foreach ($urls as $url) {
$handle = new Handle($url);
$handle->setOption(HandleOption::Timeout, 10);
$handles[] = $handle;
$multi->addHandle($handle);
}
echo "Executing " . $multi->count() . " parallel requests...\n";
// Execute all requests in parallel
$completed = $multi->executeAll();
echo "Completed " . count($completed) . " requests\n";
// Get results from each handle
foreach ($handles as $i => $handle) {
$responseCode = $handle->getInfo(Info::ResponseCode);
$totalTime = $handle->getInfo(Info::TotalTime);
echo "Request {$i}: HTTP {$responseCode} in {$totalTime}s\n";
}
echo "\n";
} catch (\Exception $e) {
echo "Multi-request error: " . $e->getMessage() . "\n\n";
}
// ============================================================================
// Example 5: Error Handling with Asymmetric Visibility
// ============================================================================
echo "=== Example 5: Error Handling ===\n";
try {
$handle = new Handle('https://invalid-domain-that-does-not-exist-12345.com');
$handle->setOption(HandleOption::Timeout, 5);
$response = $handle->fetch();
} catch (HandleException $e) {
echo "Expected error occurred:\n";
echo "Message: " . $e->getMessage() . "\n";
// Access error properties (public private(set))
echo "Error Number: " . $handle->errorNumber . "\n";
echo "Error Message: " . $handle->errorMessage . "\n";
// Cannot write (compile error if uncommented):
// $handle->errorNumber = 123; // ❌ Error: Cannot write to readonly property
echo "\n";
}
// ============================================================================
// Example 6: Advanced SSL Configuration
// ============================================================================
echo "=== Example 6: SSL Configuration ===\n";
try {
$handle = new Handle('https://www.google.com');
$handle->setOptions([
HandleOption::SslVerifyPeer => true,
HandleOption::SslVerifyHost => 2,
HandleOption::SslVersion => CURL_SSLVERSION_TLSv1_2,
HandleOption::Timeout => 10,
]);
$response = $handle->fetch();
echo "SSL Connection successful\n";
echo "Response Code: " . $handle->getInfo(Info::ResponseCode) . "\n";
echo "SSL Verify Result: " . $handle->getInfo(Info::SslVerifyResult) . "\n\n";
} catch (HandleException $e) {
echo "SSL Error: " . $e->getMessage() . "\n\n";
}
// ============================================================================
// Example 7: Upload File with Progress Callback
// ============================================================================
echo "=== Example 7: File Upload (Simulated) ===\n";
try {
$handle = new Handle('https://httpbin.org/post');
$tempFile = tempnam(sys_get_temp_dir(), 'upload_');
file_put_contents($tempFile, str_repeat('A', 1024 * 100)); // 100KB
$fp = fopen($tempFile, 'r');
$handle->setOptions([
HandleOption::Upload => true,
HandleOption::InFile => $fp,
HandleOption::InFileSize => filesize($tempFile),
HandleOption::Timeout => 30,
]);
echo "Uploading 100KB file...\n";
$response = $handle->fetch();
fclose($fp);
unlink($tempFile);
echo "Upload successful\n";
echo "Response Code: " . $handle->getInfo(Info::ResponseCode) . "\n\n";
} catch (HandleException $e) {
echo "Upload error: " . $e->getMessage() . "\n\n";
}
// ============================================================================
// Example 8: Comprehensive Info Retrieval
// ============================================================================
echo "=== Example 8: Comprehensive Info Retrieval ===\n";
try {
$handle = new Handle('https://www.example.com');
$handle->setOption(HandleOption::Timeout, 10);
$response = $handle->fetch();
echo "=== Request Information ===\n";
echo "Effective URL: " . $handle->getInfo(Info::EffectiveUrl) . "\n";
echo "HTTP Code: " . $handle->getInfo(Info::HttpCode) . "\n";
echo "Total Time: " . $handle->getInfo(Info::TotalTime) . " seconds\n";
echo "Name Lookup Time: " . $handle->getInfo(Info::NameLookupTime) . " seconds\n";
echo "Connect Time: " . $handle->getInfo(Info::ConnectTime) . " seconds\n";
echo "Pre-Transfer Time: " . $handle->getInfo(Info::PreTransferTime) . " seconds\n";
echo "Start Transfer Time: " . $handle->getInfo(Info::StartTransferTime) . " seconds\n";
echo "Size Download: " . $handle->getInfo(Info::SizeDownload) . " bytes\n";
echo "Speed Download: " . $handle->getInfo(Info::SpeedDownload) . " bytes/sec\n";
echo "Header Size: " . $handle->getInfo(Info::HeaderSize) . " bytes\n";
echo "Request Size: " . $handle->getInfo(Info::RequestSize) . " bytes\n";
echo "Content Type: " . ($handle->getInfo(Info::ContentType) ?? 'N/A') . "\n";
// Get all info at once
$allInfo = $handle->getInfo();
echo "\nTotal info keys: " . count($allInfo) . "\n\n";
} catch (HandleException $e) {
echo "Error: " . $e->getMessage() . "\n\n";
}
echo "=== All Examples Completed ===\n";

View File

@@ -0,0 +1,334 @@
<?php
declare(strict_types=1);
/**
* DefaultImplementation Attribute - Real-World Usage Examples
*
* This file demonstrates practical usage of the #[DefaultImplementation] attribute
* in a typical application structure.
*/
namespace App\Examples\DefaultImplementation;
use App\Framework\DI\Attributes\DefaultImplementation;
// =============================================================================
// Example 1: Repository Pattern
// =============================================================================
interface UserRepository
{
public function findById(string $id): ?User;
public function findAll(): array;
public function save(User $user): void;
}
/**
* Database implementation of UserRepository
* Automatically registered as default implementation
*/
#[DefaultImplementation(UserRepository::class)]
final readonly class DatabaseUserRepository implements UserRepository
{
public function __construct(
private DatabaseConnection $db
) {}
public function findById(string $id): ?User
{
// Database query implementation
return null; // Simplified
}
public function findAll(): array
{
return []; // Simplified
}
public function save(User $user): void
{
// Database insert/update implementation
}
}
// =============================================================================
// Example 2: Service Layer
// =============================================================================
interface NotificationService
{
public function send(string $recipient, string $message): void;
}
/**
* Email-based notification service
* Auto-detects NotificationService interface
*/
#[DefaultImplementation] // No explicit interface - auto-detect
final readonly class EmailNotificationService implements NotificationService
{
public function __construct(
private MailerService $mailer
) {}
public function send(string $recipient, string $message): void
{
$this->mailer->sendMail($recipient, 'Notification', $message);
}
}
// =============================================================================
// Example 3: Infrastructure Adapters
// =============================================================================
interface CacheAdapter
{
public function get(string $key): mixed;
public function set(string $key, mixed $value, int $ttl = 3600): void;
public function delete(string $key): void;
}
/**
* Redis cache adapter
* Automatically becomes the default cache implementation
*/
#[DefaultImplementation(CacheAdapter::class)]
final readonly class RedisCacheAdapter implements CacheAdapter
{
public function __construct(
private RedisConnection $redis
) {}
public function get(string $key): mixed
{
return $this->redis->get($key);
}
public function set(string $key, mixed $value, int $ttl = 3600): void
{
$this->redis->setex($key, $ttl, $value);
}
public function delete(string $key): void
{
$this->redis->del($key);
}
}
// =============================================================================
// Example 4: HTTP Client Abstraction
// =============================================================================
interface HttpClient
{
public function get(string $url, array $headers = []): HttpResponse;
public function post(string $url, array $data, array $headers = []): HttpResponse;
}
/**
* Guzzle-based HTTP client
* Auto-detects HttpClient interface
*/
#[DefaultImplementation]
final readonly class GuzzleHttpClient implements HttpClient
{
public function __construct(
private \GuzzleHttp\Client $guzzle
) {}
public function get(string $url, array $headers = []): HttpResponse
{
$response = $this->guzzle->get($url, ['headers' => $headers]);
return new HttpResponse($response->getStatusCode(), (string) $response->getBody());
}
public function post(string $url, array $data, array $headers = []): HttpResponse
{
$response = $this->guzzle->post($url, [
'headers' => $headers,
'json' => $data
]);
return new HttpResponse($response->getStatusCode(), (string) $response->getBody());
}
}
// =============================================================================
// Example 5: Multiple Interfaces (Auto-detect First)
// =============================================================================
interface EventLogger
{
public function logEvent(string $event, array $context): void;
}
interface Flushable
{
public function flush(): void;
}
/**
* File-based event logger with flush capability
* Auto-detects EventLogger (first interface)
*/
#[DefaultImplementation] // Binds to EventLogger, not Flushable
final readonly class FileEventLogger implements EventLogger, Flushable
{
public function __construct(
private string $logFilePath
) {}
public function logEvent(string $event, array $context): void
{
file_put_contents(
$this->logFilePath,
json_encode(['event' => $event, 'context' => $context]) . "\n",
FILE_APPEND
);
}
public function flush(): void
{
file_put_contents($this->logFilePath, '');
}
}
// =============================================================================
// Example 6: Using Default Implementations
// =============================================================================
/**
* Service that depends on default implementations
*/
final readonly class UserService
{
public function __construct(
private UserRepository $userRepository, // DatabaseUserRepository injected
private NotificationService $notifications, // EmailNotificationService injected
private CacheAdapter $cache // RedisCacheAdapter injected
) {}
public function registerUser(string $email, string $name): void
{
// Check cache first
$cachedUser = $this->cache->get("user:$email");
if ($cachedUser !== null) {
return; // User already registered
}
// Create and save user
$user = new User($email, $name);
$this->userRepository->save($user);
// Cache the user
$this->cache->set("user:$email", $user, 3600);
// Send notification
$this->notifications->send($email, "Welcome to our platform, $name!");
}
}
// =============================================================================
// Example 7: Advanced - Combining with Initializers
// =============================================================================
interface PaymentGateway
{
public function charge(int $amountInCents, string $token): PaymentResult;
}
/**
* Stripe payment gateway
* Requires complex initialization via Initializer
*/
#[DefaultImplementation(PaymentGateway::class)]
final readonly class StripePaymentGateway implements PaymentGateway
{
public function __construct(
private StripeApiClient $stripeClient
) {}
public function charge(int $amountInCents, string $token): PaymentResult
{
return $this->stripeClient->createCharge($amountInCents, $token);
}
}
/**
* Initializer for StripeApiClient
* Runs after DefaultImplementation registration
*/
final readonly class StripeInitializer
{
#[\App\Framework\DI\Initializer]
public function initializeStripeClient(): StripeApiClient
{
$apiKey = $_ENV['STRIPE_SECRET_KEY'] ?? throw new \RuntimeException('Missing Stripe API key');
return new StripeApiClient($apiKey, [
'api_version' => '2023-10-16',
'timeout' => 30
]);
}
}
// =============================================================================
// Usage in Application
// =============================================================================
/**
* The container automatically resolves all dependencies:
*
* $container->get(UserService::class)
* -> UserRepository (DatabaseUserRepository)
* -> NotificationService (EmailNotificationService)
* -> CacheAdapter (RedisCacheAdapter)
*
* All instances are singletons - same instance returned on subsequent calls
*/
// =============================================================================
// Stub Classes (for example completeness)
// =============================================================================
class User
{
public function __construct(
public string $email,
public string $name
) {}
}
class DatabaseConnection {}
class MailerService
{
public function sendMail(string $to, string $subject, string $body): void {}
}
class RedisConnection
{
public function get(string $key): mixed { return null; }
public function setex(string $key, int $ttl, mixed $value): void {}
public function del(string $key): void {}
}
class HttpResponse
{
public function __construct(
public int $statusCode,
public string $body
) {}
}
class StripeApiClient
{
public function __construct(string $apiKey, array $options) {}
public function createCharge(int $amount, string $token): PaymentResult
{
return new PaymentResult(true, 'ch_123');
}
}
class PaymentResult
{
public function __construct(
public bool $success,
public string $transactionId
) {}
}

View File

@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\View\Dom\Parser\HtmlParser;
use App\Framework\View\Dom\Query\QuerySelector;
use App\Framework\View\Dom\Renderer\HtmlRenderer;
use App\Framework\View\Dom\Transformer\XComponentTransformer;
// Example HTML
$html = <<<HTML
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Test Document</title>
<script>
console.log("Hello <world>");
</script>
</head>
<body>
<div class="container">
<h1 id="title">Welcome</h1>
<x-counter initial="5" />
<p>Some text content</p>
<!-- This is a comment -->
<x-button color="primary">Click me</x-button>
</div>
</body>
</html>
HTML;
// 1. Parse HTML to AST
$parser = new HtmlParser();
$document = $parser->parse($html);
echo "=== Parsed Document ===\n\n";
// 2. Query DOM
$querySelector = new QuerySelector();
// Find element by ID
$title = $querySelector->querySelector($document, '#title');
if ($title) {
echo "Found title: " . $title->getTextContent() . "\n";
}
// Find elements by class
$containers = $querySelector->querySelectorAll($document, '.container');
echo "Found " . count($containers) . " container(s)\n";
// Find all x-components
$xComponents = $querySelector->querySelectorAll($document, 'x-counter');
echo "Found " . count($xComponents) . " x-counter component(s)\n\n";
// 3. Transform AST using Visitor
$transformer = new XComponentTransformer();
$document->accept($transformer);
$xComponents = $transformer->getXComponents();
echo "=== X-Components found ===\n";
foreach ($xComponents as $component) {
echo "- <" . $component->getTagName() . ">";
foreach ($component->getAttributes() as $attr) {
echo " " . $attr;
}
echo "\n";
}
echo "\n";
// 4. Render back to HTML
$renderer = new HtmlRenderer(pretty: true);
$output = $renderer->render($document);
echo "=== Rendered HTML (pretty) ===\n\n";
echo $output;
// 5. Clone and modify
$cloned = $document->clone();
$clonedTitle = $querySelector->querySelector($cloned, '#title');
if ($clonedTitle instanceof \App\Framework\View\Dom\ElementNode) {
$clonedTitle->setAttribute('class', 'modified');
}
echo "\n=== Modified Clone ===\n\n";
$modifiedOutput = $renderer->render($cloned);
echo substr($modifiedOutput, 0, 500) . "...\n";
echo "\n✅ DOM Parser working successfully!\n";

View File

@@ -0,0 +1,417 @@
<?php
declare(strict_types=1);
/**
* Queue Job Anomaly Detection - Usage Example
*
* Demonstrates ML-based anomaly detection for background queue jobs
* using the Job Anomaly Detection system.
*
* Features Demonstrated:
* - JobHistoryAnalyzer for job pattern analysis
* - JobFeatureExtractor with 8 behavioral features
* - JobAnomalyDetector using Core Score for confidence
* - Job-level, Queue-level, and Failed Jobs analysis
* - Health monitoring and recommendations
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Queue\MachineLearning\JobHistoryAnalyzer;
use App\Framework\Queue\MachineLearning\JobFeatureExtractor;
use App\Framework\Queue\MachineLearning\JobAnomalyDetector;
use App\Framework\Queue\MachineLearning\ValueObjects\JobExecutionContext;
use App\Framework\Queue\MachineLearning\ValueObjects\JobExecutionSequence;
use App\Framework\Queue\MachineLearning\ValueObjects\JobFeatures;
use App\Framework\Queue\Services\JobMetricsManagerInterface;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Score;
use App\Framework\Core\ValueObjects\Timestamp;
echo "=== Queue Job Anomaly Detection Demo ===\n\n";
// ========================================
// 1. Setup Components (Mock for Demo)
// ========================================
echo "1. Initializing Job Anomaly Detection components...\n";
// Mock JobMetricsManager for demonstration
$metricsManager = new class implements JobMetricsManagerInterface {
public function getJobMetrics(string $jobId): ?\App\Framework\Queue\ValueObjects\JobMetrics
{
// Mock: Return sample job metrics
return new \App\Framework\Queue\ValueObjects\JobMetrics(
jobId: $jobId,
queueName: 'email-queue',
status: 'completed',
attempts: 2,
maxAttempts: 3,
executionTimeMs: 1250.5,
memoryUsageBytes: 52428800, // 50 MB
errorMessage: null,
createdAt: date('Y-m-d H:i:s', strtotime('-1 hour')),
startedAt: date('Y-m-d H:i:s', strtotime('-59 minutes')),
completedAt: date('Y-m-d H:i:s', strtotime('-58 minutes')),
failedAt: null,
metadata: []
);
}
public function getQueueMetrics(string $queueName, string $timeWindow): \App\Framework\Queue\ValueObjects\QueueMetrics
{
return new \App\Framework\Queue\ValueObjects\QueueMetrics(
queueName: $queueName,
totalJobs: 1000,
completedJobs: 850,
failedJobs: 150,
averageExecutionTime: 1200.0,
peakMemoryUsage: 104857600 // 100 MB
);
}
public function getFailedJobs(?string $queueName, string $timeWindow): array
{
return []; // Mock: No failed jobs
}
public function getPerformanceStats(?string $queueName, string $timeWindow): array
{
return [
'queue_depth' => 50,
'avg_payload_size' => 10240 // 10 KB
];
}
};
$featureExtractor = new JobFeatureExtractor(minConfidence: 0.6);
$anomalyDetector = new JobAnomalyDetector(
anomalyThreshold: Score::medium(), // 50% threshold
zScoreThreshold: 3.0,
iqrMultiplier: 1.5
);
$historyAnalyzer = new JobHistoryAnalyzer(
$metricsManager,
$featureExtractor,
$anomalyDetector
);
echo "✓ Components initialized\n\n";
// ========================================
// 2. Simulate Normal Job Execution
// ========================================
echo "2. Simulating normal job execution pattern...\n";
$normalExecutions = [];
for ($i = 1; $i <= 10; $i++) {
$normalExecutions[] = new JobExecutionContext(
jobId: "job-{$i}",
queueName: 'email-queue',
status: 'completed',
attempts: 1,
maxAttempts: 3,
executionTimeMs: 1000.0 + ($i * 50), // Slight variance
memoryUsageBytes: 50 * 1024 * 1024, // 50 MB
errorMessage: null,
createdAt: Timestamp::fromString("-{$i} minutes"),
startedAt: Timestamp::fromString("-{$i} minutes"),
completedAt: Timestamp::fromString("-{$i} minutes"),
failedAt: null,
queueDepth: 10 + $i,
payloadSizeBytes: 10240, // 10 KB
metadata: []
);
}
$normalSequence = JobExecutionSequence::fromExecutions($normalExecutions);
echo "✓ Created {$normalSequence->count()} normal job executions\n";
$normalFeatures = $featureExtractor->extract($normalSequence);
echo " Features extracted:\n";
echo " - Execution Time Variance: " . round($normalFeatures->executionTimeVariance, 3) . "\n";
echo " - Memory Usage Pattern: " . round($normalFeatures->memoryUsagePattern, 3) . "\n";
echo " - Failure Rate: " . round($normalFeatures->failureRate, 3) . "\n";
echo " - Queue Depth Correlation: " . round($normalFeatures->queueDepthCorrelation, 3) . "\n\n";
$normalResult = $anomalyDetector->detect($normalFeatures);
echo " Anomaly Detection: " . ($normalResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$normalResult->anomalyScore->toString()}\n";
echo " Severity: {$normalResult->getSeverity()}\n\n";
// ========================================
// 3. Simulate High Failure Rate Pattern
// ========================================
echo "3. Simulating high failure rate pattern...\n";
$failedExecutions = [];
for ($i = 1; $i <= 10; $i++) {
$status = $i <= 7 ? 'failed' : 'completed'; // 70% failure rate
$failedExecutions[] = new JobExecutionContext(
jobId: "failing-job-{$i}",
queueName: 'data-processing',
status: $status,
attempts: $status === 'failed' ? 3 : 1, // Max retries on failures
maxAttempts: 3,
executionTimeMs: 2500.0,
memoryUsageBytes: 100 * 1024 * 1024, // 100 MB
errorMessage: $status === 'failed' ? 'Database connection timeout' : null,
createdAt: Timestamp::fromString("-{$i} minutes"),
startedAt: Timestamp::fromString("-{$i} minutes"),
completedAt: $status === 'completed' ? Timestamp::fromString("-{$i} minutes") : null,
failedAt: $status === 'failed' ? Timestamp::fromString("-{$i} minutes") : null,
queueDepth: 50,
payloadSizeBytes: 20480, // 20 KB
metadata: []
);
}
$failedSequence = JobExecutionSequence::fromExecutions($failedExecutions);
echo "✓ Created {$failedSequence->count()} job executions with high failure rate\n";
$failedFeatures = $featureExtractor->extract($failedSequence);
echo " Features extracted:\n";
echo " - Failure Rate: " . round($failedFeatures->failureRate, 3) . " 🚨\n";
echo " - Retry Frequency: " . round($failedFeatures->retryFrequency, 3) . " 🚨\n";
echo " - Memory Usage Pattern: " . round($failedFeatures->memoryUsagePattern, 3) . "\n\n";
$failedResult = $anomalyDetector->detect($failedFeatures);
echo " Anomaly Detection: " . ($failedResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$failedResult->anomalyScore->toString()} 🚨\n";
echo " Severity: {$failedResult->getSeverity()}\n";
echo " Primary Indicator: {$failedResult->primaryIndicator}\n";
echo " Recommended Action: {$failedResult->getRecommendedAction()}\n";
if (!empty($failedResult->detectedPatterns)) {
echo " Detected Patterns:\n";
foreach ($failedResult->detectedPatterns as $pattern) {
echo " - {$pattern['type']}: {$pattern['description']}\n";
}
}
echo "\n";
// ========================================
// 4. Simulate Performance Degradation
// ========================================
echo "4. Simulating performance degradation pattern...\n";
$degradedExecutions = [];
for ($i = 1; $i <= 10; $i++) {
// Execution time increases dramatically
$executionTime = 1000.0 + ($i * 500); // Exponential growth
// Memory usage also increases (potential leak)
$memoryUsage = (50 + ($i * 10)) * 1024 * 1024; // 50 MB → 150 MB
$degradedExecutions[] = new JobExecutionContext(
jobId: "slow-job-{$i}",
queueName: 'image-processing',
status: 'completed',
attempts: 1,
maxAttempts: 3,
executionTimeMs: $executionTime,
memoryUsageBytes: $memoryUsage,
errorMessage: null,
createdAt: Timestamp::fromString("-{$i} minutes"),
startedAt: Timestamp::fromString("-{$i} minutes"),
completedAt: Timestamp::fromString("-{$i} minutes"),
failedAt: null,
queueDepth: 100 + ($i * 5), // Queue depth increases with time
payloadSizeBytes: 102400, // 100 KB
metadata: []
);
}
$degradedSequence = JobExecutionSequence::fromExecutions($degradedExecutions);
echo "✓ Created {$degradedSequence->count()} job executions with performance degradation\n";
$degradedFeatures = $featureExtractor->extract($degradedSequence);
echo " Features extracted:\n";
echo " - Execution Time Variance: " . round($degradedFeatures->executionTimeVariance, 3) . " 🚨\n";
echo " - Memory Usage Pattern: " . round($degradedFeatures->memoryUsagePattern, 3) . " 🚨\n";
echo " - Queue Depth Correlation: " . round($degradedFeatures->queueDepthCorrelation, 3) . "\n\n";
$degradedResult = $anomalyDetector->detect($degradedFeatures);
echo " Anomaly Detection: " . ($degradedResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$degradedResult->anomalyScore->toString()} 🚨\n";
echo " Severity: {$degradedResult->getSeverity()}\n";
echo " Recommended Action: {$degradedResult->getRecommendedAction()}\n\n";
// ========================================
// 5. Simulate Automated/Bot Execution
// ========================================
echo "5. Simulating automated/bot execution pattern...\n";
$botExecutions = [];
for ($i = 1; $i <= 10; $i++) {
// Perfect timing regularity (exactly 60 seconds apart)
$createdAt = Timestamp::fromString("-" . ($i * 60) . " seconds");
// Identical execution characteristics
$botExecutions[] = new JobExecutionContext(
jobId: "bot-job-{$i}",
queueName: 'api-requests',
status: 'completed',
attempts: 1,
maxAttempts: 3,
executionTimeMs: 500.0, // Exactly 500ms every time
memoryUsageBytes: 20 * 1024 * 1024, // Exactly 20 MB
errorMessage: null,
createdAt: $createdAt,
startedAt: $createdAt,
completedAt: $createdAt,
failedAt: null,
queueDepth: 10,
payloadSizeBytes: 5120, // Exactly 5 KB
metadata: []
);
}
$botSequence = JobExecutionSequence::fromExecutions($botExecutions);
echo "✓ Created {$botSequence->count()} bot-like job executions\n";
$botFeatures = $featureExtractor->extract($botSequence);
echo " Features extracted:\n";
echo " - Execution Timing Regularity: " . round($botFeatures->executionTimingRegularity, 3) . " 🚨\n";
echo " - Execution Time Variance: " . round($botFeatures->executionTimeVariance, 3) . "\n";
echo " - Payload Size Anomaly: " . round($botFeatures->payloadSizeAnomaly, 3) . "\n\n";
$botResult = $anomalyDetector->detect($botFeatures);
echo " Anomaly Detection: " . ($botResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$botResult->anomalyScore->toString()}\n";
echo " Severity: {$botResult->getSeverity()}\n";
if ($botResult->hasPattern('automated_execution')) {
echo " ⚠️ Automated execution pattern detected\n";
$pattern = $botResult->getPattern('automated_execution');
echo " Description: {$pattern['description']}\n";
}
echo "\n";
// ========================================
// 6. JobHistoryAnalyzer Integration
// ========================================
echo "6. JobHistoryAnalyzer integration...\n\n";
// Analyze specific job
echo " Analyzing specific job:\n";
$jobResult = $historyAnalyzer->analyzeJob('job-123', Duration::fromHours(1));
echo " Status: " . ($jobResult->isAnomalous ? 'ANOMALOUS' : 'NORMAL') . "\n";
echo " Score: {$jobResult->anomalyScore->toString()}\n";
echo " Action: {$jobResult->getRecommendedAction()}\n\n";
// Analyze queue
echo " Analyzing queue:\n";
$queueResult = $historyAnalyzer->analyzeQueue('email-queue', Duration::fromHours(1));
echo " Status: " . ($queueResult->isAnomalous ? 'ANOMALOUS' : 'NORMAL') . "\n";
echo " Score: {$queueResult->anomalyScore->toString()}\n\n";
// Get queue health summary
echo " Queue Health Summary:\n";
$healthSummary = $historyAnalyzer->getQueueHealthSummary('email-queue', Duration::fromHours(1));
echo " Queue: {$healthSummary['queue_name']}\n";
echo " Health Status: {$healthSummary['health_status']}\n";
echo " Total Jobs: {$healthSummary['metrics_summary']['total_jobs']}\n";
echo " Completion Rate: {$healthSummary['metrics_summary']['completion_rate']}%\n";
echo " Recommendations:\n";
foreach ($healthSummary['recommendations'] as $recommendation) {
echo " - {$recommendation}\n";
}
echo "\n";
// ========================================
// 7. Feature Analysis
// ========================================
echo "7. Detailed feature analysis comparison:\n\n";
echo " Normal Traffic Features:\n";
foreach ($normalFeatures->toArray() as $feature => $value) {
echo " - " . str_pad($feature, 35) . ": " . round($value, 3) . "\n";
}
echo "\n";
echo " High Failure Rate Features:\n";
foreach ($failedFeatures->toArray() as $feature => $value) {
$indicator = $value > 0.5 ? " 🚨" : "";
echo " - " . str_pad($feature, 35) . ": " . round($value, 3) . $indicator . "\n";
}
echo "\n";
echo " Performance Degradation Features:\n";
foreach ($degradedFeatures->toArray() as $feature => $value) {
$indicator = $value > 0.5 ? " 🚨" : "";
echo " - " . str_pad($feature, 35) . ": " . round($value, 3) . $indicator . "\n";
}
echo "\n";
// ========================================
// 8. Top Contributors Analysis
// ========================================
echo "8. Top contributing features to anomalies:\n\n";
if ($failedResult->isAnomalous) {
echo " Failed Jobs Anomaly - Top Contributors:\n";
foreach ($failedResult->getTopContributors(3) as $contributor) {
echo " - {$contributor['feature']}: {$contributor['score']->toString()} ";
echo "({$contributor['contribution_percentage']}% contribution)\n";
}
echo "\n";
}
if ($degradedResult->isAnomalous) {
echo " Performance Degradation - Top Contributors:\n";
foreach ($degradedResult->getTopContributors(3) as $contributor) {
echo " - {$contributor['feature']}: {$contributor['score']->toString()} ";
echo "({$contributor['contribution_percentage']}% contribution)\n";
}
echo "\n";
}
// ========================================
// 9. Statistics Summary
// ========================================
echo "9. Execution sequence statistics:\n\n";
echo " Normal Traffic:\n";
$normalStats = $normalSequence->getStatistics();
foreach ($normalStats as $key => $value) {
echo " - " . str_pad($key, 30) . ": {$value}\n";
}
echo "\n";
echo " Failed Jobs:\n";
$failedStats = $failedSequence->getStatistics();
foreach ($failedStats as $key => $value) {
echo " - " . str_pad($key, 30) . ": {$value}\n";
}
echo "\n";
echo "=== Demo Complete ===\n\n";
echo "Summary:\n";
echo "✓ Job Anomaly Detection successfully detects:\n";
echo " - High failure rates with excessive retries\n";
echo " - Performance degradation (execution time variance + memory growth)\n";
echo " - Resource exhaustion (queue depth correlation)\n";
echo " - Automated/bot execution patterns (timing regularity)\n";
echo " - Data processing anomalies (payload size variations)\n\n";
echo "✓ Uses Core Score for confidence levels (0-100)\n";
echo "✓ Provides actionable recommendations per severity\n";
echo "✓ Integrates with existing Queue JobMetricsManager\n";
echo "✓ Supports job-level, queue-level, and batch analysis\n";

View File

@@ -0,0 +1,380 @@
<?php
declare(strict_types=1);
/**
* LiveComponent Performance Profiling Usage Examples
*
* Dieses Script demonstriert die Performance-Profiling-Integration
* für LiveComponents mit Timeline-Visualisierung.
*
* Ausführung: php examples/livecomponent-profiling-usage.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
// Tracker initialisieren
$tracker = new NestedPerformanceTracker(
new SystemClock(),
new SystemHighResolutionClock(),
new MemoryMonitor()
);
echo "=== LiveComponent Performance Profiling Examples ===\n\n";
// Example 1: Component Lifecycle Profiling
echo "Example 1: Component Lifecycle Profiling\n";
echo str_repeat('-', 50) . "\n";
// Simuliere kompletten LiveComponent Lifecycle
$tracker->measure(
'livecomponent.counter.increment',
PerformanceCategory::CUSTOM,
function () use ($tracker) {
// 1. Schema Derive/Cache
$tracker->measure(
'livecomponent.schema.derive',
PerformanceCategory::CACHE,
function () {
usleep(500); // 0.5ms - Schema aus Cache
},
['component' => 'counter']
);
// 2. Action Execute
$tracker->measure(
'livecomponent.action.execute',
PerformanceCategory::CUSTOM,
function () {
usleep(2000); // 2ms - Business Logic
},
['action' => 'increment', 'component' => 'counter']
);
// 3. State Validate
$tracker->measure(
'livecomponent.state.validate',
PerformanceCategory::CUSTOM,
function () {
usleep(300); // 0.3ms - Validation
},
['component' => 'counter']
);
// 4. Lifecycle Hook onUpdate
$tracker->measure(
'livecomponent.lifecycle.onUpdate',
PerformanceCategory::CUSTOM,
function () {
usleep(100); // 0.1ms - Hook
},
['component' => 'counter']
);
},
['component' => 'counter', 'action' => 'increment']
);
// Timeline ausgeben
echo "\nComponent Action Timeline:\n";
$timeline = $tracker->generateTimeline();
foreach ($timeline as $event) {
$indent = str_repeat(' ', $event['depth']);
echo sprintf(
" %s[%s] %s (%.2fms)\n",
$indent,
$event['category'],
$event['name'],
$event['duration_ms']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 2: Component Render Profiling
echo "Example 2: Component Render Profiling\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere Component Render mit Cache
$tracker->measure(
'livecomponent.render.user-card',
PerformanceCategory::VIEW,
function () use ($tracker) {
// 1. Cache Get (Hit)
$tracker->measure(
'livecomponent.cache.get',
PerformanceCategory::CACHE,
function () {
usleep(300); // 0.3ms - Cache Hit
return ['html' => '<div>cached</div>', 'needs_refresh' => false];
},
['component' => 'user-card']
);
},
['component' => 'user-card']
);
// Simuliere Component Render ohne Cache
$tracker->measure(
'livecomponent.render.product-list',
PerformanceCategory::VIEW,
function () use ($tracker) {
// 1. Cache Get (Miss)
$tracker->measure(
'livecomponent.cache.get',
PerformanceCategory::CACHE,
function () {
usleep(200); // 0.2ms - Cache Miss
return ['html' => null, 'needs_refresh' => false];
},
['component' => 'product-list']
);
// 2. Get Render Data
$tracker->measure(
'livecomponent.getRenderData',
PerformanceCategory::CUSTOM,
function () {
usleep(1000); // 1ms - Data preparation
},
['component' => 'product-list']
);
// 3. Template Render
$tracker->measure(
'livecomponent.template.render',
PerformanceCategory::TEMPLATE,
function () use ($tracker) {
usleep(5000); // 5ms - Template rendering
// Nested: Template processors
$tracker->measure(
'template.processor.placeholder',
PerformanceCategory::TEMPLATE,
function () {
usleep(1000); // 1ms
}
);
$tracker->measure(
'template.processor.component',
PerformanceCategory::TEMPLATE,
function () {
usleep(2000); // 2ms
}
);
},
['component' => 'product-list', 'template' => 'components/product-list.view.php']
);
// 4. Cache Set
$tracker->measure(
'livecomponent.cache.set',
PerformanceCategory::CACHE,
function () {
usleep(400); // 0.4ms - Cache storage
},
['component' => 'product-list']
);
},
['component' => 'product-list']
);
echo "\nComponent Render Timeline:\n";
$timeline = $tracker->generateTimeline();
foreach ($timeline as $event) {
$indent = str_repeat(' ', $event['depth']);
$contextInfo = !empty($event['context']['template'])
? " ({$event['context']['template']})"
: '';
echo sprintf(
" %s[%s] %s%s (%.2fms self, %.2fms total)\n",
$indent,
$event['category'],
$event['name'],
$contextInfo,
$event['self_time_ms'],
$event['duration_ms']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 3: Multiple Component Actions (Flamegraph)
echo "Example 3: Multiple Component Actions (Flamegraph)\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere mehrere Component Actions
for ($i = 0; $i < 3; $i++) {
$tracker->measure(
'livecomponent.search.updateQuery',
PerformanceCategory::CUSTOM,
function () use ($tracker) {
$tracker->measure(
'livecomponent.action.execute',
PerformanceCategory::CUSTOM,
function () {
usleep(3000); // 3ms
}
);
$tracker->measure(
'livecomponent.state.validate',
PerformanceCategory::CUSTOM,
function () {
usleep(500); // 0.5ms
}
);
},
['component' => 'search', 'action' => 'updateQuery']
);
}
echo "\nFlamegraph Data (aggregated):\n";
$flamegraph = $tracker->generateFlamegraph();
foreach ($flamegraph as $entry) {
echo sprintf(
" %s → %.1f samples\n",
$entry['stack_trace'],
$entry['samples']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 4: Performance Budget Validation for LiveComponents
echo "Example 4: Performance Budget Validation\n";
echo str_repeat('-', 50) . "\n";
$budgets = [
'livecomponent.action.execute' => 5, // max 5ms for actions
'livecomponent.template.render' => 10, // max 10ms for templates
'livecomponent.cache.get' => 1, // max 1ms for cache
'livecomponent.render' => 20, // max 20ms total render
];
$violations = [];
foreach ($timeline as $event) {
foreach ($budgets as $operation => $budget) {
if (str_contains($event['name'], $operation)) {
if ($event['duration_ms'] > $budget) {
$violations[] = [
'operation' => $event['name'],
'component' => $event['context']['component'] ?? 'unknown',
'duration' => $event['duration_ms'],
'budget' => $budget,
'exceeded_by' => $event['duration_ms'] - $budget,
'percentage' => (($event['duration_ms'] - $budget) / $budget) * 100
];
}
}
}
}
if (!empty($violations)) {
echo "\n⚠️ Performance Budget Violations:\n";
foreach ($violations as $violation) {
echo sprintf(
" • [%s] %s: %.2fms (budget: %.2fms, exceeded by %.2fms / %.1f%%)\n",
$violation['component'],
$violation['operation'],
$violation['duration'],
$violation['budget'],
$violation['exceeded_by'],
$violation['percentage']
);
}
} else {
echo "\n✅ All LiveComponent operations within performance budget!\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 5: Export für Chrome DevTools
echo "Example 5: Chrome DevTools Export\n";
echo str_repeat('-', 50) . "\n";
// Generate full timeline with all examples
$fullTimeline = $tracker->generateTimeline();
// Convert to Chrome Trace Event Format
$traceEvents = [];
foreach ($fullTimeline as $event) {
// Begin Event
$traceEvents[] = [
'name' => $event['name'],
'cat' => $event['category'],
'ph' => 'B',
'ts' => (int)($event['start_time'] * 1_000_000),
'pid' => 1,
'tid' => 1,
'args' => $event['context']
];
// End Event
$traceEvents[] = [
'name' => $event['name'],
'cat' => $event['category'],
'ph' => 'E',
'ts' => (int)($event['end_time'] * 1_000_000),
'pid' => 1,
'tid' => 1
];
}
$chromeTrace = [
'traceEvents' => $traceEvents,
'displayTimeUnit' => 'ms',
'otherData' => [
'version' => '1.0',
'framework' => 'Custom PHP Framework - LiveComponents',
'profiler' => 'NestedPerformanceTracker'
]
];
$chromeTraceFile = __DIR__ . '/../tests/tmp/livecomponent-trace.json';
@mkdir(dirname($chromeTraceFile), 0755, true);
file_put_contents($chromeTraceFile, json_encode($chromeTrace, JSON_PRETTY_PRINT));
echo "\nChrome Trace saved to: {$chromeTraceFile}\n";
echo "View in Chrome DevTools:\n";
echo " 1. Open Chrome and navigate to: chrome://tracing\n";
echo " 2. Click 'Load' and select: {$chromeTraceFile}\n";
echo " 3. Explore the LiveComponent lifecycle timeline\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Summary
echo "✅ LiveComponent Performance Profiling Examples completed!\n\n";
echo "Generated Files:\n";
echo "{$chromeTraceFile}\n\n";
echo "Key Insights:\n";
echo " • LiveComponent actions are fully traced with nested operations\n";
echo " • Component render pipeline is profiled (cache → render → template)\n";
echo " • Lifecycle hooks (onMount, onUpdate) are measured\n";
echo " • Performance budgets can be validated per component\n";
echo " • Chrome DevTools integration for visual analysis\n\n";
echo "Next Steps:\n";
echo " 1. Load trace in Chrome DevTools for visual timeline\n";
echo " 2. Identify slow component actions and rendering\n";
echo " 3. Set performance budgets for production monitoring\n";
echo " 4. Integrate with logging for continuous profiling\n\n";

View File

@@ -0,0 +1,414 @@
<?php
declare(strict_types=1);
/**
* Memory Profiling Usage Examples
*
* Dieses Script demonstriert die erweiterten Memory-Profiling-Funktionen
* mit dem MemoryProfiler für detaillierte Memory-Analyse.
*
* Ausführung: php examples/memory-profiling-usage.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\Performance\MemoryProfiler;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
// Initialize tracker and profiler
$tracker = new NestedPerformanceTracker(
new SystemClock(),
new SystemHighResolutionClock(),
new MemoryMonitor()
);
$profiler = new MemoryProfiler($tracker);
echo "=== Memory Profiling Examples ===\n\n";
// Example 1: Memory Hotspot Identification
echo "Example 1: Memory Hotspot Identification\n";
echo str_repeat('-', 50) . "\n";
// Simuliere verschiedene Operations mit unterschiedlichem Memory-Verbrauch
$tracker->measure(
'database.query.large_result',
PerformanceCategory::DATABASE,
function () {
// Simuliere große Datenbank-Abfrage
$data = array_fill(0, 10000, str_repeat('x', 100)); // ~1MB
usleep(5000); // 5ms
}
);
$tracker->measure(
'cache.load',
PerformanceCategory::CACHE,
function () {
// Simuliere Cache-Load
$data = array_fill(0, 1000, str_repeat('x', 100)); // ~0.1MB
usleep(1000); // 1ms
}
);
$tracker->measure(
'api.process',
PerformanceCategory::API,
function () {
// Simuliere API Processing
$data = array_fill(0, 5000, str_repeat('x', 100)); // ~0.5MB
usleep(3000); // 3ms
}
);
echo "\nMemory Hotspots (Top 5):\n";
$hotspots = $profiler->getMemoryHotspots(5);
foreach ($hotspots as $index => $hotspot) {
echo sprintf(
" %d. %s [%s]\n" .
" Memory: %.2fMB | Duration: %.2fms | Memory/ms: %.4fMB\n",
$index + 1,
$hotspot['operation'],
$hotspot['category'],
$hotspot['memory_mb'],
$hotspot['duration_ms'],
$hotspot['memory_per_ms']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 2: Memory Leak Detection
echo "Example 2: Memory Leak Detection\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere potentielle Memory Leaks
for ($i = 0; $i < 5; $i++) {
$tracker->measure(
"iteration.{$i}",
PerformanceCategory::CUSTOM,
function () use ($i) {
// Simuliere steigendes Memory (Leak Pattern)
$data = array_fill(0, ($i + 1) * 2000, str_repeat('x', 100));
usleep(2000);
}
);
}
$leakDetection = $profiler->detectMemoryLeaks(0.5); // 0.5MB threshold
echo "\nMemory Leak Detection Results:\n";
echo " Threshold: {$leakDetection['threshold_mb']}MB\n";
echo " Potential Leaks Found: {$leakDetection['leak_count']}\n";
echo " Total Memory Growth: {$leakDetection['total_memory_growth_mb']}MB\n\n";
if (!empty($leakDetection['potential_leaks'])) {
echo " Detected Leaks:\n";
foreach ($leakDetection['potential_leaks'] as $leak) {
echo sprintf(
" • %s: %.2fMB allocated (Cumulative: %.2fMB)\n",
$leak['operation'],
$leak['memory_allocated_mb'],
$leak['cumulative_memory_mb']
);
}
} else {
echo " ✅ No memory leaks detected\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 3: Memory Efficiency Scoring
echo "Example 3: Memory Efficiency Scoring\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere effiziente vs. ineffiziente Operations
$tracker->measure(
'efficient.operation',
PerformanceCategory::CUSTOM,
function () {
$data = array_fill(0, 100, str_repeat('x', 10)); // Small memory
usleep(1000); // 1ms
}
);
$tracker->measure(
'inefficient.operation',
PerformanceCategory::CUSTOM,
function () {
$data = array_fill(0, 10000, str_repeat('x', 100)); // Large memory
usleep(1000); // 1ms (same time, more memory)
}
);
$efficiency = $profiler->calculateEfficiencyScore();
echo "\nMemory Efficiency Score:\n";
echo " Score: {$efficiency['score']}/100\n";
echo " Rating: {$efficiency['rating']}\n";
echo " Total Memory: {$efficiency['total_memory_mb']}MB\n";
echo " Total Time: {$efficiency['total_time_ms']}ms\n";
echo " Memory per ms: {$efficiency['memory_per_ms']}MB\n";
$ratingColor = match ($efficiency['rating']) {
'Excellent' => '✅',
'Good' => '👍',
'Fair' => '⚠️',
'Poor' => '❌',
'Critical' => '🚨',
default => ''
};
echo "\n {$ratingColor} {$efficiency['rating']} - ";
echo match ($efficiency['rating']) {
'Excellent' => "Sehr geringe Memory-Nutzung",
'Good' => "Akzeptable Memory-Nutzung",
'Fair' => "Durchschnittliche Memory-Nutzung",
'Poor' => "Hohe Memory-Nutzung - Optimierung empfohlen",
'Critical' => "Kritische Memory-Nutzung - Sofortige Optimierung erforderlich",
default => "Keine Daten verfügbar"
};
echo "\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 4: Comprehensive Memory Report
echo "Example 4: Comprehensive Memory Report\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere gemischte Operations
$categories = [
['category' => PerformanceCategory::DATABASE, 'count' => 3],
['category' => PerformanceCategory::CACHE, 'count' => 2],
['category' => PerformanceCategory::API, 'count' => 4],
['category' => PerformanceCategory::TEMPLATE, 'count' => 1]
];
foreach ($categories as $categoryConfig) {
$category = $categoryConfig['category'];
$count = $categoryConfig['count'];
for ($i = 0; $i < $count; $i++) {
$tracker->measure(
"{$category->value}_operation_{$i}",
$category,
function () use ($i) {
$size = rand(100, 5000);
$data = array_fill(0, $size, str_repeat('x', 10));
usleep(rand(500, 2000));
}
);
}
}
$report = $profiler->generateMemoryReport();
echo "\nMemory Report Summary:\n";
echo " Total Operations: {$report['summary']['total_operations']}\n";
echo " Total Memory: {$report['summary']['total_memory_mb']}MB\n";
echo " Avg Memory per Operation: {$report['summary']['avg_memory_per_operation_mb']}MB\n";
echo " Peak Memory: {$report['summary']['peak_memory_mb']}MB\n\n";
echo " Memory by Category:\n";
foreach ($report['by_category'] as $category => $data) {
echo sprintf(
" • %s: %.2fMB total (%.4fMB avg, %.2fMB peak, %d ops)\n",
$category,
$data['total_memory_mb'],
$data['avg_memory_mb'],
$data['peak_memory_mb'],
$data['operations']
);
}
echo "\n Top Memory Hotspots:\n";
foreach ($report['hotspots'] as $index => $hotspot) {
echo sprintf(
" %d. %s: %.2fMB\n",
$index + 1,
$hotspot['operation'],
$hotspot['memory_mb']
);
}
echo "\n Efficiency: {$report['efficiency']['score']}/100 ({$report['efficiency']['rating']})\n";
echo " Leak Detection: {$report['leaks']['leak_count']} potential leaks\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 5: Memory Over Time Tracking
echo "Example 5: Memory Over Time Tracking\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere wachsende Memory-Nutzung über Zeit
for ($i = 0; $i < 10; $i++) {
$tracker->measure(
"timestep_{$i}",
PerformanceCategory::CUSTOM,
function () use ($i) {
// Memory wächst über Zeit
$size = ($i + 1) * 500;
$data = array_fill(0, $size, str_repeat('x', 10));
usleep(1000);
}
);
}
$memoryTracking = $profiler->trackMemoryOverTime();
echo "\nMemory Tracking Over Time:\n";
echo " Final Cumulative Memory: {$memoryTracking['final_cumulative_mb']}MB\n";
echo " Trend: {$memoryTracking['trend']}\n\n";
echo " Timeline (first 5 points):\n";
foreach (array_slice($memoryTracking['tracking_points'], 0, 5) as $point) {
echo sprintf(
" • %s: +%.2fMB (Cumulative: %.2fMB)\n",
$point['operation'],
$point['delta_mb'],
$point['cumulative_mb']
);
}
echo "\n 💡 Trend Analysis:\n";
echo " " . match ($memoryTracking['trend']) {
'rapidly_growing' => "⚠️ Memory wächst schnell - Leak-Überprüfung empfohlen",
'growing' => "⚠️ Memory wächst - Monitoring fortsetzen",
'stable' => "✅ Stabiler Memory-Verbrauch",
'decreasing' => "✅ Memory-Nutzung nimmt ab",
'rapidly_decreasing' => "✅ Memory wird schnell freigegeben",
default => " Unzureichende Daten für Trend-Analyse"
};
echo "\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 6: Memory Budget Validation
echo "Example 6: Memory Budget Validation\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere Operations mit Memory-Budgets
$tracker->measure('api.request', PerformanceCategory::API, function () {
$data = array_fill(0, 3000, str_repeat('x', 100)); // ~0.3MB
usleep(2000);
});
$tracker->measure('database.query', PerformanceCategory::DATABASE, function () {
$data = array_fill(0, 15000, str_repeat('x', 100)); // ~1.5MB
usleep(5000);
});
$tracker->measure('cache.get', PerformanceCategory::CACHE, function () {
$data = array_fill(0, 500, str_repeat('x', 100)); // ~0.05MB
usleep(500);
});
// Define memory budgets
$budgets = [
'api.request' => 0.5, // max 0.5MB
'database.query' => 1.0, // max 1MB
'cache.get' => 0.1, // max 0.1MB
];
$budgetViolations = $profiler->getMemoryBudgetViolations($budgets);
echo "\nMemory Budget Validation:\n";
echo " Budgets Checked: {$budgetViolations['budgets_checked']}\n";
echo " Violations Found: {$budgetViolations['violation_count']}\n\n";
if (!empty($budgetViolations['violations'])) {
echo " ⚠️ Budget Violations:\n";
foreach ($budgetViolations['violations'] as $violation) {
echo sprintf(
" • %s: %.2fMB (Budget: %.2fMB, Exceeded by: %.2fMB / %.1f%%)\n",
$violation['operation'],
$violation['memory_mb'],
$violation['budget_mb'],
$violation['exceeded_by_mb'],
$violation['percentage']
);
}
} else {
echo " ✅ All operations within memory budget!\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 7: Operation Comparison
echo "Example 7: Memory Usage Comparison (A/B Testing)\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset();
// Simuliere zwei verschiedene Implementierungen
$tracker->measure('implementation.v1', PerformanceCategory::CUSTOM, function () {
$data = array_fill(0, 10000, str_repeat('x', 100)); // ~1MB
usleep(3000);
});
$tracker->measure('implementation.v2', PerformanceCategory::CUSTOM, function () {
$data = array_fill(0, 5000, str_repeat('x', 100)); // ~0.5MB (optimized)
usleep(3000);
});
$comparison = $profiler->compareOperations('implementation.v1', 'implementation.v2');
echo "\nA/B Comparison Results:\n\n";
echo " Implementation v1:\n";
echo " Memory: {$comparison['operation_1']['memory_mb']}MB\n";
echo " Executions: {$comparison['operation_1']['executions']}\n\n";
echo " Implementation v2:\n";
echo " Memory: {$comparison['operation_2']['memory_mb']}MB\n";
echo " Executions: {$comparison['operation_2']['executions']}\n\n";
echo " Comparison:\n";
echo " Difference: {$comparison['comparison']['difference_mb']}MB\n";
echo " Percentage Diff: {$comparison['comparison']['percentage_diff']}%\n";
echo " Winner: {$comparison['comparison']['winner']}\n";
$savings = abs($comparison['comparison']['percentage_diff']);
if ($savings > 0) {
echo "\n 💡 v2 uses {$savings}% less memory than v1\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Summary
echo "✅ Memory Profiling Examples completed!\n\n";
echo "Key Insights:\n";
echo " • MemoryProfiler provides comprehensive memory analysis\n";
echo " • Memory leak detection helps identify growing allocations\n";
echo " • Efficiency scoring rates memory usage vs. execution time\n";
echo " • Memory budgets ensure operations stay within limits\n";
echo " • A/B testing helps validate memory optimizations\n\n";
echo "Use Cases:\n";
echo " 1. Identify memory hotspots for optimization\n";
echo " 2. Detect and prevent memory leaks\n";
echo " 3. Monitor memory efficiency over time\n";
echo " 4. Validate memory budgets in production\n";
echo " 5. Compare memory usage between implementations\n\n";
echo "Next Steps:\n";
echo " 1. Set memory budgets for critical operations\n";
echo " 2. Monitor memory trends in production\n";
echo " 3. Alert on memory efficiency degradation\n";
echo " 4. Use A/B testing for memory optimizations\n\n";

View File

@@ -0,0 +1,352 @@
<?php
declare(strict_types=1);
/**
* ML Model Management Usage Examples
*
* Comprehensive examples demonstrating all features of the ML Model Management system:
* 1. Model Registration and Versioning
* 2. A/B Testing and Model Comparison
* 3. Real-Time Performance Monitoring
* 4. Automatic Threshold Optimization
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\MachineLearning\ModelManagement\ModelRegistry;
use App\Framework\MachineLearning\ModelManagement\ABTestingService;
use App\Framework\MachineLearning\ModelManagement\ModelPerformanceMonitor;
use App\Framework\MachineLearning\ModelManagement\AutoTuningEngine;
use App\Framework\MachineLearning\ModelManagement\ValueObjects\ModelMetadata;
use App\Framework\MachineLearning\ModelManagement\ValueObjects\ModelType;
use App\Framework\MachineLearning\ModelManagement\ValueObjects\ABTestConfig;
use App\Framework\Core\ValueObjects\Version;
use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\DI\Container;
// ============================================================================
// Setup: Get services from DI container
// ============================================================================
$container = require __DIR__ . '/../bootstrap/container.php';
$registry = $container->get(ModelRegistry::class);
$abTesting = $container->get(ABTestingService::class);
$performanceMonitor = $container->get(ModelPerformanceMonitor::class);
$autoTuning = $container->get(AutoTuningEngine::class);
echo "=== ML Model Management System - Usage Examples ===\n\n";
// ============================================================================
// Example 1: Register N+1 Detection Model Versions
// ============================================================================
echo "1. Model Registration and Versioning\n";
echo str_repeat('-', 60) . "\n";
// Register initial version
$n1DetectorV1 = ModelMetadata::forN1Detector(
version: Version::fromString('1.0.0'),
configuration: [
'threshold' => 0.7,
'window_size' => 100,
'min_cluster_size' => 3,
]
);
$n1DetectorV1 = $n1DetectorV1->withPerformanceMetrics([
'accuracy' => 0.92,
'precision' => 0.89,
'recall' => 0.88,
'f1_score' => 0.885,
'false_positive_rate' => 0.11,
]);
$registry->register($n1DetectorV1);
echo "✓ Registered N+1 Detector v1.0.0\n";
echo " Accuracy: {$n1DetectorV1->getAccuracy()}\n";
echo " F1-Score: {$n1DetectorV1->getF1Score()}\n\n";
// Register improved version
$n1DetectorV11 = ModelMetadata::forN1Detector(
version: Version::fromString('1.1.0'),
configuration: [
'threshold' => 0.75, // Optimized threshold
'window_size' => 100,
'min_cluster_size' => 3,
]
);
$n1DetectorV11 = $n1DetectorV11->withPerformanceMetrics([
'accuracy' => 0.95,
'precision' => 0.93,
'recall' => 0.91,
'f1_score' => 0.92,
'false_positive_rate' => 0.07,
]);
$registry->register($n1DetectorV11);
echo "✓ Registered N+1 Detector v1.1.0 (improved)\n";
echo " Accuracy: {$n1DetectorV11->getAccuracy()}\n";
echo " F1-Score: {$n1DetectorV11->getF1Score()}\n\n";
// Retrieve and list all versions
$allVersions = $registry->getAll('n1-detector');
echo "Total versions registered: " . count($allVersions) . "\n";
foreach ($allVersions as $model) {
echo " - {$model->version->toString()} (Accuracy: {$model->getAccuracy()})\n";
}
echo "\n";
// ============================================================================
// Example 2: A/B Testing - Compare Model Versions
// ============================================================================
echo "2. A/B Testing and Model Comparison\n";
echo str_repeat('-', 60) . "\n";
// Create A/B test configuration
$abTestConfig = ABTestConfig::create(
modelName: 'n1-detector',
versionA: Version::fromString('1.0.0'),
versionB: Version::fromString('1.1.0'),
trafficSplit: 0.5 // 50/50 split
);
echo "Test Configuration:\n";
echo " Model: {$abTestConfig->modelName}\n";
echo " Version A: {$abTestConfig->versionA->toString()} ({$abTestConfig->trafficSplitA * 100}%)\n";
echo " Version B: {$abTestConfig->versionB->toString()} ({$abTestConfig->getTrafficSplitB() * 100}%)\n";
echo " Primary Metric: {$abTestConfig->primaryMetric}\n\n";
// Run A/B test
$abTestResult = $abTesting->runTest($abTestConfig);
echo "A/B Test Results:\n";
echo " Winner: {$abTestResult->winner}\n";
echo " Statistically Significant: " . ($abTestResult->isStatisticallySignificant ? 'Yes' : 'No') . "\n";
echo " Primary Metric Improvement: " . sprintf('%+.2f%%', $abTestResult->getPrimaryMetricImprovementPercent()) . "\n";
echo "\nRecommendation:\n";
echo " {$abTestResult->recommendation}\n\n";
// Metrics comparison
echo "Detailed Metrics Comparison:\n";
$summary = $abTestResult->getMetricsSummary();
echo " Version A ({$abTestConfig->versionA->toString()}):\n";
echo " Accuracy: " . sprintf('%.4f', $summary['version_a']['accuracy']) . "\n";
echo " Precision: " . sprintf('%.4f', $summary['version_a']['precision']) . "\n";
echo " Recall: " . sprintf('%.4f', $summary['version_a']['recall']) . "\n";
echo " F1-Score: " . sprintf('%.4f', $summary['version_a']['f1_score']) . "\n\n";
echo " Version B ({$abTestConfig->versionB->toString()}):\n";
echo " Accuracy: " . sprintf('%.4f', $summary['version_b']['accuracy']) . "\n";
echo " Precision: " . sprintf('%.4f', $summary['version_b']['precision']) . "\n";
echo " Recall: " . sprintf('%.4f', $summary['version_b']['recall']) . "\n";
echo " F1-Score: " . sprintf('%.4f', $summary['version_b']['f1_score']) . "\n\n";
// Gradual rollout plan
if ($abTestResult->shouldDeployVersionB()) {
echo "Gradual Rollout Plan:\n";
$rolloutPlan = $abTesting->generateRolloutPlan(steps: 5);
foreach ($rolloutPlan as $step => $trafficSplitB) {
echo sprintf(
" Step %d: %.0f%% traffic to v%s\n",
$step,
$trafficSplitB * 100,
$abTestConfig->versionB->toString()
);
}
}
echo "\n";
// ============================================================================
// Example 3: Real-Time Performance Monitoring
// ============================================================================
echo "3. Real-Time Performance Monitoring\n";
echo str_repeat('-', 60) . "\n";
// Simulate some predictions
echo "Simulating predictions...\n";
$version = Version::fromString('1.1.0');
// Simulate 20 predictions
for ($i = 0; $i < 20; $i++) {
$prediction = (bool) ($i % 3 !== 0); // Predict false every 3rd
$actual = (bool) ($i % 4 !== 0); // Actual false every 4th
$confidence = 0.75 + ($i * 0.01);
$performanceMonitor->trackPrediction(
modelName: 'n1-detector',
version: $version,
prediction: $prediction,
actual: $actual,
confidence: $confidence
);
}
echo "✓ Tracked 20 predictions\n\n";
// Get current metrics
$currentMetrics = $performanceMonitor->getCurrentMetrics(
'n1-detector',
$version,
Duration::fromHours(1)
);
echo "Current Performance Metrics (last 1 hour):\n";
echo " Total Predictions: {$currentMetrics['total_predictions']}\n";
echo " Correct: {$currentMetrics['correct_predictions']}\n";
echo " Accuracy: " . sprintf('%.4f', $currentMetrics['accuracy']) . "\n";
echo " Precision: " . sprintf('%.4f', $currentMetrics['precision']) . "\n";
echo " Recall: " . sprintf('%.4f', $currentMetrics['recall']) . "\n";
echo " F1-Score: " . sprintf('%.4f', $currentMetrics['f1_score']) . "\n";
echo " Avg Confidence: " . sprintf('%.4f', $currentMetrics['average_confidence']) . "\n\n";
// Check for performance degradation
$degradationInfo = $performanceMonitor->getPerformanceDegradationInfo(
'n1-detector',
$version,
thresholdPercent: 0.05
);
echo "Performance Degradation Check:\n";
echo " Has Degraded: " . ($degradationInfo['has_degraded'] ? 'Yes' : 'No') . "\n";
echo " Baseline Accuracy: " . sprintf('%.4f', $degradationInfo['baseline_accuracy']) . "\n";
echo " Current Accuracy: " . sprintf('%.4f', $degradationInfo['current_accuracy']) . "\n";
echo " Degradation: " . sprintf('%.2f%%', $degradationInfo['degradation_percent']) . "\n";
echo "\nRecommendation:\n";
echo " {$degradationInfo['recommendation']}\n\n";
// Concept drift detection
$hasDrift = $performanceMonitor->detectConceptDrift('n1-detector', $version);
echo "Concept Drift Detected: " . ($hasDrift ? 'Yes' : 'No') . "\n\n";
// ============================================================================
// Example 4: Automatic Threshold Optimization
// ============================================================================
echo "4. Automatic Threshold Optimization\n";
echo str_repeat('-', 60) . "\n";
// Optimize threshold for maximum F1-score
$optimizationResult = $autoTuning->optimizeThreshold(
modelName: 'n1-detector',
version: $version,
metricToOptimize: 'f1_score',
thresholdRange: [0.5, 0.9],
step: 0.05,
timeWindow: Duration::fromHours(1)
);
echo "Threshold Optimization Results:\n";
echo " Current Threshold: " . sprintf('%.2f', $optimizationResult['current_threshold']) . "\n";
echo " Optimal Threshold: " . sprintf('%.2f', $optimizationResult['optimal_threshold']) . "\n";
echo " Current F1-Score: " . sprintf('%.4f', $optimizationResult['current_metric_value']) . "\n";
echo " Optimal F1-Score: " . sprintf('%.4f', $optimizationResult['optimal_metric_value']) . "\n";
echo " Improvement: " . sprintf('%+.2f%%', $optimizationResult['improvement_percent']) . "\n";
echo "\nRecommendation:\n";
echo " {$optimizationResult['recommendation']}\n\n";
// Adaptive threshold adjustment
$adaptiveResult = $autoTuning->adaptiveThresholdAdjustment('n1-detector', $version);
echo "Adaptive Threshold Adjustment:\n";
echo " Current Threshold: " . sprintf('%.2f', $adaptiveResult['current_threshold']) . "\n";
echo " Recommended Threshold: " . sprintf('%.2f', $adaptiveResult['recommended_threshold']) . "\n";
echo " Reason: {$adaptiveResult['adjustment_reason']}\n";
echo "\nExpected Improvement:\n";
echo " Accuracy: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['accuracy']) . "\n";
echo " Precision: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['precision']) . "\n";
echo " Recall: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['recall']) . "\n\n";
// Precision-recall trade-off optimization
$tradeoffResult = $autoTuning->optimizePrecisionRecallTradeoff(
modelName: 'n1-detector',
version: $version,
targetPrecision: 0.95 // Target 95% precision
);
echo "Precision-Recall Trade-off Optimization:\n";
echo " Target Precision: 0.95\n";
echo " Optimal Threshold: " . sprintf('%.2f', $tradeoffResult['optimal_threshold']) . "\n";
echo " Achieved Precision: " . sprintf('%.4f', $tradeoffResult['achieved_precision']) . "\n";
echo " Achieved Recall: " . sprintf('%.4f', $tradeoffResult['achieved_recall']) . "\n";
echo " F1-Score: " . sprintf('%.4f', $tradeoffResult['f1_score']) . "\n\n";
// ============================================================================
// Example 5: Version Comparison Across Multiple Models
// ============================================================================
echo "5. Multi-Version Performance Comparison\n";
echo str_repeat('-', 60) . "\n";
$versions = [
Version::fromString('1.0.0'),
Version::fromString('1.1.0'),
];
$comparison = $performanceMonitor->compareVersions(
'n1-detector',
$versions,
Duration::fromHours(24)
);
echo "Performance Comparison (last 24 hours):\n\n";
foreach ($comparison as $versionStr => $data) {
echo "Version {$versionStr}:\n";
echo " Environment: " . ($data['environment'] ?? 'N/A') . "\n";
echo " Deployed: " . ($data['deployed_at'] ?? 'Not deployed') . "\n";
echo " Current Accuracy: " . sprintf('%.4f', $data['current_metrics']['accuracy']) . "\n";
echo " Total Predictions: {$data['current_metrics']['total_predictions']}\n";
echo "\n";
}
// ============================================================================
// Example 6: Production Deployment Workflow
// ============================================================================
echo "6. Production Deployment Workflow\n";
echo str_repeat('-', 60) . "\n";
// Deploy winning version to production
if ($abTestResult->shouldDeployVersionB()) {
$winningVersion = $abTestResult->getWinningVersion();
echo "Deploying version {$winningVersion->toString()} to production...\n";
// Update model with deployment info
$updatedMetadata = $n1DetectorV11->withDeployment(
environment: 'production',
deployedAt: Timestamp::now()
);
$registry->update($updatedMetadata);
echo "✓ Successfully deployed to production\n";
echo " Environment: {$updatedMetadata->environment}\n";
echo " Deployed At: {$updatedMetadata->deployedAt->format('Y-m-d H:i:s')}\n";
echo "\n";
}
// Get all production models
$productionModels = $registry->getProductionModels();
echo "Active Production Models: " . count($productionModels) . "\n";
foreach ($productionModels as $model) {
echo " - {$model->modelName} v{$model->version->toString()}\n";
echo " Type: {$model->modelType->value}\n";
echo " Accuracy: {$model->getAccuracy()}\n";
echo " Deployed: {$model->deployedAt->format('Y-m-d H:i:s')}\n\n";
}
echo "\n=== Examples Completed Successfully ===\n";

View File

@@ -0,0 +1,378 @@
<?php
declare(strict_types=1);
/**
* ML-Enhanced WAF Behavioral Analysis - Usage Example
*
* Demonstrates the complete integration of ML-based behavioral analysis
* into the WAF system for advanced threat detection.
*
* Features Demonstrated:
* - RequestHistoryTracker for sequence storage
* - BehaviorPatternExtractor with 8 features
* - BehaviorAnomalyDetector using Core Score value object
* - MLEnhancedWafLayer integration with WafEngine
* - Advanced threat detection scenarios
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Waf\WafEngine;
use App\Framework\Waf\Layers\MLEnhancedWafLayer;
use App\Framework\Waf\MachineLearning\BehaviorPatternExtractor;
use App\Framework\Waf\MachineLearning\BehaviorAnomalyDetector;
use App\Framework\Waf\MachineLearning\RequestHistoryTracker;
use App\Framework\Waf\MachineLearning\ValueObjects\BehaviorFeatures;
use App\Framework\Waf\MachineLearning\ValueObjects\RequestSequence;
use App\Framework\Cache\SmartCache;
use App\Framework\Core\ValueObjects\Score;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Http\IpAddress;
use App\Infrastructure\GeoIp\GeoIp;
echo "=== ML-Enhanced WAF Behavioral Analysis Demo ===\n\n";
// ========================================
// 1. Setup Components
// ========================================
echo "1. Initializing ML WAF components...\n";
// Mock cache for demonstration
$cache = new SmartCache(new \App\Framework\Cache\Driver\InMemoryCache());
// Mock GeoIp service
$geoIp = new class {
public function getCountryCode(\App\Framework\Http\IpAddress $ip) {
return new class {
public function toString(): string {
return 'US';
}
};
}
};
// Mock logger
$logger = new class implements \Psr\Log\LoggerInterface {
use \Psr\Log\LoggerTrait;
public function log($level, $message, array $context = []): void {
echo "[{$level}] {$message}\n";
if (!empty($context)) {
echo " Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
}
}
};
// Create components
$historyTracker = new RequestHistoryTracker(
cache: $cache,
maxRequestsPerIp: 50,
timeWindowSeconds: 300
);
$patternExtractor = new BehaviorPatternExtractor(
geoIp: $geoIp,
minConfidence: 0.6
);
$anomalyDetector = new BehaviorAnomalyDetector(
anomalyThreshold: Score::medium(),
zScoreThreshold: 3.0,
iqrMultiplier: 1.5
);
$mlWafLayer = new MLEnhancedWafLayer(
historyTracker: $historyTracker,
patternExtractor: $patternExtractor,
anomalyDetector: $anomalyDetector,
logger: $logger,
confidenceThreshold: Score::medium(),
minHistorySize: 5
);
echo "✓ ML WAF Layer initialized: {$mlWafLayer->getName()} v{$mlWafLayer->getVersion()}\n\n";
// ========================================
// 2. Simulate Normal Traffic Pattern
// ========================================
echo "2. Simulating normal traffic pattern...\n";
$normalIp = new IpAddress('203.0.113.10');
for ($i = 1; $i <= 10; $i++) {
$request = createMockRequest($normalIp, "/page-{$i}", 'GET');
$historyTracker->track($request);
sleep(1); // Normal timing
}
$normalSequence = $historyTracker->getSequence($normalIp);
echo "✓ Tracked {$normalSequence->count()} normal requests\n";
$normalFeatures = $patternExtractor->extract($normalSequence);
echo " Features extracted:\n";
echo " - Request Frequency: " . round($normalFeatures->requestFrequency, 2) . " req/s\n";
echo " - Endpoint Diversity: " . round($normalFeatures->endpointDiversity, 2) . "\n";
echo " - User-Agent Consistency: " . round($normalFeatures->userAgentConsistency, 2) . "\n\n";
$normalAnomalyResult = $anomalyDetector->detect($normalFeatures);
echo " Anomaly Detection: " . ($normalAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$normalAnomalyResult->anomalyScore->toString()}\n";
echo " Indicator: {$normalAnomalyResult->primaryIndicator}\n\n";
// ========================================
// 3. Simulate DDoS Attack Pattern
// ========================================
echo "3. Simulating DDoS attack pattern...\n";
$ddosIp = new IpAddress('198.51.100.42');
// High frequency, same endpoint
for ($i = 1; $i <= 20; $i++) {
$request = createMockRequest($ddosIp, "/api/search", 'GET');
$historyTracker->track($request);
// No sleep - rapid fire
}
$ddosSequence = $historyTracker->getSequence($ddosIp);
echo "✓ Tracked {$ddosSequence->count()} DDoS-like requests\n";
$ddosFeatures = $patternExtractor->extract($ddosSequence);
echo " Features extracted:\n";
echo " - Request Frequency: " . round($ddosFeatures->requestFrequency, 2) . " req/s 🚨\n";
echo " - Endpoint Diversity: " . round($ddosFeatures->endpointDiversity, 2) . " 🚨\n";
echo " - User-Agent Consistency: " . round($ddosFeatures->userAgentConsistency, 2) . "\n\n";
$ddosAnomalyResult = $anomalyDetector->detect($ddosFeatures);
echo " Anomaly Detection: " . ($ddosAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$ddosAnomalyResult->anomalyScore->toString()} 🚨\n";
echo " Severity: {$ddosAnomalyResult->getSeverity()}\n";
echo " Indicator: {$ddosAnomalyResult->primaryIndicator}\n";
echo " Recommended Action: {$ddosAnomalyResult->getRecommendedAction()}\n\n";
// ========================================
// 4. Simulate Bot Pattern
// ========================================
echo "4. Simulating bot pattern...\n";
$botIp = new IpAddress('198.51.100.99');
// Perfect timing regularity with identical payloads
for ($i = 1; $i <= 10; $i++) {
$request = createMockRequest($botIp, "/api/data", 'POST', 'same_payload_data');
$historyTracker->track($request);
usleep(500000); // Exactly 0.5 seconds between requests
}
$botSequence = $historyTracker->getSequence($botIp);
echo "✓ Tracked {$botSequence->count()} bot-like requests\n";
$botFeatures = $patternExtractor->extract($botSequence);
echo " Features extracted:\n";
echo " - Time Pattern Regularity: " . round($botFeatures->timePatternRegularity, 2) . " 🚨\n";
echo " - Payload Similarity: " . round($botFeatures->payloadSimilarity, 2) . " 🚨\n";
echo " - Request Frequency: " . round($botFeatures->requestFrequency, 2) . " req/s\n\n";
$botAnomalyResult = $anomalyDetector->detect($botFeatures);
echo " Anomaly Detection: " . ($botAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n";
echo " Score: {$botAnomalyResult->anomalyScore->toString()}\n";
echo " Severity: {$botAnomalyResult->getSeverity()}\n";
echo " Indicator: {$botAnomalyResult->primaryIndicator}\n";
if (!empty($botAnomalyResult->detectedPatterns)) {
echo " Detected Patterns:\n";
foreach ($botAnomalyResult->detectedPatterns as $pattern) {
echo " - {$pattern['type']}\n";
}
}
echo "\n";
// ========================================
// 5. Test MLEnhancedWafLayer Integration
// ========================================
echo "5. Testing ML WAF Layer integration...\n\n";
// Analyze normal traffic
echo " Analyzing normal traffic through ML WAF Layer:\n";
$normalRequest = createMockRequest($normalIp, "/dashboard", 'GET');
$normalResult = $mlWafLayer->analyze($normalRequest);
echo " Status: " . ($normalResult->isThreat() ? 'THREAT' : 'CLEAN') . "\n";
echo " Message: {$normalResult->getMessage()}\n";
echo " Processing Time: {$normalResult->getProcessingTime()->toMilliseconds()}ms\n\n";
// Analyze DDoS traffic
echo " Analyzing DDoS traffic through ML WAF Layer:\n";
$ddosRequest = createMockRequest($ddosIp, "/api/search", 'GET');
$ddosResult = $mlWafLayer->analyze($ddosRequest);
echo " Status: " . ($ddosResult->isThreat() ? '🚨 THREAT' : 'CLEAN') . "\n";
echo " Message: {$ddosResult->getMessage()}\n";
echo " Processing Time: {$ddosResult->getProcessingTime()->toMilliseconds()}ms\n";
if ($ddosResult->isThreat()) {
$detections = $ddosResult->getDetections();
echo " Detections: " . count($detections) . "\n";
foreach ($detections as $detection) {
echo " - {$detection->category->value}: {$detection->description}\n";
echo " Severity: {$detection->severity->value}, Confidence: {$detection->confidence->getValue()}%\n";
}
}
echo "\n";
// ========================================
// 6. Layer Metrics and Health
// ========================================
echo "6. ML WAF Layer metrics and health status:\n\n";
echo " Layer Name: {$mlWafLayer->getName()}\n";
echo " Version: {$mlWafLayer->getVersion()}\n";
echo " Priority: {$mlWafLayer->getPriority()}\n";
echo " Enabled: " . ($mlWafLayer->isEnabled() ? 'Yes' : 'No') . "\n";
echo " Healthy: " . ($mlWafLayer->isHealthy() ? '✓ Yes' : '❌ No') . "\n";
echo " Confidence Level: {$mlWafLayer->getConfidenceLevel()->getValue()}%\n";
echo " Timeout Threshold: {$mlWafLayer->getTimeoutThreshold()->toMilliseconds()}ms\n";
echo " Supports Parallel Processing: " . ($mlWafLayer->supportsParallelProcessing() ? 'Yes' : 'No') . "\n\n";
echo " Supported Categories:\n";
foreach ($mlWafLayer->getSupportedCategories() as $category) {
echo " - {$category->value}\n";
}
echo "\n";
// ========================================
// 7. Feature Vector Analysis
// ========================================
echo "7. Complete feature vector comparison:\n\n";
echo " Normal Traffic Features:\n";
$normalVector = $normalFeatures->toArray();
foreach ($normalVector as $key => $value) {
echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n";
}
echo "\n";
echo " DDoS Attack Features:\n";
$ddosVector = $ddosFeatures->toArray();
foreach ($ddosVector as $key => $value) {
echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n";
}
echo "\n";
echo " Bot Pattern Features:\n";
$botVector = $botFeatures->toArray();
foreach ($botVector as $key => $value) {
echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n";
}
echo "\n";
// ========================================
// 8. Request History Statistics
// ========================================
echo "8. Request history statistics:\n\n";
$normalStats = $normalSequence->getStatistics();
echo " Normal Traffic Statistics:\n";
foreach ($normalStats as $key => $value) {
echo " - " . str_pad($key, 30) . ": {$value}\n";
}
echo "\n";
$ddosStats = $ddosSequence->getStatistics();
echo " DDoS Traffic Statistics:\n";
foreach ($ddosStats as $key => $value) {
echo " - " . str_pad($key, 30) . ": {$value}\n";
}
echo "\n";
echo "=== Demo Complete ===\n\n";
echo "Summary:\n";
echo "✓ ML WAF Layer successfully detects:\n";
echo " - DDoS attacks (high frequency + low diversity)\n";
echo " - Bot patterns (perfect regularity + high similarity)\n";
echo " - Normal traffic patterns (no anomalies)\n\n";
echo "✓ Uses Core Score value object for confidence levels\n";
echo "✓ Provides detailed feature extraction and analysis\n";
echo "✓ Integrates seamlessly with existing WAF system\n";
// ========================================
// Helper Functions
// ========================================
function createMockRequest(
IpAddress $ip,
string $path,
string $method,
string $body = ''
): \App\Framework\Http\Request {
return new class($ip, $path, $method, $body) implements \App\Framework\Http\Request {
public function __construct(
private readonly IpAddress $ip,
private readonly string $path,
private readonly string $method,
private readonly string $body
) {}
public string $path {
get => $this->path;
}
public object $method {
get => new class($this->method) {
public function __construct(public readonly string $value) {}
};
}
public array $queryParams {
get => [];
}
public string $body {
get => $this->body;
}
public int $timestamp {
get => time();
}
public object $headers {
get => new class {
public function getFirst(string $name): ?string {
return match($name) {
'User-Agent' => 'Mozilla/5.0 (compatible; Bot/1.0)',
'Content-Type' => 'application/json',
'Content-Length' => '0',
default => null
};
}
};
}
public object $server {
get => new class($this->ip) {
public function __construct(private readonly IpAddress $ip) {}
public function getRemoteAddr(): IpAddress {
return $this->ip;
}
};
}
public object $parsedBody {
get => new class {
public array $data {
get => [];
}
};
}
};
}

View File

@@ -0,0 +1,269 @@
<?php
declare(strict_types=1);
/**
* N+1 Detection Model Management Integration Example
*
* Demonstrates how the N+1 Detection ML system integrates with
* the ML Model Management System for versioning, monitoring, and auto-tuning.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneModelAdapter;
use App\Framework\Database\NPlusOneDetection\QueryExecutionContext;
use App\Framework\MachineLearning\ModelManagement\ModelRegistry;
use App\Framework\MachineLearning\ModelManagement\ModelPerformanceMonitor;
use App\Framework\MachineLearning\ModelManagement\AutoTuningEngine;
use App\Framework\Core\ValueObjects\Version;
use App\Framework\Core\ValueObjects\Duration;
// ============================================================================
// Setup: Get services from DI container
// ============================================================================
$container = require __DIR__ . '/../bootstrap/container.php';
$adapter = $container->get(NPlusOneModelAdapter::class);
$registry = $container->get(ModelRegistry::class);
$performanceMonitor = $container->get(ModelPerformanceMonitor::class);
$autoTuning = $container->get(AutoTuningEngine::class);
echo "=== N+1 Detection Model Management Integration ===\n\n";
// ============================================================================
// Example 1: Model Registration
// ============================================================================
echo "1. Model Registration\n";
echo str_repeat('-', 60) . "\n";
// Register current N+1 detector model
$metadata = $adapter->registerCurrentModel();
echo "✓ Registered N+1 Detector Model\n";
echo " Name: {$metadata->modelName}\n";
echo " Version: {$metadata->version->toString()}\n";
echo " Type: {$metadata->modelType->value}\n";
echo " Configuration:\n";
foreach ($metadata->configuration as $key => $value) {
echo " - {$key}: " . json_encode($value) . "\n";
}
echo "\n";
// ============================================================================
// Example 2: Analysis with Automatic Tracking
// ============================================================================
echo "2. Analysis with Automatic Tracking\n";
echo str_repeat('-', 60) . "\n";
// Simulate query execution contexts
$contexts = [
// N+1 pattern detected
new QueryExecutionContext(
query: 'SELECT * FROM users WHERE id = ?',
bindParams: [1],
executionTime: Duration::fromMilliseconds(5),
stackTrace: ['UserRepository::find', 'UserController::show', 'index.php'],
contextData: [
'parent_query' => 'SELECT * FROM posts',
'query_count_in_request' => 15,
'similar_query_count' => 12
]
),
// Normal query (no N+1)
new QueryExecutionContext(
query: 'SELECT * FROM users',
bindParams: [],
executionTime: Duration::fromMilliseconds(25),
stackTrace: ['UserRepository::findAll', 'UserController::index', 'index.php'],
contextData: [
'query_count_in_request' => 3,
'similar_query_count' => 0
]
),
];
foreach ($contexts as $i => $context) {
echo "\nAnalyzing Query " . ($i + 1) . "...\n";
// Analyze with automatic tracking (ground truth provided for training)
$groundTruth = $i === 0; // First query is N+1, second is not
$result = $adapter->analyzeWithTracking($context, $groundTruth);
echo " Query: {$context->query}\n";
echo " Execution Time: {$context->executionTime->toMilliseconds()}ms\n";
echo " Detection Result:\n";
echo " - Success: " . ($result['success'] ? 'Yes' : 'No') . "\n";
echo " - Anomalies Found: " . count($result['anomalies']) . "\n";
echo " - Confidence: " . sprintf('%.2f', $result['overall_confidence']) . "\n";
echo " Tracking Info:\n";
echo " - Prediction: " . ($result['tracking']['prediction'] ? 'N+1 Detected' : 'Normal') . "\n";
echo " - Ground Truth: " . ($groundTruth ? 'N+1 Pattern' : 'Normal Query') . "\n";
echo " - Tracked: " . ($result['tracking']['tracked'] ? 'Yes' : 'No') . "\n";
}
echo "\n";
// ============================================================================
// Example 3: Real-Time Performance Monitoring
// ============================================================================
echo "3. Real-Time Performance Monitoring\n";
echo str_repeat('-', 60) . "\n";
// Get current performance metrics
$metrics = $adapter->getCurrentPerformanceMetrics();
echo "Performance Metrics (last 1 hour):\n";
echo " Total Predictions: {$metrics['total_predictions']}\n";
echo " Correct Predictions: {$metrics['correct_predictions']}\n";
echo " Accuracy: " . sprintf('%.4f', $metrics['accuracy']) . "\n";
echo " Precision: " . sprintf('%.4f', $metrics['precision']) . "\n";
echo " Recall: " . sprintf('%.4f', $metrics['recall']) . "\n";
echo " F1-Score: " . sprintf('%.4f', $metrics['f1_score']) . "\n";
echo " Average Confidence: " . sprintf('%.4f', $metrics['average_confidence']) . "\n";
echo "\n";
// Check for performance degradation
$degradationInfo = $adapter->checkPerformanceDegradation(thresholdPercent: 0.05);
echo "Performance Degradation Check:\n";
echo " Has Degraded: " . ($degradationInfo['has_degraded'] ? 'Yes' : 'No') . "\n";
echo " Baseline Accuracy: " . sprintf('%.4f', $degradationInfo['baseline_accuracy']) . "\n";
echo " Current Accuracy: " . sprintf('%.4f', $degradationInfo['current_accuracy']) . "\n";
echo " Degradation: " . sprintf('%.2f%%', $degradationInfo['degradation_percent']) . "\n";
echo "\nRecommendation: {$degradationInfo['recommendation']}\n\n";
// ============================================================================
// Example 4: Automatic Threshold Optimization
// ============================================================================
echo "4. Automatic Threshold Optimization\n";
echo str_repeat('-', 60) . "\n";
// Optimize confidence threshold for maximum F1-score
$optimizationResult = $autoTuning->optimizeThreshold(
modelName: 'n1-detector',
version: Version::fromString('1.0.0'),
metricToOptimize: 'f1_score',
thresholdRange: [0.5, 0.9],
step: 0.05,
timeWindow: Duration::fromHours(1)
);
echo "Threshold Optimization Results:\n";
echo " Current Threshold: " . sprintf('%.2f', $optimizationResult['current_threshold']) . "\n";
echo " Optimal Threshold: " . sprintf('%.2f', $optimizationResult['optimal_threshold']) . "\n";
echo " Current F1-Score: " . sprintf('%.4f', $optimizationResult['current_metric_value']) . "\n";
echo " Optimal F1-Score: " . sprintf('%.4f', $optimizationResult['optimal_metric_value']) . "\n";
echo " Improvement: " . sprintf('%+.2f%%', $optimizationResult['improvement_percent']) . "\n";
echo "\nRecommendation: {$optimizationResult['recommendation']}\n\n";
// ============================================================================
// Example 5: Adaptive Threshold Adjustment
// ============================================================================
echo "5. Adaptive Threshold Adjustment\n";
echo str_repeat('-', 60) . "\n";
// Automatically adjust threshold based on FP/FN rates
$adaptiveResult = $autoTuning->adaptiveThresholdAdjustment(
'n1-detector',
Version::fromString('1.0.0')
);
echo "Adaptive Adjustment Results:\n";
echo " Current Threshold: " . sprintf('%.2f', $adaptiveResult['current_threshold']) . "\n";
echo " Recommended Threshold: " . sprintf('%.2f', $adaptiveResult['recommended_threshold']) . "\n";
echo " Adjustment Reason: {$adaptiveResult['adjustment_reason']}\n";
echo "\nExpected Improvement:\n";
echo " Accuracy: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['accuracy']) . "\n";
echo " Precision: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['precision']) . "\n";
echo " Recall: " . sprintf('%+.4f', $adaptiveResult['expected_improvement']['recall']) . "\n";
echo "\n";
// ============================================================================
// Example 6: Model Configuration Update
// ============================================================================
echo "6. Model Configuration Update\n";
echo str_repeat('-', 60) . "\n";
// Update model configuration based on optimization results
if ($optimizationResult['improvement_percent'] > 5.0) {
echo "Applying optimized threshold...\n";
$newConfiguration = $metadata->configuration;
$newConfiguration['confidence_threshold'] = $optimizationResult['optimal_threshold'];
$adapter->updateConfiguration($newConfiguration);
echo "✓ Configuration Updated\n";
echo " New Threshold: " . sprintf('%.2f', $optimizationResult['optimal_threshold']) . "\n";
echo " Expected F1-Score Improvement: " . sprintf('%+.2f%%', $optimizationResult['improvement_percent']) . "\n";
} else {
echo "Current configuration is optimal. No update needed.\n";
}
echo "\n";
// ============================================================================
// Example 7: Production Deployment
// ============================================================================
echo "7. Production Deployment\n";
echo str_repeat('-', 60) . "\n";
// Deploy to production when performance is validated
if ($metrics['accuracy'] >= 0.90 && !$degradationInfo['has_degraded']) {
echo "Deploying N+1 Detector to production...\n";
$adapter->deployToProduction();
// Verify deployment
$deployedMetadata = $adapter->getModelMetadata();
echo "✓ Successfully deployed to production\n";
echo " Environment: {$deployedMetadata->environment}\n";
echo " Deployed At: {$deployedMetadata->deployedAt->format('Y-m-d H:i:s')}\n";
echo " Accuracy: " . sprintf('%.4f', $deployedMetadata->getAccuracy()) . "\n";
} else {
echo "⚠ Deployment criteria not met:\n";
if ($metrics['accuracy'] < 0.90) {
echo " - Accuracy too low: " . sprintf('%.4f', $metrics['accuracy']) . " (required: 0.90)\n";
}
if ($degradationInfo['has_degraded']) {
echo " - Performance degradation detected\n";
}
}
echo "\n";
// ============================================================================
// Example 8: Model Versioning
// ============================================================================
echo "8. Model Versioning\n";
echo str_repeat('-', 60) . "\n";
// List all versions of N+1 detector
$allVersions = $registry->getAll('n1-detector');
echo "N+1 Detector Versions:\n";
foreach ($allVersions as $versionMetadata) {
echo " - v{$versionMetadata->version->toString()}\n";
echo " Created: {$versionMetadata->createdAt->format('Y-m-d H:i:s')}\n";
if ($versionMetadata->deployedAt) {
echo " Deployed: {$versionMetadata->deployedAt->format('Y-m-d H:i:s')} ({$versionMetadata->environment})\n";
}
if ($versionMetadata->getAccuracy()) {
echo " Accuracy: " . sprintf('%.4f', $versionMetadata->getAccuracy()) . "\n";
}
}
echo "\n=== Integration Complete ===\n";

View File

@@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
/**
* N+1 Detection Machine Learning - Usage Example
*
* This example demonstrates how to use the N+1 Detection ML Engine
* to analyze query execution patterns and detect N+1 query problems.
*/
require __DIR__ . '/../vendor/autoload.php';
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngine;
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngineInitializer;
use App\Framework\Database\NPlusOneDetection\QueryExecutionContext;
use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Config\Environment;
use App\Framework\DateTime\SystemClock;
use App\Framework\Logging\Handlers\ConsoleHandler;
use App\Framework\Logging\Logger;
use App\Framework\Logging\LogLevel;
echo "=== N+1 Detection Machine Learning - Usage Example ===\n\n";
// Setup
$environment = new Environment();
$clock = new SystemClock();
$logger = new Logger([new ConsoleHandler(LogLevel::INFO)]);
// Initialize N+1 Detection ML Engine
$initializer = new NPlusOneDetectionEngineInitializer($environment, $clock, $logger);
$engine = $initializer();
echo "✓ N+1 Detection ML Engine initialized\n";
echo "Configuration: " . json_encode($engine->getConfiguration(), JSON_PRETTY_PRINT) . "\n\n";
// Example 1: Clean Query Pattern (No N+1)
echo "=== Example 1: Clean Query Pattern (No N+1) ===\n";
$cleanContext = QueryExecutionContext::fromQueries([
[
'query' => 'SELECT * FROM users WHERE id = 1',
'duration' => 5.0,
'complexity' => 0.3,
'joins' => 0,
],
[
'query' => 'SELECT * FROM posts WHERE user_id = 1',
'duration' => 8.0,
'complexity' => 0.4,
'joins' => 0,
],
], executedInLoop: false);
$result1 = $engine->analyzeQueryContext($cleanContext);
echo "Analysis Result:\n";
echo " - Success: " . ($result1['success'] ? 'Yes' : 'No') . "\n";
echo " - Features Extracted: " . count($result1['features']) . "\n";
echo " - Anomalies Detected: " . count($result1['anomalies']) . "\n";
echo " - Overall Confidence: " . round($result1['overall_confidence'], 2) . "%\n";
echo " - Analysis Time: " . round($result1['analysis_time_ms'], 2) . "ms\n";
echo " - Has N+1 Pattern: " . ($cleanContext->hasNPlusOnePattern() ? 'Yes' : 'No') . "\n\n";
// Example 2: Suspicious N+1 Pattern
echo "=== Example 2: Suspicious N+1 Pattern ===\n";
$queries = [];
// Simulate N+1: 1 initial query + 10 repeated queries in loop
$queries[] = [
'query' => 'SELECT * FROM users',
'duration' => 10.0,
'complexity' => 0.5,
'joins' => 0,
];
for ($i = 1; $i <= 10; $i++) {
$queries[] = [
'query' => "SELECT * FROM posts WHERE user_id = {$i}", // Will be normalized to same hash
'duration' => 5.0 + ($i * 0.1), // Slightly varying timing
'complexity' => 0.3,
'joins' => 0,
];
}
$suspiciousContext = QueryExecutionContext::fromQueries($queries, executedInLoop: true, loopDepth: 1);
$result2 = $engine->analyzeQueryContext($suspiciousContext);
echo "Analysis Result:\n";
echo " - Success: " . ($result2['success'] ? 'Yes' : 'No') . "\n";
echo " - Features Extracted: " . count($result2['features']) . "\n";
echo " - Anomalies Detected: " . count($result2['anomalies']) . "\n";
echo " - Overall Confidence: " . round($result2['overall_confidence'], 2) . "%\n";
echo " - Analysis Time: " . round($result2['analysis_time_ms'], 2) . "ms\n";
echo " - Has N+1 Pattern: " . ($suspiciousContext->hasNPlusOnePattern() ? '⚠️ Yes' : 'No') . "\n";
echo " - Repetition Rate: " . round($suspiciousContext->getRepetitionRate(), 2) . "%\n";
echo " - Unique Queries: " . count($suspiciousContext->uniqueQueryHashes) . " / " . $suspiciousContext->queryCount . "\n\n";
// Show detected anomalies
if (!empty($result2['anomalies'])) {
echo "Detected Anomalies:\n";
foreach ($result2['anomalies'] as $anomaly) {
echo " - Type: {$anomaly->type->value}\n";
echo " Confidence: " . round($anomaly->confidence->value, 2) . "%\n";
echo " Severity: {$anomaly->severity->value}\n";
echo " Description: {$anomaly->description}\n";
if (!empty($anomaly->context)) {
echo " Context: " . json_encode($anomaly->context) . "\n";
}
echo "\n";
}
}
// Show extracted features
echo "=== Extracted Features (Sample) ===\n";
if (!empty($result2['features'])) {
$sampleFeatures = array_slice($result2['features'], 0, 3);
foreach ($sampleFeatures as $feature) {
echo " - {$feature->name}: " . round($feature->value, 4) . " {$feature->unit}\n";
echo " Type: {$feature->type->value}\n";
if (!empty($feature->metadata)) {
echo " Metadata: " . json_encode($feature->metadata) . "\n";
}
echo "\n";
}
}
// Example 3: Disabled Engine
echo "=== Example 3: Disabled Engine ===\n";
$disabledEngine = new NPlusOneDetectionEngine(
enabled: false,
extractors: [],
detectors: [],
clock: $clock,
analysisTimeout: Duration::fromSeconds(5),
confidenceThreshold: \App\Framework\Core\ValueObjects\Percentage::from(60.0)
);
$result3 = $disabledEngine->analyzeQueryContext($suspiciousContext);
echo "Analysis Result:\n";
echo " - Success: " . ($result3['success'] ? 'Yes' : 'No') . "\n";
echo " - Error: " . ($result3['error'] ?? 'None') . "\n\n";
echo "=== Integration Example ===\n";
echo "To integrate N+1 Detection ML into your application:\n\n";
echo "1. Inject NPlusOneDetectionEngine into your services:\n";
echo " public function __construct(\n";
echo " private readonly NPlusOneDetectionEngine \$mlEngine\n";
echo " ) {}\n\n";
echo "2. Collect query execution data during request processing\n\n";
echo "3. Create QueryExecutionContext from collected queries\n\n";
echo "4. Analyze with ML Engine:\n";
echo " \$result = \$this->mlEngine->analyzeQueryContext(\$context);\n\n";
echo "5. Take action based on anomalies detected:\n";
echo " if (\$result['overall_confidence'] > 80.0) {\n";
echo " \$this->logger->warning('Potential N+1 detected', [\n";
echo " 'anomalies' => count(\$result['anomalies']),\n";
echo " 'confidence' => \$result['overall_confidence'],\n";
echo " ]);\n";
echo " }\n\n";
echo "✓ N+1 Detection ML Usage Example Complete\n";

View File

@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
/**
* N+1 Detection ML Integration Example
*
* Demonstrates complete integration of N+1 Detection ML engine with
* the existing NPlusOneDetectionService for enhanced query analysis.
*/
require __DIR__ . '/../vendor/autoload.php';
use App\Framework\Database\QueryOptimization\NPlusOneDetectionService;
use App\Framework\Database\QueryOptimization\NPlusOneDetectionServiceInitializer;
use App\Framework\Database\QueryOptimization\QueryLogger;
use App\Framework\Database\QueryOptimization\Analysis\NPlusOneDetector;
use App\Framework\Database\QueryOptimization\Analysis\EagerLoadingAnalyzer;
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngine;
use App\Framework\Database\NPlusOneDetection\MachineLearning\NPlusOneDetectionEngineInitializer;
use App\Framework\Config\Environment;
use App\Framework\DateTime\SystemClock;
use App\Framework\Logging\Handlers\ConsoleHandler;
use App\Framework\Logging\Logger;
use App\Framework\Logging\LogLevel;
use App\Framework\DI\DefaultContainer;
echo "=== N+1 Detection ML Integration Example ===\n\n";
// 1. Setup Components
$environment = new Environment();
$clock = new SystemClock();
$logger = new Logger([new ConsoleHandler(LogLevel::INFO)]);
$container = new DefaultContainer();
// Register logger in container
$container->singleton(Logger::class, $logger);
// 2. Initialize ML Engine
echo "Step 1: Initializing ML Engine...\n";
$mlEngineInitializer = new NPlusOneDetectionEngineInitializer($environment, $clock, $logger);
$mlEngine = $mlEngineInitializer();
$container->singleton(NPlusOneDetectionEngine::class, $mlEngine);
echo "✓ ML Engine initialized\n";
echo " Configuration: " . json_encode($mlEngine->getConfiguration(), JSON_PRETTY_PRINT) . "\n\n";
// 3. Create QueryLogger and simulate query execution
echo "Step 2: Simulating Query Execution...\n";
$queryLogger = new QueryLogger();
$queryLogger->enable();
// Simulate N+1 scenario: 1 query + 10 repeated queries
echo "Logging initial query: SELECT * FROM users\n";
$queryLogger->logQuery(
'SELECT * FROM users',
[],
10.5,
10
);
echo "Logging N+1 pattern: 10 repeated queries in loop\n";
for ($i = 1; $i <= 10; $i++) {
$queryLogger->logQuery(
"SELECT * FROM posts WHERE user_id = $i",
[$i],
5.0 + ($i * 0.2),
rand(5, 15)
);
}
$queryLogger->disable();
echo "✓ Query logging completed\n";
echo " Total queries logged: " . $queryLogger->getQueryCount() . "\n";
echo " Total execution time: " . round($queryLogger->getTotalExecutionTime(), 2) . "ms\n\n";
// 4. Create NPlusOneDetectionService with ML Integration
echo "Step 3: Creating N+1 Detection Service with ML...\n";
$detector = new NPlusOneDetector(
minExecutionCount: 5,
minSeverityScore: 4.0
);
$eagerLoadingAnalyzer = new EagerLoadingAnalyzer();
$detectionService = new NPlusOneDetectionService(
queryLogger: $queryLogger,
detector: $detector,
eagerLoadingAnalyzer: $eagerLoadingAnalyzer,
logger: $logger,
mlEngine: $mlEngine
);
echo "✓ Detection service initialized\n";
echo " ML engine enabled: " . ($mlEngine->isEnabled() ? 'Yes' : 'No') . "\n\n";
// 5. Perform Analysis
echo "Step 4: Analyzing Queries...\n";
echo "=====================================\n\n";
$analysisResult = $detectionService->analyze();
// 6. Display Traditional Pattern-Based Results
echo "=== Traditional Pattern Detection ===\n";
$stats = $analysisResult['statistics'];
echo "Query Statistics:\n";
echo " Total queries: " . $stats['total_queries'] . "\n";
echo " Total patterns: " . $stats['total_patterns'] . "\n";
echo " N+1 patterns detected: " . $stats['n_plus_one_patterns'] . "\n";
echo " N+1 queries: " . $stats['n_plus_one_queries'] . " (" . round($stats['n_plus_one_percentage'], 1) . "% of total)\n";
echo " Time wasted: " . round($stats['n_plus_one_time_ms'], 2) . "ms (" . round($stats['time_wasted_percentage'], 1) . "% of total)\n\n";
if (!empty($analysisResult['detections'])) {
echo "Detected N+1 Issues:\n";
foreach ($analysisResult['detections'] as $index => $detection) {
echo " [" . ($index + 1) . "] {$detection->getSeverityLevel()} - {$detection->pattern->getTableName()}\n";
echo " Executions: {$detection->pattern->getExecutionCount()}\n";
echo " Total time: " . round($detection->pattern->getTotalExecutionTimeMs(), 2) . "ms\n";
echo " Impact: {$detection->getPerformanceImpact()}\n";
}
echo "\n";
}
// 7. Display ML Analysis Results
if (isset($analysisResult['ml_analysis'])) {
echo "=== Machine Learning Analysis ===\n";
$mlAnalysis = $analysisResult['ml_analysis'];
echo "ML Analysis Status: " . ($mlAnalysis['success'] ? '✓ Success' : '✗ Failed') . "\n";
if ($mlAnalysis['success']) {
echo "Anomalies Detected: " . $mlAnalysis['anomalies_count'] . "\n";
echo "Overall Confidence: " . round($mlAnalysis['overall_confidence'], 2) . "%\n";
echo "Analysis Time: " . round($mlAnalysis['analysis_time_ms'], 2) . "ms\n\n";
if (!empty($mlAnalysis['anomalies'])) {
echo "ML-Detected Anomalies:\n";
foreach ($mlAnalysis['anomalies'] as $index => $anomaly) {
echo " [" . ($index + 1) . "] {$anomaly->type->value}\n";
echo " Confidence: " . round($anomaly->confidence->value, 2) . "%\n";
echo " Severity: {$anomaly->severity->value}\n";
echo " Description: {$anomaly->description}\n";
if (!empty($anomaly->context)) {
echo " Context: " . json_encode($anomaly->context) . "\n";
}
echo "\n";
}
}
echo "Extracted Features (Sample):\n";
$sampleFeatures = array_slice($mlAnalysis['features'], 0, 5);
foreach ($sampleFeatures as $feature) {
echo " - {$feature->name}: " . round($feature->value, 4) . " {$feature->unit}\n";
}
echo "\n";
} else {
echo "Error: " . ($mlAnalysis['error'] ?? 'Unknown error') . "\n\n";
}
} else {
echo "=== Machine Learning Analysis ===\n";
echo "ML engine not enabled or not available\n\n";
}
// 8. Generate Eager Loading Strategies
if (!empty($analysisResult['strategies'])) {
echo "=== Optimization Strategies ===\n";
foreach ($analysisResult['strategies'] as $strategy) {
echo "Strategy for {$strategy->entityClass}:\n";
echo " Relations to eager load: " . implode(', ', $strategy->relationsToLoad) . "\n";
echo " Expected improvement: " . $strategy->expectedImprovement . "%\n";
echo " Implementation: {$strategy->implementationHint}\n\n";
}
}
// 9. Summary
echo "=== Integration Summary ===\n";
echo "✓ Traditional pattern detection completed\n";
echo "✓ ML-based anomaly detection completed\n";
echo "✓ Combined analysis provides:\n";
echo " - Pattern-based detection (existing framework)\n";
echo " - ML-based anomaly detection (new capability)\n";
echo " - Eager loading optimization strategies\n";
echo " - Comprehensive performance insights\n\n";
echo "Integration Benefits:\n";
echo "1. Enhanced detection accuracy through ML\n";
echo "2. Reduced false positives via confidence scoring\n";
echo "3. Automatic feature extraction from query patterns\n";
echo "4. Real-time anomaly detection with low overhead\n";
echo "5. Seamless integration with existing detection pipeline\n\n";
echo "✓ N+1 Detection ML Integration Example Complete\n";

View File

@@ -0,0 +1,389 @@
<?php
declare(strict_types=1);
/**
* Performance Profiling Usage Examples
*
* Dieses Script demonstriert die Verwendung des NestedPerformanceTracker
* für Flamegraph-Visualisierung und Timeline-Analyse.
*
* Ausführung: php examples/performance-profiling-usage.php
*/
require_once __DIR__ . '/../vendor/autoload.php';
use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
// Tracker initialisieren
$tracker = new NestedPerformanceTracker(
new SystemClock(),
new SystemHighResolutionClock(),
new MemoryMonitor()
);
echo "=== Performance Profiling Examples ===\n\n";
// Example 1: Einfache verschachtelte Operationen
echo "Example 1: Nested Operations\n";
echo str_repeat('-', 50) . "\n";
$tracker->measure(
'http.request',
PerformanceCategory::CONTROLLER,
function () use ($tracker) {
usleep(5000); // 5ms Controller-Logik
// Database Query
$tracker->measure(
'database.query',
PerformanceCategory::DATABASE,
function () {
usleep(10000); // 10ms Query
return ['users' => 100];
}
);
// Cache Operation
$tracker->measure(
'cache.get',
PerformanceCategory::CACHE,
function () {
usleep(2000); // 2ms Cache
return ['cached' => true];
}
);
// Template Rendering
$tracker->measure(
'template.render',
PerformanceCategory::VIEW,
function () use ($tracker) {
usleep(3000); // 3ms Template
// Nested: Asset Loading
$tracker->measure(
'assets.load',
PerformanceCategory::FILESYSTEM,
function () {
usleep(1000); // 1ms Assets
}
);
}
);
return ['status' => 'success'];
}
);
// Flamegraph generieren
echo "\nFlamegraph Data:\n";
$flamegraph = $tracker->generateFlamegraph();
foreach ($flamegraph as $entry) {
echo sprintf(
" %s → %.2f samples\n",
$entry['stack_trace'],
$entry['samples']
);
}
// Timeline generieren
echo "\nTimeline Events:\n";
$timeline = $tracker->generateTimeline();
foreach ($timeline as $event) {
$indent = str_repeat(' ', $event['depth']);
echo sprintf(
" %s[%s] %s (%.2fms self, %.2fms total, %.2fMB memory)\n",
$indent,
$event['category'],
$event['name'],
$event['self_time_ms'],
$event['duration_ms'],
$event['memory_delta_mb']
);
}
// Summary
echo "\nPerformance Summary:\n";
$summary = $tracker->getSummary();
foreach ($summary as $key => $value) {
echo sprintf(" %s: %s\n", $key, is_float($value) ? number_format($value, 2) : $value);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 2: Flamegraph Export für Visualisierung
echo "Example 2: Flamegraph Export (Brendan Gregg Format)\n";
echo str_repeat('-', 50) . "\n";
$tracker->reset(); // Reset für neues Beispiel
// Komplexere Operation
$tracker->measure(
'api.request',
PerformanceCategory::API,
function () use ($tracker) {
usleep(2000);
// Service Layer
$tracker->measure(
'service.process',
PerformanceCategory::CUSTOM,
function () use ($tracker) {
usleep(5000);
// Repository
$tracker->measure(
'repository.find',
PerformanceCategory::DATABASE,
function () {
usleep(8000);
}
);
// Cache
$tracker->measure(
'cache.set',
PerformanceCategory::CACHE,
function () {
usleep(3000);
}
);
}
);
// Response Transformation
$tracker->measure(
'transformer.transform',
PerformanceCategory::CUSTOM,
function () {
usleep(4000);
}
);
}
);
$flamegraphData = $tracker->generateFlamegraph();
echo "\nFlamegraph Format für flamegraph.pl:\n";
echo "----------------------------------------\n";
foreach ($flamegraphData as $entry) {
echo sprintf(
"%s %d\n",
$entry['stack_trace'],
(int) ceil($entry['samples'])
);
}
// In Datei schreiben für flamegraph.pl Tool
$flamegraphFile = __DIR__ . '/../tests/tmp/flamegraph.txt';
@mkdir(dirname($flamegraphFile), 0755, true);
$output = [];
foreach ($flamegraphData as $entry) {
$output[] = sprintf(
"%s %d",
$entry['stack_trace'],
(int) ceil($entry['samples'])
);
}
file_put_contents($flamegraphFile, implode("\n", $output));
echo "\nFlamegraph data saved to: {$flamegraphFile}\n";
echo "Generate SVG: flamegraph.pl {$flamegraphFile} > flamegraph.svg\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 3: Chrome DevTools Timeline Export
echo "Example 3: Chrome DevTools Timeline Export\n";
echo str_repeat('-', 50) . "\n";
$timeline = $tracker->generateTimeline();
// In Chrome Trace Event Format konvertieren
$traceEvents = [];
foreach ($timeline as $event) {
// Begin Event
$traceEvents[] = [
'name' => $event['name'],
'cat' => $event['category'],
'ph' => 'B', // Begin
'ts' => (int)($event['start_time'] * 1_000_000), // Microseconds
'pid' => 1,
'tid' => 1,
'args' => $event['context']
];
// End Event
$traceEvents[] = [
'name' => $event['name'],
'cat' => $event['category'],
'ph' => 'E', // End
'ts' => (int)($event['end_time'] * 1_000_000),
'pid' => 1,
'tid' => 1
];
}
$chromeTrace = [
'traceEvents' => $traceEvents,
'displayTimeUnit' => 'ms',
'otherData' => [
'version' => '1.0',
'framework' => 'Custom PHP Framework'
]
];
$chromeTraceFile = __DIR__ . '/../tests/tmp/chrome-trace.json';
file_put_contents($chromeTraceFile, json_encode($chromeTrace, JSON_PRETTY_PRINT));
echo "\nChrome Trace saved to: {$chromeTraceFile}\n";
echo "Open in Chrome: chrome://tracing → Load → {$chromeTraceFile}\n";
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 4: Performance Budget Validation
echo "Example 4: Performance Budget Validation\n";
echo str_repeat('-', 50) . "\n";
$budgets = [
'database.query' => 5, // max 5ms
'cache.get' => 1, // max 1ms
'api.request' => 20, // max 20ms
];
$violations = [];
foreach ($timeline as $event) {
// Check ob Operation ein Budget hat
foreach ($budgets as $operation => $budget) {
if (str_contains($event['name'], $operation)) {
if ($event['duration_ms'] > $budget) {
$violations[] = [
'operation' => $event['name'],
'duration' => $event['duration_ms'],
'budget' => $budget,
'exceeded_by' => $event['duration_ms'] - $budget,
'exceeded_percentage' => (($event['duration_ms'] - $budget) / $budget) * 100
];
}
}
}
}
if (!empty($violations)) {
echo "\n⚠️ Performance Budget Violations:\n";
foreach ($violations as $violation) {
echo sprintf(
" • %s: %.2fms (budget: %.2fms, exceeded by %.2fms / %.1f%%)\n",
$violation['operation'],
$violation['duration'],
$violation['budget'],
$violation['exceeded_by'],
$violation['exceeded_percentage']
);
}
} else {
echo "\n✅ All operations within performance budget!\n";
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 5: Bottleneck Detection
echo "Example 5: Automatic Bottleneck Detection\n";
echo str_repeat('-', 50) . "\n";
// Sortiere nach self_time_ms (Zeit ohne Children)
$timelineCopy = $timeline;
usort($timelineCopy, fn($a, $b) => $b['self_time_ms'] <=> $a['self_time_ms']);
// Top 3 Bottlenecks
$bottlenecks = array_slice($timelineCopy, 0, 3);
echo "\nTop 3 Performance Bottlenecks (by self-time):\n";
foreach ($bottlenecks as $index => $bottleneck) {
$percentage = ($bottleneck['self_time_ms'] / $bottleneck['duration_ms']) * 100;
echo sprintf(
" %d. %s [%s]\n" .
" Self Time: %.2fms (%.1f%% of total %.2fms)\n" .
" Memory: %.2fMB\n" .
" Depth: %d\n",
$index + 1,
$bottleneck['name'],
$bottleneck['category'],
$bottleneck['self_time_ms'],
$percentage,
$bottleneck['duration_ms'],
$bottleneck['memory_delta_mb'],
$bottleneck['depth']
);
}
echo "\n" . str_repeat('=', 50) . "\n\n";
// Example 6: Memory Usage Analysis
echo "Example 6: Memory Usage Analysis\n";
echo str_repeat('-', 50) . "\n";
$totalMemory = 0;
$memoryByCategory = [];
foreach ($timeline as $event) {
$totalMemory += $event['memory_delta_mb'];
$category = $event['category'];
if (!isset($memoryByCategory[$category])) {
$memoryByCategory[$category] = 0;
}
$memoryByCategory[$category] += $event['memory_delta_mb'];
}
echo sprintf("\nTotal Memory Delta: %.2fMB\n", $totalMemory);
echo "\nMemory Usage by Category:\n";
arsort($memoryByCategory);
foreach ($memoryByCategory as $category => $memory) {
$percentage = ($memory / max($totalMemory, 0.001)) * 100;
echo sprintf(
" • %s: %.2fMB (%.1f%%)\n",
$category,
$memory,
$percentage
);
}
// High memory operations
$highMemoryOps = array_filter($timeline, fn($e) => $e['memory_delta_mb'] > 0.5);
if (!empty($highMemoryOps)) {
echo "\n⚠️ High Memory Operations (>0.5MB):\n";
foreach ($highMemoryOps as $op) {
echo sprintf(
" • %s: %.2fMB\n",
$op['name'],
$op['memory_delta_mb']
);
}
}
echo "\n" . str_repeat('=', 50) . "\n\n";
echo "✅ Performance Profiling Examples completed!\n\n";
echo "Generated Files:\n";
echo "{$flamegraphFile}\n";
echo "{$chromeTraceFile}\n\n";
echo "Next Steps:\n";
echo " 1. Generate SVG: flamegraph.pl {$flamegraphFile} > flamegraph.svg\n";
echo " 2. View in Chrome: chrome://tracing → Load {$chromeTraceFile}\n";
echo " 3. Integrate into API endpoints for production monitoring\n\n";