-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathWebRotor.php
More file actions
406 lines (359 loc) · 13.6 KB
/
WebRotor.php
File metadata and controls
406 lines (359 loc) · 13.6 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
<?php
declare(strict_types=1);
namespace Phphleb\Webrotor;
use Phphleb\Webrotor\Src\Exception\WebRotorComplianceException;
use Phphleb\Webrotor\Src\Exception\WebRotorConfigException;
use Phphleb\Webrotor\Src\Exception\WebRotorException;
use Phphleb\Webrotor\Src\Handler\Psr7Converter;
use Phphleb\Webrotor\Src\Handler\Psr7CreatorInterface;
use Phphleb\Webrotor\Src\InternalConfig;
use Phphleb\Webrotor\Src\Log\FileLogger;
use Phphleb\Webrotor\Src\Middleware\CookieMiddlewareInterface;
use Phphleb\Webrotor\Src\Middleware\SessionMiddlewareInterface;
use Phphleb\Webrotor\Src\Process\Cleaner;
use Phphleb\Webrotor\Src\Process\Output;
use Phphleb\Webrotor\Src\Process\Spawn\TemporaryWorkerCreator;
use Phphleb\Webrotor\Src\Process\Spawn\TemporaryWorkerCreatorInterface;
use Phphleb\Webrotor\Src\Session\SessionManager;
use Phphleb\Webrotor\Src\Process\Worker;
use Phphleb\Webrotor\Src\Log\LoggerManager;
use Phphleb\Webrotor\Src\Session\SessionManagerInterface;
use Phphleb\Webrotor\Src\Storage\FileStorage;
use Phphleb\Webrotor\Src\Storage\SharedMemoryStorage;
use Phphleb\Webrotor\Src\Storage\StorageInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;
$argv = $argv ?? null;
/**
* @author Foma Tuturov <fomiash@yandex.ru>
*
* Implementing an asynchronous web server.
*/
final class WebRotor
{
public const ID_ARG = '--id';
public const TEMPORARY_WORKER_ARG = '--temporary-worker';
public const RUNTIME_DIR = 'wr-runtime';
public const LOGS_DIR = 'wr-logs';
/**
* @var bool
*/
private $hasInitialized = false;
/**
* @var int
*/
private $executions = 0;
/**
* @var InternalConfig
*/
private $config;
/**
* @var StorageInterface|null
*/
private $storage = null;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var Worker
*/
private $process = null;
/**
* @var CookieMiddlewareInterface|null
*/
private $cookie = null;
/**
* @var SessionMiddlewareInterface|null
*/
private $session = null;
/**
* @var Output|null
*/
private $output = null;
/**
* @var null|SessionManagerInterface
*/
private $sessionManager = null;
/**
* @var null|TemporaryWorkerCreatorInterface
*/
private $workerCreator = null;
/**
* @var bool
*/
private $isWorker;
/**
* @var string|null
*/
private $searchTag = null;
/**
* @param Config|null $config - a configuration object with non-standard settings.
* @param LoggerInterface|null $logger - implementation of a custom logger.
* @param array<string, array<int, string>|null> $globals - defining additional global variable.
*/
public function __construct(?Config $config = null, ?LoggerInterface $logger = null, array $globals = [])
{
global $argv;
$arguments = array_key_exists('argv', $globals) ? $globals['argv'] : $argv;
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2);
if (empty($backtrace[0]['file'])) {
throw new WebRotorException('Could not determine public project directory');
}
$this->isWorker = empty($_SERVER['REQUEST_METHOD']) && is_array($arguments);
$this->config = $this->initConfig($config ?? new Config(), $backtrace[0]['file'], $arguments);
$logger = $logger ?? new FileLogger($this->config);
$this->logger = $logger;
WebRotorException::$logger = $this->logger;
register_shutdown_function(static function() use ($logger) {
$error = error_get_last();
gc_collect_cycles();
gc_mem_caches();
if ($error &&
(strpos($error['file'], 'webrotor') !== false ||
strpos($error['message'], 'Allowed memory size') !== false
)) {
$logger->error("{$error['message']} in {$error['file']} on line {$error['line']}");
}
});
}
/**
* @param StorageInterface $value - data storage different from the default (in files)
*/
public function setStorage(StorageInterface $value): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setStorage` method cannot be used after initialization');
}
$this->storage = $value;
return $this;
}
/**
* @param CookieMiddlewareInterface $value - custom Cookies handler.
*/
public function setCookieMiddleware(CookieMiddlewareInterface $value): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setCookieMiddleware` method cannot be used after initialization');
}
$this->cookie = $value;
return $this;
}
/**
* @param SessionMiddlewareInterface $value - custom session handler.
*/
public function setSessionMiddleware(SessionMiddlewareInterface $value): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setSessionMiddleware` method cannot be used after initialization');
}
$this->session = $value;
return $this;
}
/**
* @param Output $value - custom result handler.
*/
public function setOutput(Output $value): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setOutput` method cannot be used after initialization');
}
$this->output = $value;
return $this;
}
/**
* @param SessionManagerInterface $sessionManager - custom session handler.
*/
public function setSessionManager(SessionManagerInterface $sessionManager): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setSessionManager` method cannot be used after initialization');
}
$this->sessionManager = $sessionManager;
return $this;
}
/**
* @param TemporaryWorkerCreatorInterface $workerCreator - custom new worker handler.
*/
public function setWorkerCreator(TemporaryWorkerCreatorInterface $workerCreator): self
{
if ($this->hasInitialized) {
throw new WebRotorException('The `setWorkerCreator` method cannot be used after initialization');
}
$this->workerCreator = $workerCreator;
return $this;
}
/**
* The initialization method for asynchronous processing
* must be called before initializing your working code (framework).
*
* @param Psr7CreatorInterface $psr7Creator - a wrapper for initializing PSR-7 objects.
*
* @return array<string, mixed>
*/
public function init(Psr7CreatorInterface $psr7Creator): array
{
$this->hasInitialized = true;
$storage = $this->storage;
if (!$storage) {
$storage = new FileStorage($this->config->getRuntimeDirectory());
$this->logger->debug('The file data storage is automatically selected');
}
$this->sessionManager = $this->sessionManager ?? new SessionManager($this->logger, $this->config);
$workerCreator = $this->workerCreator ?? new TemporaryWorkerCreator($this->config, $this->logger, $storage);
$this->process = new Worker(
$this->config,
$storage,
new Psr7Converter(
$psr7Creator,
$this->cookie,
$this->session,
$this->sessionManager
),
$this->logger,
$this->sessionManager,
$workerCreator
);
if ($this->isWorker) {
$this->logger->debug(...LoggerManager::createInitialWorkerInfo($this->config));
}
if (!$this->isWorker && $this->process->isWorkersActive()) {
/**
* @var array<string, null|string> $request
* @var string $tag
*/
[$tag, $request] = $this->process->setCurrentRequest();
$this->searchTag = $tag;
if (empty($request)) {
return [];
}
$this->logger->info(...LoggerManager::createStartInfoFromLogger($request, $tag));
return $this->process->prepareRequest($tag, $this->output ?? new Output($this->process->getSessionManager()));
}
return [];
}
/**
* External code handler in a function.
*
* @return array<string, mixed>
*/
public function run(callable $fn): array
{
$this->executions++;
if (!$this->hasInitialized) {
throw new WebRotorException('The `run` method can only be used after initialization');
}
$this->output = $this->output ?? new Output($this->process->getSessionManager());
if ($this->isWorker) {
$this->process->setWorkerStat();
(new Cleaner($this->process, $this->config, $this->logger))->cleanOldResources();
// Processing the requests in worker mode.
foreach($this->process->getRequests() as $tag => $request) {
$start = microtime(true);
try {
/**
* @var ResponseInterface $response - the result of executing application code.
*/
$response = $fn($request, $this->process->createDefaultResponse());
/** @var ServerRequestInterface $request */
$this->process->sendWorkerLog($request, $response, $tag);
} catch (Throwable $t) {
$response = $this->process->getErrorResponse($this->config->isDebug() ? (string)$t : '');
/** @var ServerRequestInterface $request */
$this->process->sendWorkerLog($request, $response, $tag, $t);
}
/** @var ServerRequestInterface $request */
$this->process->setResponse($tag, $response, $request);
$this->output->setResponse($response);
$this->process->logStat($tag, $start);
}
} else {
// If the worker was unable to process the request,
// it is displayed in standard mode.
$request = $this->process->createCurrentRequest();
try {
/**
* @var ResponseInterface $response - the result of executing application code.
*/
$response = $fn($request, $this->process->createDefaultResponse());
$this->process->sendStandardLog($request, $response);
} catch (Throwable $t) {
$response = $this->process->getErrorResponse($this->config->isDebug() ? (string)$t : '');
$this->process->sendStandardLog($request, $response, $t);
}
$this->process->logStat($this->searchTag ?? 'undefined');
$this->output->run($this->process->handleResponse($request, $response));
}
return $this->output->getResult();
}
/**
* @param array<int, string>|null $arguments
*/
private function initConfig(Config $config, string $indexFilePath, ?array $arguments): InternalConfig
{
$publicDirectory = dirname($indexFilePath);
$runtimeDirectory = $config->runtimeDirectory;
$logDirectory = $config->logDirectory;
if (empty($runtimeDirectory)) {
$runtimeDirectory = dirname($publicDirectory) . DIRECTORY_SEPARATOR . self::RUNTIME_DIR;
}
if (empty($logDirectory)) {
$logDirectory = dirname($publicDirectory) . DIRECTORY_SEPARATOR . self::LOGS_DIR;
}
$isTemporaryWorker = false;
$interpreterPathPattern = '';
if ($this->isWorker) {
if ($config->interpreterPathPattern) {
$version = preg_replace('/(\d+\.\d+)(\.\d+)?/', '$1', PHP_VERSION);
if ($version) {
$interpreterPathPattern = str_replace('{version}', $version, $config->interpreterPathPattern);
}
if (!is_dir($interpreterPathPattern)) {
$interpreterPathPattern = '';
}
}
foreach($arguments ?? [] as $arg) {
if ($arg === self::TEMPORARY_WORKER_ARG) {
$isTemporaryWorker = true;
}
}
foreach($arguments ?? [] as $arg) {
if (strpos($arg, self::ID_ARG . '=') === 0) {
$workerId = (int)substr($arg, strlen(self::ID_ARG) + 1);
if ((!$isTemporaryWorker && $workerId > $config->workerNum) || $workerId < 1) {
throw new WebRotorConfigException('The ID of the current worker is not included in the number set in the configuration');
}
}
}
}
$maxExecutionTime = ini_get('max_execution_time');
if (!is_numeric($maxExecutionTime)) {
$maxExecutionTime = $this->isWorker ? 0 : 30;
}
return new InternalConfig(
$indexFilePath,
microtime(true),
$config->workerNum,
$runtimeDirectory,
$workerId ?? 1,
$config->workerLifetimeSec,
(int)$maxExecutionTime,
$logDirectory,
$config->logLevel,
$config->workerResponseTimeSec,
$config->debug,
$config->logRotationPerDay,
$config->timeZone,
$this->isWorker,
$config->temporaryWorkerLifetimeSec,
$isTemporaryWorker,
$interpreterPathPattern,
$config->codeVersion,
$config->workerRequestDelayMicroSec,
$config->responseDelayWaitMicroSec,
$config->idleTimeoutSec
);
}
}