PHP code example of highperapp / zero-downtime

1. Go to this page and download the library: Download highperapp/zero-downtime library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

highperapp / zero-downtime example snippets


use HighPerApp\HighPer\ZeroDowntime\ZeroDowntimeBootstrap;
use HighPerApp\HighPer\Framework\Contracts\ApplicationInterface;
use Psr\Log\LoggerInterface;

// Initialize in your application bootstrap
$zeroDowntime = new ZeroDowntimeBootstrap($app, $logger, [
    'reload_strategy' => 'blue-green',
    'enable_connection_migration' => true,
    'enable_request_buffering' => true,
    'worker_count' => 4,
    'graceful_shutdown_timeout' => 30
]);

// Trigger zero-downtime reload
posix_kill(posix_getpid(), SIGHUP);

// Get reload result
$result = $zeroDowntime->performZeroDowntimeReload();
echo "Migrated {$result['migrated_connections']} connections";
echo "Replayed {$result['replayed_requests']} requests";

// In your application configuration
'providers' => [
    HighPerApp\HighPer\ZeroDowntime\ZeroDowntimeServiceProvider::class,
]

use HighPerApp\HighPer\ZeroDowntime\ConnectionMigration\ConnectionStateSerializer;
use HighPerApp\HighPer\ZeroDowntime\RequestQueue\ProxyRequestQueue;
use HighPerApp\HighPer\WebSocket\WebSocketConnection;
use HighPerApp\HighPer\Websockets\Http2WebSocketConnection;

// Connection serialization with active state management
$serializer = new ConnectionStateSerializer($logger, [
    'compression_enabled' => true,
    'state_storage_path' => '/tmp/highper-connection-states'
]);

// Register connections
$serializer->registerConnection('conn1', $webSocketConnection, 'http1_websocket');
$serializer->registerConnection('conn2', $http2WebSocketConnection, 'http2_websocket');

// Manage connection states for zero-downtime optimization
$serializer->markConnectionActive('conn1');  // O(1) performance
$serializer->markConnectionIdle('conn2');

// Serialize only active connections for priority migration
$activeStates = $serializer->serializeActiveConnections();
echo "Active connections: " . $serializer->getActiveConnectionCount();

// Serialize all connections
$allStates = $serializer->serializeAllConnections();

// Migrate connections to new workers
$workers = [['pid' => 1234], ['pid' => 1235]];
$migrationResult = $serializer->migrateConnectionsToWorkers($workers, $activeStates);

// Request buffering with worker-specific handling
$queue = new ProxyRequestQueue($logger, [
    'max_buffer_size_mb' => 10,
    'max_buffer_time_seconds' => 30,
    'overflow_strategy' => 'reject',
    'priority_headers' => ['x-priority', 'x-urgent']
]);

// Global request buffering
$queue->startBuffering();
$queue->bufferRequest([
    'method' => 'POST',
    'uri' => '/api/data',
    'headers' => ['x-priority' => '1'],
    'body' => json_encode(['data' => 'important'])
]);

// Worker-specific buffering
$workerPid = 1234;
$queue->startWorkerBuffering($workerPid);
$queue->bufferRequest($request, $workerPid);

// Replay buffered requests
$replayResult = $queue->replayBufferedRequests($workers);
echo "Replayed {$replayResult['replayed_requests']} requests in {$replayResult['replay_time_ms']}ms";

// Get queue statistics
$stats = $queue->getStats();
echo "Buffer utilization: {$stats['global_buffer']['size_bytes']} bytes";

use EaseAppPHP\HighPer\Websockets\Http2WebSocketHandler;

$handler = new Http2WebSocketHandler($logger, [
    'enable_compression' => true,
    'max_frame_size' => 65536
]);

// Handles CONNECT method with :protocol pseudo-header

// Automatic protocol detection and serialization
$connectionStates = $serializer->serializeAllConnections();

// Each state TP/3 QUIC state)
// - Frame buffers and compression context

$stats = $zeroDowntime->getStats();
/*
{
    "reload_in_progress": false,
    "strategy": "blue-green", 
    "active_connections": 150,
    "buffered_requests": 0,
    "worker_stats": {...},
    "socket_stats": {...}
}
*/

// Register custom connection types
$serializer->registerConnection('custom_conn', $connection, 'custom_protocol');

// Implement custom serialization
class CustomConnectionSerializer extends ConnectionStateSerializer 
{
    protected function serializeCustomProtocolState($connection): array
    {
        // Custom serialization logic
        return [
            'custom_state' => $connection->getCustomState(),
            'protocol_version' => $connection->getProtocolVersion()
        ];
    }
}

