-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactServer.php
More file actions
251 lines (210 loc) · 8.39 KB
/
Copy pathReactServer.php
File metadata and controls
251 lines (210 loc) · 8.39 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
<?php
declare(strict_types=1);
namespace PivotPHP\ReactPHP\Server;
use PivotPHP\Core\Core\Application;
use PivotPHP\Core\Http\Response as PivotResponse;
use PivotPHP\ReactPHP\Bridge\RequestBridge;
use PivotPHP\ReactPHP\Bridge\RequestFactory;
use PivotPHP\ReactPHP\Bridge\ResponseBridge;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Http\HttpServer;
use React\Http\Message\Response as ReactResponse;
use React\Promise\Promise;
use React\Socket\SocketServer;
use Throwable;
final class ReactServer
{
private HttpServer $httpServer;
private ?SocketServer $socketServer = null;
private LoopInterface $loop;
private LoggerInterface $logger;
private RequestBridge $requestBridge;
private RequestFactory $requestFactory;
private ResponseBridge $responseBridge;
private array $config;
public function __construct(
private Application $application,
?LoopInterface $loop = null,
?LoggerInterface $logger = null,
array $config = []
) {
$this->loop = $loop ?? Loop::get();
$this->logger = $logger ?? new NullLogger();
$this->config = array_merge($this->getDefaultConfig(), $config);
$this->requestBridge = new RequestBridge();
$this->requestFactory = RequestFactory::create();
$this->responseBridge = new ResponseBridge();
$this->initializeHttpServer();
}
public function listen(string $address = '0.0.0.0:8080'): void
{
$this->socketServer = new SocketServer($address, [], $this->loop);
$this->httpServer->listen($this->socketServer);
$this->logger->info('ReactPHP server started', [
'address' => $address,
'pid' => getmypid(),
'memory' => memory_get_usage(true),
]);
$this->registerSignalHandlers();
$this->loop->run();
}
public function stop(): void
{
$this->logger->info('Stopping ReactPHP server...');
if ($this->socketServer !== null) {
$this->socketServer->close();
$this->socketServer = null;
}
$this->loop->stop();
$this->logger->info('ReactPHP server stopped');
}
public function getLoop(): LoopInterface
{
return $this->loop;
}
private function initializeHttpServer(): void
{
$middleware = [];
if ($this->config['streaming']) {
$middleware[] = new \React\Http\Middleware\StreamingRequestMiddleware();
}
if ($this->config['request_body_buffer_size'] !== null) {
$middleware[] = new \React\Http\Middleware\RequestBodyBufferMiddleware(
$this->config['request_body_buffer_size']
);
}
if ($this->config['request_body_size_limit'] !== null) {
$middleware[] = new \React\Http\Middleware\LimitConcurrentRequestsMiddleware(
$this->config['max_concurrent_requests']
);
}
$middleware[] = [$this, 'handleRequest'];
$this->httpServer = new HttpServer($this->loop, ...$middleware);
}
public function handleRequest(ServerRequestInterface $request): Promise
{
return new Promise(function ($resolve, $reject) use ($request) {
try {
$startTime = microtime(true);
// Convert ReactPHP request to PSR-7 ServerRequest
$psrRequest = $this->requestBridge->convertFromReact($request);
// Handle request through PivotPHP Application
// Convert PSR-7 to PivotPHP Request if needed (concurrency-safe)
if (!($psrRequest instanceof \PivotPHP\Core\Http\Request)) {
// Create PivotPHP Request using the cleaner factory approach
// This reduces reflection usage and is more maintainable
$pivotRequest = $this->requestFactory->createFromPsr7($psrRequest);
$psrResponse = $this->application->handle($pivotRequest);
} else {
$psrResponse = $this->application->handle($psrRequest);
}
// Convert PSR-7 Response to ReactPHP Response
// Use streaming if enabled and response indicates streaming
if ($this->config['streaming'] && $this->isStreamingResponse($psrResponse)) {
$reactResponse = $this->responseBridge->convertToReactStream($psrResponse);
} else {
$reactResponse = $this->responseBridge->convertToReact($psrResponse);
}
$duration = (microtime(true) - $startTime) * 1000;
$this->logger->info('Request handled', [
'method' => $request->getMethod(),
'uri' => (string) $request->getUri(),
'status' => $psrResponse->getStatusCode(),
'duration_ms' => round($duration, 2),
'memory' => memory_get_usage(true),
]);
$resolve($reactResponse);
} catch (Throwable $e) {
$this->handleError($e, $resolve);
}
});
}
private function handleError(Throwable $e, callable $resolve): void
{
$this->logger->error('Request handling failed', [
'error' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]);
// Use PivotPHP's error handling if available
if ($this->application->has('error.handler')) {
try {
$errorHandler = $this->application->make('error.handler');
if (is_object($errorHandler) && method_exists($errorHandler, 'handle')) {
$errorResponse = $errorHandler->handle($e);
} else {
throw new \RuntimeException('Invalid error handler');
}
$reactResponse = $this->responseBridge->convertToReact($errorResponse);
$resolve($reactResponse);
return;
} catch (Throwable $handlerError) {
$this->logger->error('Error handler failed', [
'error' => $handlerError->getMessage(),
]);
}
}
// Fallback error response
$errorBody = json_encode([
'error' => 'Internal Server Error',
'message' => $this->config['debug'] ? $e->getMessage() : 'An error occurred',
'error_id' => uniqid('err_', true),
]);
$resolve(new ReactResponse(
500,
['Content-Type' => 'application/json'],
$errorBody !== false ? $errorBody : '{"error":"Internal Server Error"}'
));
}
private function isStreamingResponse(\Psr\Http\Message\ResponseInterface $response): bool
{
// Check if response should be streamed based on headers or other indicators
$contentType = $response->getHeaderLine('Content-Type');
$transferEncoding = $response->getHeaderLine('Transfer-Encoding');
// Stream if chunked transfer encoding is used
if ($transferEncoding === 'chunked') {
return true;
}
// Stream for certain content types
$streamableTypes = [
'text/event-stream',
'application/octet-stream',
'video/',
'audio/',
];
foreach ($streamableTypes as $type) {
if (str_starts_with($contentType, $type)) {
return true;
}
}
// Check for custom streaming header
return $response->hasHeader('X-Stream-Response');
}
private function registerSignalHandlers(): void
{
if (!function_exists('pcntl_signal')) {
return;
}
$handler = function (int $signal) {
$this->logger->info('Received signal', ['signal' => $signal]);
$this->stop();
};
$this->loop->addSignal(SIGTERM, $handler);
$this->loop->addSignal(SIGINT, $handler);
}
private function getDefaultConfig(): array
{
return [
'debug' => false,
'streaming' => false,
'max_concurrent_requests' => 100,
'request_body_size_limit' => 67108864, // 64MB
'request_body_buffer_size' => 8192, // 8KB
];
}
}