-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathHlebQueueBootstrap.php
More file actions
269 lines (238 loc) · 10.5 KB
/
HlebQueueBootstrap.php
File metadata and controls
269 lines (238 loc) · 10.5 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
<?php
/**
* @author Foma Tuturov <fomiash@yandex.ru>
*/
declare(strict_types=1);
namespace Hleb;
use App\Bootstrap\ContainerFactory;
use ErrorException;
use Hleb\Base\RollbackInterface;
use Hleb\Base\Task;
use Hleb\Constructor\Data\DebugAnalytics;
use Hleb\Constructor\Data\SystemSettings;
use Hleb\Init\ErrorLog;
use Hleb\Main\Logger\Log;
use Hleb\Main\Logger\LoggerInterface;
use Hleb\Constructor\Attributes\Accessible;
use Hleb\Constructor\Attributes\AvailableAsParent;
use Hleb\Main\Logger\LogLevel;
use Throwable;
/**
* Framework loader for executing individual commands from a queue.
* Installed similarly to the console.php file.
* Can be executed by a worker in various modes specified in the constructor,
* since commands may have restrictive attributes.
* Can be used in asynchronous mode.
*
* Загрузчик фреймворка для выполнения отдельных команд из очереди.
* Инсталлируется аналогично файлу console.php
* Может выполняться воркером в различных указанных в конструкторе режимах,
* так как у команд могут быть ограничительные атрибуты.
* Может использоваться в асинхронном режиме.
*
* ```php
*
* (new Hleb\HlebQueueBootstrap(__DIR__))->load(\App\Commands\DefaultTask::class, ['value']);
*
* ```
*/
#[Accessible] #[AvailableAsParent]
class HlebQueueBootstrap extends HlebBootstrap
{
private static int $processNumber = 0;
protected const SUPPORTED_MODES = [self::ASYNC_MODE, self::CONSOLE_MODE, self::STANDARD_MODE];
protected mixed $result = null;
protected bool $verbosity = true;
/**
* A constructor for executing commands from a queue by the framework.
* If the path to the public folder is not used in the project, then it may not be specified,
* in which case the public directory may not exist at all.
*
* Конструктор для выполнения команд из очереди фреймворком.
* Если путь до публичной папки не используется в проекте, то он может быть не указан,
* в этом случае публичной директории вообще может не существовать.
*
* @param string|null $publicPath - full path to the public directory of the project.
* - полный путь к публичной директории проекта.
*
* @param array $config - an array replacing the configuration data.
* - заменяющий конфигурационные данные массив.
*
* @param int $mode - in what mode the commands are executed.
* - в каком режиме выполняются команды.
*
* @throws Throwable
*/
public function __construct(
?string $publicPath = null,
array $config = [],
?LoggerInterface $logger = null,
int $mode = self::STANDARD_MODE,
) {
\defined('HLEB_IS_QUEUE') or \define('HLEB_IS_QUEUE', 'on');
if (!\in_array($mode, self::SUPPORTED_MODES)) {
throw new \ErrorException('Unsupported mode');
}
$this->mode = $mode;
\defined('HLEB_START') or \define('HLEB_START', \microtime(true));
// Initialization errors should be sent to the log.
// Ошибки инициализации должны быть отправлены в лог.
try {
parent::__construct($publicPath, $config, $logger);
} catch (Throwable $t) {
$this->errorLog($t);
throw $t;
}
}
/**
* Getting the result of the executed command as specified in the command code via setResult().
*
* Получение результата выполненной команды как заданное в коде команды через setResult().
*/
public function getResult(): mixed
{
return $this->result;
}
/**
* Sets whether data should be output as content when executing a task.
*
* Устанавливает, нужно ли выводить данные при выполнении задачи как контент.
*/
public function setVerbosity(bool $value): void
{
$this->verbosity = $value;
}
/**
* @return array
*/
protected function getDefaultConfig(): array
{
$config = parent::getDefaultConfig();
$config['common']['allowed.hosts'] = [];
$config['common']['max.cli.log.level'] = 'info';
$config['common']['max.log.level'] = 'info';
$config['common']['routes.auto-update'] = false;
$config['main']['session.enabled'] = false;
return $config;
}
/**
* Execute a command from a queue.
* Returns the exit code of the script.
*
* Выполнение команды из очереди.
* Возвращает код завершения скрипта.
*
* @param string|null $commandClass - class of command to be executed. The name is used here rather than the
* class object, so as not to initialize a third-party autoloader for it.
*
* - класс команды, который должен быть выполнен. Здесь используется название, а не
* объект класса, чтобы не инициализировать для него сторонний автозагрузчик.
*
*
* @param array $arguments - an array with arguments for the command.
* - массив с аргументами для команды.
*
* @throws Throwable
*/
#[\Override]
public function load(?string $commandClass = null, array $arguments = []): int
{
self::$processNumber++;
\date_default_timezone_set($this->config['common']['timezone']);
if (!$commandClass) {
throw new ErrorException('The command must be specified.');
}
if (!\is_a($commandClass, Task::class, true)) {
throw new ErrorException('The command class must be inherited from ' . Task::class);
}
$status = true;
try {
$this->loadSettings();
$command = new $commandClass();
$status = $command->call($arguments, strictVerbosity: $this->verbosity);
$this->result = $command->getResult();
} catch (\AsyncExitException $e) {
echo $e->getMessage();
} catch (Throwable $t) {
$this->logsPostProcessing();
$this->errorLog($t);
if ($this->mode !== self::ASYNC_MODE) {
throw $t;
}
$status = false;
} finally {
$this->logsPostProcessing();
if ($this->mode === self::ASYNC_MODE) {
self::prepareAsyncRequestData($this->config, self::$processNumber);
}
}
return (int)($status != false);
}
/**
* Preparing data to use an asynchronous request.
*
* Подготовка данных к использованию асинхронного запроса.
*
* @see HlebAsyncBootstrap::prepareAsyncRequestData()
*
* @internal
*/
protected static function prepareAsyncRequestData(array $config, int $processNumber): void
{
// If your application does not use state storage, you can disable state cleanup.
// Если в приложении не используется хранение состояния, то можно отключить его очистку.
if ($config['system']['async.clear.state'] ?? true) {
foreach (\get_declared_classes() as $class) {
\is_a($class, RollbackInterface::class, true) and $class::rollback();
}
}
foreach ([ContainerFactory::class, Registrar::class, DebugAnalytics::class, ErrorLog::class] as $class) {
\class_exists($class, false) and $class::rollback();
}
/*
* Periodically clean up used memory and call GC. Will be applied to every $rate request.
* For example, if you pass HLEB_ASYNC_RE_CLEANING=3, then after every third request.
*
* Периодическая очистка используемой памяти и вызов GC. Будет применено к каждому $rate запросу.
* Например, если передать HLEB_ASYNC_RE_CLEANING=3, то после каждого третьего запроса.
*/
$rate = (int)get_env('HLEB_ASYNC_RE_CLEANING', get_constant('HLEB_ASYNC_RE_CLEANING', self::DEFAULT_RE_CLEANING));
if ($rate >= 0 && ($rate === 0 || $processNumber % $rate == 0)) {
\gc_collect_cycles();
\gc_mem_caches();
}
\memory_reset_peak_usage();
}
/**
* Saving the error in prepared form if it occurred at the top level.
*
* Сохранение ошибки в подготовленном виде, если она возникла на самом верхнем уровне.
*/
public function errorLog(Throwable $e): void
{
// The error may be in the error handler itself.
// Ошибка может быть в самом обработчике ошибок.
try {
\class_exists(ErrorLog::class, false) or require __DIR__ . '/Init/ErrorLog.php';
ErrorLog::log($e);
} catch (Throwable $t) {
\error_log((string)$e);
\error_log((string)$t);
}
}
/**
* Simplified project assembly.
*
* Упрощённая сборка проекта.
*/
protected function loadSettings(): void
{
$startTime = \defined('HLEB_START') ? HLEB_START : \microtime(true);
$this->config['system']['start.unixtime'] = $startTime;
SystemSettings::setStartTime($startTime);
$this->logger and Log::setLogger($this->logger);
LogLevel::setDefaultMaxLogLevel(SystemSettings::getCommonValue('max.log.level'));
\date_default_timezone_set($this->config['common']['timezone']);
\ini_set('display_errors', $this->config['common']['debug'] ? '1' : '0');
}
}