// Enable encryption for sensitive connection data
$serializer = new ConnectionStateSerializer($logger, [
    'encryption_enabled' => true,
    'encryption_key' => getenv('CONNECTION_STATE_KEY'),
    'compression_enabled' => true
]);

// Configure secure buffer limits
$queue = new ProxyRequestQueue($logger, [
    'max_buffer_size_mb' => 10,        // Prevent memory exhaustion
    'max_requests_per_buffer' => 1000, // Limit buffer size
    'max_buffer_time_seconds' => 30,   // Prevent indefinite buffering
    'buffer_to_disk' => false          // Avoid disk-based attacks
]);

// Get performance metrics
$bootstrap = new ZeroDowntimeBootstrap($app, $logger);
$stats = $bootstrap->getStats();

echo "Active connections: {$stats['active_connections']}";
echo "Memory usage: {$stats['memory_usage_mb']}MB";
echo "Uptime: {$stats['uptime_seconds']} seconds";

// Health status monitoring
$health = $bootstrap->getHealthStatus();
echo "Status: {$health['status']}";  // healthy|reloading|degraded
echo "Component status: " . json_encode($health['components']);

class ZeroDowntimeBootstrap
{
    // Deployment operations
    public function performZeroDowntimeReload(): array;              // Trigger hot reload
    public function performGracefulShutdown(): array;                // Graceful shutdown
    public function testConnectionMigration(): void;                 // Test migration
    
    // Status and monitoring
    public function getStats(): array;                               // System statistics
    public function getHealthStatus(): array;                        // Health check
    public function isReloadInProgress(): bool;                      // Check reload status
}

class ConnectionStateSerializer
{
    // Connection management
    public function registerConnection(string $id, object $connection, string $protocol): void;
    public function unregisterConnection(string $connectionId): void;
    public function hasConnection(string $connectionId): bool;
    
    // Active state management (O(1) performance)
    public function markConnectionActive(string $connectionId): void;
    public function markConnectionIdle(string $connectionId): void;
    public function markConnectionClosing(string $connectionId): void;
    public function isConnectionActive(string $connectionId): bool;
    
    // Serialization operations
    public function serializeAllConnections(): array;                // All connections
    public function serializeActiveConnections(): array;             // Active only (priority)
    public function serializeWorkerConnections(int $workerPid): array;
    
    // Migration operations
    public function migrateConnectionsToWorkers(array $workers, array $states): array;
    public function migrateWorkerConnections(array $newWorker, array $connectionStates): void;
    
    // Statistics and validation
    public function getActiveConnectionCount(): int;                 // O(1) performance
    public function getTotalConnectionCount(): int;
    public function getConnectionStats(): array;
    public function validateStates(array $states): array;
    
    // Compression utilities
    public function compressStates(array $states): string;
    public function decompressStates(string $compressedData): array;
}

class ProxyRequestQueue
{
    // Buffer management
    public function startBuffering(): void;                          // Global buffering
    public function stopBuffering(): void;
    public function startWorkerBuffering(int $workerPid): void;      // Worker-specific
    public function stopWorkerBuffering(int $workerPid): void;
    
    // Request operations
    public function bufferRequest($request, ?int $targetWorkerPid = null): bool;
    public function replayBufferedRequests(array $newWorkers): array;
    public function replayWorkerRequests(array $newWorker, int $oldWorkerPid): void;
    
    // Queue management
    public function flush(): void;                                   // Emergency flush
    public function flushBuffer(): array;                            // Get and clear
    public function getBufferedRequests(): array;                    // Priority sorted
    public function getRequestsForWorker(string $workerId): array;
    public function getExpiredRequests(): array;
    
    // Status and statistics
    public function getBufferedRequestCount(): int;
    public function isBufferingEnabled(): bool;
    public function getBufferStats(): array;
    public function getPerformanceMetrics(): array;
    public function getStats(): array;
}

[
    'reload_successful' => true,
    'migrated_connections' => 150,
    'replayed_requests' => 45,
    'strategy' => 'blue-green',
    'duration_ms' => 2340.50
]

[
    'status' => 'healthy',  // healthy|reloading|degraded
    'components' => [
        'connection_migration' => [
            'status' => 'healthy',
            'active_connections' => 150
        ],
        'request_buffering' => [
            'status' => 'idle',
            'buffered_requests' => 0
        ]
    ],
    'uptime_seconds' => 3600.45,
    'memory_usage_mb' => 45.2
]