Files
proton/framework/Queue/Worker.php
T
2026-09-12 23:55:44 +03:00

227 lines
7.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Queue;
use Rsgrinko\Proton\Cache\Cache;
use Rsgrinko\Proton\Models\AuditEntry;
use Rsgrinko\Proton\Models\RememberToken;
use Rsgrinko\Proton\Models\Setting;
use Rsgrinko\Proton\Models\UserSession;
use Rsgrinko\Proton\RateLimit\RateLimiter;
use Rsgrinko\Proton\Support\Config;
use Rsgrinko\Proton\Support\Logger;
use Rsgrinko\Proton\Support\RequestId;
use Throwable;
/**
* Воркер очереди: разбирает задачи, ведёт расписание и подчищает за приложением.
*
* Запускается демоном (systemd) или по cron с ключом --once. После выкладки кода
* воркер нужно перезапускать: он держит загруженные классы в памяти, и веб-часть
* уже отвечает по-новому, пока задачи выполняются старым кодом. Флаг перезапуска
* ставится командой worker:restart — воркер доработает круг и выйдет сам.
*/
final class Worker
{
/** Ключ в settings, по которому воркеру говорят «выйди» */
public const RESTART_KEY = 'worker:restart';
private Logger $logger;
private string $queue;
private bool $stopping = false;
public function __construct(string $queue = Queue::DEFAULT_QUEUE)
{
$this->logger = new Logger('worker');
$this->queue = $queue;
}
/**
* Основной цикл. $once — разобрать всё готовое и выйти (для cron).
*
* @return array{done: int, failed: int}
*/
public function run(bool $once = false): array
{
$this->listenSignals();
$startedAt = time();
$done = 0;
$failed = 0;
$sleep = max(1, (int) Config::get('queue.sleep', 3));
$lifetime = max(0, (int) Config::get('queue.worker_lifetime', 3600));
$restartAt = (int) Setting::get(self::RESTART_KEY, '0');
$this->logger->info('Воркер запущен', ['queue' => $this->queue, 'once' => $once]);
do {
$job = Queue::claim($this->queue);
if ($job !== null) {
$this->perform($job) ? $done++ : $failed++;
continue;
}
// Очередь пуста — самое время заняться обслуживанием
$this->maintenance();
if ($once || $this->stopping) {
break;
}
if ($lifetime > 0 && time() - $startedAt >= $lifetime) {
$this->logger->info('Воркер отработал своё время и выходит');
break;
}
if ((int) Setting::get(self::RESTART_KEY, '0') > $restartAt) {
$this->logger->info('Получен запрос на перезапуск');
break;
}
sleep($sleep);
} while (true);
$this->logger->info('Воркер остановлен', ['done' => $done, 'failed' => $failed]);
return ['done' => $done, 'failed' => $failed];
}
/**
* Просит работающий воркер выйти: systemd поднимет его заново уже с новым кодом.
*/
public static function requestRestart(): void
{
Setting::set(self::RESTART_KEY, (string) time());
}
/**
* Выполняет одну задачу. true — получилось.
*
* @param array<string, mixed> $row
*/
private function perform(array $row): bool
{
// Своя цепочка на каждую задачу: соседние задачи не должны сливаться
// в одну строку логов
RequestId::set((string) ($row['request_id'] ?? ''));
$class = (string) $row['job_class'];
$payload = json_decode((string) $row['payload'], true);
$payload = is_array($payload) ? $payload : [];
if (!class_exists($class) || !is_subclass_of($class, Job::class)) {
Queue::fail($row, 'Класс задачи не найден: ' . $class, 0);
$this->logger->error('Задача без класса', ['id' => $row['id'], 'class' => $class]);
return false;
}
/** @var Job $job */
$job = new $class();
$startedAt = microtime(true);
try {
$job->handle($payload);
Queue::complete((int) $row['id']);
$this->logger->info('Задача выполнена', [
'id' => (int) $row['id'],
'job' => $class,
'ms' => (int) round((microtime(true) - $startedAt) * 1000),
]);
return true;
} catch (Throwable $e) {
$attempt = (int) $row['attempts'];
$again = Queue::fail($row, $e->getMessage(), $job->backoff($attempt));
$this->logger->error('Задача упала', [
'id' => (int) $row['id'],
'job' => $class,
'attempt' => $attempt,
'again' => $again,
'error' => $e->getMessage(),
]);
if (!$again) {
try {
$job->failed($payload, $e->getMessage());
} catch (Throwable $inner) {
$this->logger->error('Обработчик отказа тоже упал', ['error' => $inner->getMessage()]);
}
}
return false;
}
}
/**
* Уборка и расписание — то, ради чего в других проектах держат cron.
*/
private function maintenance(): void
{
$interval = max(60, (int) Config::get('queue.maintenance_interval', 300));
$last = (int) Setting::get('worker:maintenance', '0');
if (time() - $last < $interval) {
// Расписание проверяем чаще уборки: у задач может быть свой минутный шаг
Scheduler::run();
return;
}
Setting::set('worker:maintenance', (string) time());
try {
Queue::releaseStuck((int) Config::get('queue.stuck_minutes', 15));
Queue::purge((int) Config::get('queue.keep_days', 7));
(new RateLimiter())->cleanup();
Cache::cleanup();
RememberToken::purge();
UserSession::purge((int) Config::get('auth.sessions_keep_days', 60));
AuditEntry::purge((int) Config::get('audit.keep_days', 180));
(new Logger('app'))->purge();
Scheduler::run();
} catch (Throwable $e) {
$this->logger->error('Обслуживание не доехало', ['error' => $e->getMessage()]);
}
}
/**
* Ctrl+C и systemd stop должны останавливать воркер по-хорошему: доработать
* текущую задачу и выйти, а не обрываться на середине.
*/
private function listenSignals(): void
{
if (!function_exists('pcntl_signal')) {
return;
}
pcntl_async_signals(true);
foreach ([SIGTERM, SIGINT] as $signal) {
pcntl_signal($signal, function (): void {
$this->stopping = true;
$this->logger->info('Получен сигнал остановки, доработаю круг');
});
}
}
}