-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
761 lines (641 loc) · 25.3 KB
/
server.php
File metadata and controls
761 lines (641 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
<?php
/**
* Deepgram Flux Starter - PHP (Ratchet)
*
* WebSocket proxy server for Deepgram's Flux API using Ratchet + ReactPHP.
* Forwards all messages (JSON and binary) bidirectionally between client and Deepgram.
*
* Key Features:
* - WebSocket proxy: /api/flux -> wss://api.deepgram.com/v2/listen
* - JWT session auth via access_token.<jwt> subprotocol
* - HTTP endpoints: GET /api/session, GET /api/metadata
* - CORS enabled for frontend communication
* - Graceful shutdown on SIGINT/SIGTERM
*
* Usage: php server.php
*/
require_once __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Yosymfony\Toml\Toml;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Http\HttpServerInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\WebSocket\WsServerInterface;
use React\EventLoop\Loop;
use React\Socket\SocketServer;
use Ratchet\Http\Router;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
// ============================================================================
// ENVIRONMENT LOADING
// ============================================================================
Dotenv::createImmutable(__DIR__)->safeLoad();
// ============================================================================
// CONFIGURATION
// ============================================================================
/**
* Server and Deepgram configuration.
* Port and host can be overridden via environment variables.
*/
$CONFIG = [
'port' => $_ENV['PORT'] ?? '8081',
'host' => $_ENV['HOST'] ?? '0.0.0.0',
'deepgramSttUrl' => 'wss://api.deepgram.com/v2/listen',
];
// ============================================================================
// API KEY LOADING
// ============================================================================
/**
* Load the Deepgram API key from environment variables.
* Exits with a helpful error message if not found.
*
* @return string The Deepgram API key
*/
function loadApiKey(): string
{
$apiKey = $_ENV['DEEPGRAM_API_KEY'] ?? '';
if (empty($apiKey)) {
fwrite(STDERR, "\nERROR: Deepgram API key not found!\n\n");
fwrite(STDERR, "Please set your API key using one of these methods:\n\n");
fwrite(STDERR, "1. Create a .env file (recommended):\n");
fwrite(STDERR, " DEEPGRAM_API_KEY=your_api_key_here\n\n");
fwrite(STDERR, "2. Environment variable:\n");
fwrite(STDERR, " export DEEPGRAM_API_KEY=your_api_key_here\n\n");
fwrite(STDERR, "Get your API key at: https://console.deepgram.com\n\n");
exit(1);
}
return $apiKey;
}
$API_KEY = loadApiKey();
// ============================================================================
// SESSION AUTH - JWT tokens for production security
// ============================================================================
/**
* Session secret for signing JWTs.
* Generated at startup if SESSION_SECRET env var is not set.
*/
$SESSION_SECRET = $_ENV['SESSION_SECRET'] ?? bin2hex(random_bytes(32));
/** JWT expiry time in seconds (1 hour) */
define('JWT_EXPIRY', 3600);
/**
* Create a signed JWT session token.
*
* @param string $secret The secret key for signing
* @return string The encoded JWT token
*/
function createSessionToken(string $secret): string
{
$now = time();
$payload = [
'iat' => $now,
'exp' => $now + JWT_EXPIRY,
];
return JWT::encode($payload, $secret, 'HS256');
}
/**
* Validate JWT from WebSocket subprotocol: access_token.<jwt>
* Returns the full subprotocol string if valid, null if invalid.
*
* @param string|null $protocolHeader The Sec-WebSocket-Protocol header value
* @param string $secret The JWT signing secret
* @return string|null The valid subprotocol string or null
*/
function validateWsToken(?string $protocolHeader, string $secret): ?string
{
if ($protocolHeader === null || $protocolHeader === '') {
return null;
}
$protocols = array_map('trim', explode(',', $protocolHeader));
foreach ($protocols as $proto) {
if (str_starts_with($proto, 'access_token.')) {
$token = substr($proto, strlen('access_token.'));
try {
JWT::decode($token, new Key($secret, 'HS256'));
return $proto;
} catch (\Exception $e) {
return null;
}
}
}
return null;
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/**
* Reserved WebSocket close codes that cannot be set by applications.
*/
const RESERVED_CLOSE_CODES = [1004, 1005, 1006, 1015];
/**
* Returns a safe close code, defaulting to 1000 if the given code is reserved.
*
* @param int $code The close code to check
* @return int A safe close code
*/
function getSafeCloseCode(int $code): int
{
if ($code >= 1000 && $code <= 4999 && !in_array($code, RESERVED_CLOSE_CODES)) {
return $code;
}
return 1000;
}
/**
* Build the Deepgram WebSocket URL from client query parameters.
*
* @param string $queryString The client's query string
* @param string $baseUrl The base Deepgram STT URL
* @return string The fully-qualified Deepgram URL
*/
function buildDeepgramUrl(string $queryString, string $baseUrl): string
{
parse_str($queryString, $params);
$model = $params['model'] ?? 'flux-general-en';
$encoding = $params['encoding'] ?? 'linear16';
$sampleRate = $params['sample_rate'] ?? '16000';
$dgParams = [
'model' => $model,
'encoding' => $encoding,
'sample_rate' => $sampleRate,
];
// Optional parameters
if (!empty($params['eot_threshold'])) {
$dgParams['eot_threshold'] = $params['eot_threshold'];
}
if (!empty($params['eager_eot_threshold'])) {
$dgParams['eager_eot_threshold'] = $params['eager_eot_threshold'];
}
if (!empty($params['eot_timeout_ms'])) {
$dgParams['eot_timeout_ms'] = $params['eot_timeout_ms'];
}
$url = $baseUrl . '?' . http_build_query($dgParams);
// Handle keyterm parameters (can appear multiple times)
// http_build_query cannot handle repeated keys, so we append them manually
if (isset($params['keyterm'])) {
$keyterms = is_array($params['keyterm']) ? $params['keyterm'] : [$params['keyterm']];
foreach ($keyterms as $term) {
$url .= '&keyterm=' . rawurlencode($term);
}
}
return $url;
}
/**
* Send a JSON HTTP response via Ratchet ConnectionInterface.
*
* @param ConnectionInterface $conn The HTTP connection
* @param int $status HTTP status code
* @param mixed $data Data to encode as JSON
* @param array $extraHeaders Additional headers
*/
function sendHttpResponse(ConnectionInterface $conn, int $status, mixed $data, array $extraHeaders = []): void
{
$body = json_encode($data, JSON_UNESCAPED_SLASHES);
$headers = array_merge([
'Content-Type' => 'application/json',
'Content-Length' => strlen($body),
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization',
], $extraHeaders);
$statusTexts = [
200 => 'OK',
204 => 'No Content',
404 => 'Not Found',
500 => 'Internal Server Error',
];
$statusText = $statusTexts[$status] ?? 'Unknown';
$response = "HTTP/1.1 {$status} {$statusText}\r\n";
foreach ($headers as $key => $value) {
$response .= "{$key}: {$value}\r\n";
}
$response .= "\r\n";
$response .= $body;
$conn->send($response);
$conn->close();
}
// ============================================================================
// WEBSOCKET PROXY HANDLER - /api/flux
// ============================================================================
/**
* Flux WebSocket proxy handler.
* Authenticates clients via JWT subprotocol, connects to Deepgram Flux API,
* and forwards all messages bidirectionally.
*/
class FluxHandler implements \Ratchet\WebSocket\MessageComponentInterface, WsServerInterface
{
/** @var \SplObjectStorage Active client connections */
private \SplObjectStorage $clients;
/** @var array<int,\Ratchet\Client\WebSocket> Map of client resource ID to Deepgram WS */
private array $deepgramConnections = [];
/** @var string Deepgram API key */
private string $apiKey;
/** @var string JWT signing secret */
private string $sessionSecret;
/** @var string Base Deepgram STT URL */
private string $deepgramSttUrl;
/** @var array<int,int> Client message counts for logging */
private array $clientMsgCounts = [];
/** @var array<int,int> Deepgram message counts for logging */
private array $dgMsgCounts = [];
public function __construct(string $apiKey, string $sessionSecret, string $deepgramSttUrl)
{
$this->clients = new \SplObjectStorage();
$this->apiKey = $apiKey;
$this->sessionSecret = $sessionSecret;
$this->deepgramSttUrl = $deepgramSttUrl;
}
/**
* Return the list of subprotocols the server supports.
* Ratchet calls this to negotiate with the client.
*
* @param array $protocols Protocols requested by the client
* @return array Protocols the server agrees to
*/
public function getSubProtocols(): array
{
// Ratchet uses this for the initial handshake; we handle protocol
// negotiation dynamically in onOpen via the request headers.
return [];
}
/**
* Handle new WebSocket connection.
* Validates JWT from subprotocol, then opens upstream Deepgram connection.
*
* @param ConnectionInterface $conn The client connection
*/
public function onOpen(ConnectionInterface $conn): void
{
$resourceId = $conn->resourceId;
// Extract query string from the request
$queryString = '';
if (isset($conn->httpRequest)) {
$uri = $conn->httpRequest->getUri();
$queryString = $uri->getQuery();
// Validate JWT from subprotocol header
$protocolHeader = $conn->httpRequest->getHeaderLine('Sec-WebSocket-Protocol');
$validProto = validateWsToken($protocolHeader, $this->sessionSecret);
if ($validProto === null) {
echo "WebSocket auth failed: invalid or missing token (client #{$resourceId})\n";
$conn->close();
return;
}
echo "Client #{$resourceId} connected to /api/flux (authenticated)\n";
}
$this->clients->attach($conn);
$this->clientMsgCounts[$resourceId] = 0;
$this->dgMsgCounts[$resourceId] = 0;
// Build Deepgram URL from client query params
$deepgramUrl = buildDeepgramUrl($queryString, $this->deepgramSttUrl);
echo "Connecting to Deepgram Flux: {$deepgramUrl}\n";
// Connect to Deepgram via Pawl (ReactPHP WebSocket client)
$connector = new \Ratchet\Client\Connector(Loop::get());
$connector($deepgramUrl, [], [
'Authorization' => 'Token ' . $this->apiKey,
])->then(
function (\Ratchet\Client\WebSocket $dgWs) use ($conn, $resourceId) {
echo "Connected to Deepgram Flux API (client #{$resourceId})\n";
$this->deepgramConnections[$resourceId] = $dgWs;
// Forward Deepgram messages to client
$dgWs->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn, $resourceId) {
$this->dgMsgCounts[$resourceId] = ($this->dgMsgCounts[$resourceId] ?? 0) + 1;
$count = $this->dgMsgCounts[$resourceId];
$payload = $msg->getPayload();
$isBinary = $msg->isBinary();
if ($count % 10 === 0 || !$isBinary) {
echo " Deepgram message #{$count} (binary: " . ($isBinary ? 'true' : 'false') . ", size: " . strlen($payload) . ") -> client #{$resourceId}\n";
}
if ($conn->writable ?? true) {
if ($isBinary) {
$frame = new \Ratchet\RFC6455\Messaging\Frame($payload, true, \Ratchet\RFC6455\Messaging\Frame::OP_BINARY);
$conn->send($frame);
} else {
$conn->send($payload);
}
}
});
// Handle Deepgram close
$dgWs->on('close', function ($code = null, $reason = null) use ($conn, $resourceId) {
$code = $code ?? 1000;
$reason = $reason ?? '';
echo "Deepgram connection closed (client #{$resourceId}): {$code} {$reason}\n";
unset($this->deepgramConnections[$resourceId]);
if ($this->clients->contains($conn)) {
$conn->close(getSafeCloseCode($code));
}
});
// Handle Deepgram errors
$dgWs->on('error', function (\Exception $e) use ($conn, $resourceId) {
echo "Deepgram WebSocket error (client #{$resourceId}): {$e->getMessage()}\n";
unset($this->deepgramConnections[$resourceId]);
if ($this->clients->contains($conn)) {
$conn->close(1011);
}
});
},
function (\Exception $e) use ($conn, $resourceId) {
echo "Failed to connect to Deepgram (client #{$resourceId}): {$e->getMessage()}\n";
if ($this->clients->contains($conn)) {
$conn->close(1011);
}
}
);
}
/**
* Handle incoming message from client. Forward to Deepgram.
*
* @param ConnectionInterface $conn The client connection
* @param \Ratchet\RFC6455\Messaging\MessageInterface $msg The message data
*/
public function onMessage(ConnectionInterface $conn, \Ratchet\RFC6455\Messaging\MessageInterface $msg): void
{
$resourceId = $conn->resourceId;
$this->clientMsgCounts[$resourceId] = ($this->clientMsgCounts[$resourceId] ?? 0) + 1;
$count = $this->clientMsgCounts[$resourceId];
$isBinary = $msg->isBinary();
$payload = $msg->getPayload();
if ($count % 100 === 0 || !$isBinary) {
echo " Client #{$resourceId} message #{$count} (binary: " . ($isBinary ? 'true' : 'false') . ", size: " . strlen($payload) . ") -> Deepgram\n";
}
if (isset($this->deepgramConnections[$resourceId])) {
$dgWs = $this->deepgramConnections[$resourceId];
if ($isBinary) {
$frame = new \Ratchet\RFC6455\Messaging\Frame($payload, true, \Ratchet\RFC6455\Messaging\Frame::OP_BINARY);
$dgWs->send($frame);
} else {
$dgWs->send($payload);
}
}
}
/**
* Handle client disconnect. Close corresponding Deepgram connection.
*
* @param ConnectionInterface $conn The client connection
*/
public function onClose(ConnectionInterface $conn): void
{
$resourceId = $conn->resourceId;
echo "Client #{$resourceId} disconnected\n";
$this->clients->detach($conn);
// Close Deepgram connection if open
if (isset($this->deepgramConnections[$resourceId])) {
$this->deepgramConnections[$resourceId]->close(1000, 'Client disconnected');
unset($this->deepgramConnections[$resourceId]);
}
// Clean up counters
unset($this->clientMsgCounts[$resourceId]);
unset($this->dgMsgCounts[$resourceId]);
}
/**
* Handle client WebSocket error.
*
* @param ConnectionInterface $conn The client connection
* @param \Exception $e The error
*/
public function onError(ConnectionInterface $conn, \Exception $e): void
{
$resourceId = $conn->resourceId;
echo "Client #{$resourceId} WebSocket error: {$e->getMessage()}\n";
// Close Deepgram connection if open
if (isset($this->deepgramConnections[$resourceId])) {
$this->deepgramConnections[$resourceId]->close(1011, 'Client error');
unset($this->deepgramConnections[$resourceId]);
}
$conn->close();
}
/**
* Get number of active connections.
*
* @return int Number of active connections
*/
public function getConnectionCount(): int
{
return $this->clients->count();
}
/**
* Close all active connections for graceful shutdown.
*/
public function closeAll(): void
{
foreach ($this->clients as $conn) {
try {
$conn->close(1001);
} catch (\Exception $e) {
// Ignore errors during shutdown
}
}
foreach ($this->deepgramConnections as $dgWs) {
try {
$dgWs->close(1000, 'Server shutting down');
} catch (\Exception $e) {
// Ignore errors during shutdown
}
}
}
}
// ============================================================================
// HTTP HANDLER - /api/session, /api/metadata, and CORS
// ============================================================================
/**
* HTTP request handler for REST endpoints.
* Handles GET /api/session, GET /api/metadata, and CORS preflight.
*/
class HttpHandler implements HttpServerInterface
{
/** @var string JWT signing secret */
private string $sessionSecret;
public function __construct(string $sessionSecret)
{
$this->sessionSecret = $sessionSecret;
}
/**
* Handle incoming HTTP request.
*
* @param ConnectionInterface $conn The HTTP connection
* @param RequestInterface $request The PSR-7 request
*/
public function onOpen(ConnectionInterface $conn, ?RequestInterface $request = null): void
{
$path = $request?->getUri()->getPath() ?? '/';
$method = $request?->getMethod() ?? 'GET';
// Handle CORS preflight
if ($method === 'OPTIONS') {
$response = "HTTP/1.1 204 No Content\r\n";
$response .= "Access-Control-Allow-Origin: *\r\n";
$response .= "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n";
$response .= "Access-Control-Allow-Headers: Content-Type, Authorization\r\n";
$response .= "Content-Length: 0\r\n";
$response .= "\r\n";
$conn->send($response);
$conn->close();
return;
}
// GET /api/session - Issue JWT session token
if ($path === '/api/session' && $method === 'GET') {
$token = createSessionToken($this->sessionSecret);
sendHttpResponse($conn, 200, ['token' => $token]);
return;
}
// GET /health - Simple health check
if ($path === '/health' && $method === 'GET') {
sendHttpResponse($conn, 200, ['status' => 'ok']);
return;
}
// GET /api/metadata - Return metadata from deepgram.toml
if ($path === '/api/metadata' && $method === 'GET') {
try {
$tomlPath = __DIR__ . '/deepgram.toml';
if (!file_exists($tomlPath)) {
sendHttpResponse($conn, 500, [
'error' => 'INTERNAL_SERVER_ERROR',
'message' => 'deepgram.toml not found',
]);
return;
}
$config = Toml::parseFile($tomlPath);
if (!isset($config['meta'])) {
sendHttpResponse($conn, 500, [
'error' => 'INTERNAL_SERVER_ERROR',
'message' => 'Missing [meta] section in deepgram.toml',
]);
return;
}
sendHttpResponse($conn, 200, $config['meta']);
} catch (\Exception $e) {
error_log('Error reading metadata: ' . $e->getMessage());
sendHttpResponse($conn, 500, [
'error' => 'INTERNAL_SERVER_ERROR',
'message' => 'Failed to read metadata from deepgram.toml',
]);
}
return;
}
// 404 for unknown routes
sendHttpResponse($conn, 404, [
'error' => 'Not Found',
'message' => 'Endpoint not found',
]);
}
public function onMessage(ConnectionInterface $conn, $msg): void
{
// HTTP handler does not receive messages
}
public function onClose(ConnectionInterface $conn): void
{
// Nothing to clean up
}
public function onError(ConnectionInterface $conn, \Exception $e): void
{
echo "HTTP error: {$e->getMessage()}\n";
$conn->close();
}
}
// ============================================================================
// SERVER SETUP - Ratchet IoServer with Router
// ============================================================================
$loop = Loop::get();
// Create the WebSocket proxy handler
$fluxHandler = new FluxHandler($API_KEY, $SESSION_SECRET, $CONFIG['deepgramSttUrl']);
// Create the HTTP handler
$httpHandler = new HttpHandler($SESSION_SECRET);
// Build routes using Symfony Routing
$routes = new RouteCollection();
// WebSocket route for /api/flux
$wsServer = new WsServer($fluxHandler);
// Custom ServerNegotiator to accept access_token.* WebSocket subprotocols
$customNegotiator = new class(new \Ratchet\RFC6455\Handshake\RequestVerifier()) extends \Ratchet\RFC6455\Handshake\ServerNegotiator {
public function __construct(\Ratchet\RFC6455\Handshake\RequestVerifier $verifier) {
parent::__construct($verifier);
$this->setStrictSubProtocolCheck(false);
}
public function handshake(\Psr\Http\Message\RequestInterface $request): \Psr\Http\Message\ResponseInterface {
$response = parent::handshake($request);
if ($response->getStatusCode() === 101 && !$response->hasHeader('Sec-WebSocket-Protocol')) {
$protocols = $request->getHeader('Sec-WebSocket-Protocol');
$all = array_map('trim', explode(',', implode(',', $protocols)));
foreach ($all as $proto) {
if (str_starts_with($proto, 'access_token.')) {
$response = $response->withHeader('Sec-WebSocket-Protocol', $proto);
break;
}
}
}
return $response;
}
};
$ref = new \ReflectionProperty($wsServer, 'handshakeNegotiator');
$ref->setValue($wsServer, $customNegotiator);
$routes->add('flux', new Route('/api/flux', [
'_controller' => $wsServer,
], [], [], '', [], ['GET']));
// HTTP routes - individual endpoints + fallback
$routes->add('api_session', new Route('/api/session', [
'_controller' => $httpHandler,
], [], [], '', [], ['GET', 'OPTIONS']));
$routes->add('api_metadata', new Route('/api/metadata', [
'_controller' => $httpHandler,
], [], [], '', [], ['GET', 'OPTIONS']));
$routes->add('health', new Route('/health', [
'_controller' => $httpHandler,
], [], [], '', [], ['GET']));
// Fallback for unknown routes
$routes->add('http_catch_all', new Route('/{path}', [
'_controller' => $httpHandler,
], ['path' => '.*'], [], '', [], ['GET', 'POST', 'OPTIONS']));
$requestContext = new RequestContext();
$urlMatcher = new UrlMatcher($routes, $requestContext);
$router = new Router($urlMatcher);
// Create the server
$socket = new SocketServer("{$CONFIG['host']}:{$CONFIG['port']}", [], $loop);
$server = new IoServer(
new HttpServer($router),
$socket,
$loop
);
echo "\n" . str_repeat('=', 70) . "\n";
echo "Backend API Server running at http://localhost:{$CONFIG['port']}\n";
echo "\n";
echo "GET /api/session\n";
echo "WS /api/flux (auth required)\n";
echo "GET /api/metadata\n";
echo "GET /health\n";
echo str_repeat('=', 70) . "\n\n";
// ============================================================================
// GRACEFUL SHUTDOWN
// ============================================================================
/**
* Handle shutdown signals to close connections cleanly.
*/
function gracefulShutdown(int $signal, $loop, FluxHandler $handler): void
{
$signalName = match ($signal) {
SIGINT => 'SIGINT',
SIGTERM => 'SIGTERM',
default => "Signal {$signal}",
};
echo "\n{$signalName} received: starting graceful shutdown...\n";
$count = $handler->getConnectionCount();
echo "Closing {$count} active WebSocket connection(s)...\n";
$handler->closeAll();
echo "Shutdown complete\n";
$loop->stop();
}
// Register signal handlers via ReactPHP event loop
$loop->addSignal(SIGINT, function (int $sig) use ($loop, $fluxHandler) {
gracefulShutdown($sig, $loop, $fluxHandler);
});
$loop->addSignal(SIGTERM, function (int $sig) use ($loop, $fluxHandler) {
gracefulShutdown($sig, $loop, $fluxHandler);
});
// ============================================================================
// START SERVER
// ============================================================================
$loop->run();