diff --git a/app/Controllers/Admin/QueueController.php b/app/Controllers/Admin/QueueController.php index a1faa20..83b334d 100644 --- a/app/Controllers/Admin/QueueController.php +++ b/app/Controllers/Admin/QueueController.php @@ -39,7 +39,7 @@ final class QueueController extends Controller Filter::text('queue', 'Очередь', 'queue', 'default, webhooks'), Filter::search('q', 'Поиск', ['job_class', 'error'], 'класс задачи или ошибка'), Filter::dates('when', 'Когда', 'created_at'), - ])->sortable(['id', 'priority', 'created_at'], 'id'); + ])->sortable(['id', 'priority', 'created_at', 'duration_ms'], 'id'); $query = $filters->apply(Connection::instance()->table('jobs')); diff --git a/docs/QUEUE.md b/docs/QUEUE.md index 22412c9..05151a1 100644 --- a/docs/QUEUE.md +++ b/docs/QUEUE.md @@ -68,6 +68,13 @@ php bin/proton worker:restart # доработает круг и вый доставок вебхуков, прочитанные уведомления и логи. Приложению об этом заботиться не нужно. +У каждой выполненной или упавшей задачи в панели («Очередь») видно, сколько она +заняла и сколько раз сходила в базу — колонки «Время» и «SQL». Число запросов +считается, только если включён `APP_DEBUG`: полные тексты запросов не хранятся +(на очереди рассылок это были бы гигабайты), только счётчик и сумма времени — +задача, которая вдруг стала делать втрое больше запросов, чем обычно, видна +сразу. Время выполнения пишется всегда, без отладки. + ### Разбор полётов ```bash diff --git a/framework/Queue/Queue.php b/framework/Queue/Queue.php index 3e92d34..c425c4b 100644 --- a/framework/Queue/Queue.php +++ b/framework/Queue/Queue.php @@ -118,29 +118,32 @@ final class Queue /** * Задача выполнена. + * + * @param array{duration_ms?: int, queries_count?: int|null, queries_ms?: float|null}|null $profile */ - public static function complete(int $id): void + public static function complete(int $id, ?array $profile = null): void { - Connection::instance()->update('jobs', [ + Connection::instance()->update('jobs', array_merge([ 'status' => self::DONE, 'finished_at' => Connection::now(), 'updated_at' => Connection::now(), 'error' => null, - ], ['id' => $id]); + ], self::profileColumns($profile)), ['id' => $id]); } /** * Задача упала: возвращаем в очередь с паузой или признаём неудавшейся. * - * @param array $row + * @param array $row + * @param array{duration_ms?: int, queries_count?: int|null, queries_ms?: float|null}|null $profile */ - public static function fail(array $row, string $error, int $backoff): bool + public static function fail(array $row, string $error, int $backoff, ?array $profile = null): bool { $attempts = (int) $row['attempts']; $max = (int) $row['max_attempts']; $again = $attempts < $max; - Connection::instance()->update('jobs', [ + Connection::instance()->update('jobs', array_merge([ // Исчерпала попытки — уходит в «мёртвые»: их разбирают руками, // а не повторяют бесконечно 'status' => $again ? self::QUEUED : self::DEAD, @@ -148,11 +151,32 @@ final class Queue 'error' => mb_substr($error, 0, 1000), 'finished_at' => $again ? null : Connection::now(), 'updated_at' => Connection::now(), - ], ['id' => (int) $row['id']]); + ], self::profileColumns($profile)), ['id' => (int) $row['id']]); return $again; } + /** + * Колонки профиля для UPDATE — своим методом, чтобы complete() и fail() + * не дублировали одну и ту же сборку. + * + * @param array{duration_ms?: int, queries_count?: int|null, queries_ms?: float|null}|null $profile + * + * @return array + */ + private static function profileColumns(?array $profile): array + { + if ($profile === null) { + return []; + } + + return [ + 'duration_ms' => $profile['duration_ms'] ?? null, + 'queries_count' => $profile['queries_count'] ?? null, + 'queries_ms' => $profile['queries_ms'] ?? null, + ]; + } + /** * Повторить неудавшуюся задачу. */ diff --git a/framework/Queue/Worker.php b/framework/Queue/Worker.php index 322b6ab..d400802 100644 --- a/framework/Queue/Worker.php +++ b/framework/Queue/Worker.php @@ -18,6 +18,7 @@ use Rsgrinko\Proton\RateLimit\RateLimiter; use Rsgrinko\Proton\Support\Config; use Rsgrinko\Proton\Support\ExportFile; use Rsgrinko\Proton\Support\Logger; +use Rsgrinko\Proton\Support\Profiler; use Rsgrinko\Proton\Support\Trash; use Rsgrinko\Proton\Support\RequestId; use Throwable; @@ -172,23 +173,32 @@ final class Worker /** @var Job $job */ $job = new $class(); + // Своя пачка запросов на каждую задачу: иначе счётчик копится + // с предыдущей и цифры ничего не значат + Profiler::reset(); + $startedAt = microtime(true); try { $job->handle($payload); - Queue::complete((int) $row['id']); + $profile = $this->profile($startedAt); + + Queue::complete((int) $row['id'], $profile); $this->logger->info('Задача выполнена', [ - 'id' => (int) $row['id'], - 'job' => $class, - 'ms' => (int) round((microtime(true) - $startedAt) * 1000), + 'id' => (int) $row['id'], + 'job' => $class, + 'ms' => $profile['duration_ms'], + 'queries' => $profile['queries_count'], ]); return true; } catch (Throwable $e) { + $profile = $this->profile($startedAt); + $attempt = (int) $row['attempts']; - $again = Queue::fail($row, $e->getMessage(), $job->backoff($attempt)); + $again = Queue::fail($row, $e->getMessage(), $job->backoff($attempt), $profile); $this->logger->error('Задача упала', [ 'id' => (int) $row['id'], @@ -210,6 +220,22 @@ final class Worker } } + /** + * Сколько заняла задача и сколько сходила в базу. Запросы считаются, только + * когда включён APP_DEBUG — на бою это лишняя память на каждую задачу, + * а вот время выполнения ничего не стоит и нужно всегда. + * + * @return array{duration_ms: int, queries_count: int|null, queries_ms: float|null} + */ + private function profile(float $startedAt): array + { + return [ + 'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000), + 'queries_count' => Profiler::enabled() ? Profiler::count() : null, + 'queries_ms' => Profiler::enabled() ? Profiler::time() : null, + ]; + } + /** * Уборка и расписание — то, ради чего в других проектах держат cron. */ diff --git a/migrations/20260916030000_add_job_profile.php b/migrations/20260916030000_add_job_profile.php new file mode 100644 index 0000000..f2dfe38 --- /dev/null +++ b/migrations/20260916030000_add_job_profile.php @@ -0,0 +1,36 @@ +table('jobs', function (Blueprint $table): void { + $table->integer('duration_ms')->nullable(); + $table->integer('queries_count')->nullable(); + $table->float('queries_ms')->nullable(); + }); + } + + public function down(): void + { + $this->table('jobs', function (Blueprint $table): void { + $table->dropColumn('duration_ms'); + $table->dropColumn('queries_count'); + $table->dropColumn('queries_ms'); + }); + } +} diff --git a/resources/views/admin/queue.php b/resources/views/admin/queue.php index f7fd90c..2009ab8 100644 --- a/resources/views/admin/queue.php +++ b/resources/views/admin/queue.php @@ -104,6 +104,8 @@ $badges = [ $filters, 'route' => 'admin.queue', 'column' => 'priority', 'label' => 'Важность']) ?> Состояние Попытки + $filters, 'route' => 'admin.queue', 'column' => 'duration_ms', 'label' => 'Время']) ?> + SQL $filters, 'route' => 'admin.queue', 'column' => 'created_at', 'label' => 'Создана']) ?> @@ -122,6 +124,10 @@ $badges = [ из + + diff --git a/tests/QueueExtraTest.php b/tests/QueueExtraTest.php index 72df6c7..09291a1 100644 --- a/tests/QueueExtraTest.php +++ b/tests/QueueExtraTest.php @@ -15,7 +15,9 @@ use Rsgrinko\Proton\Models\Setting; use Rsgrinko\Proton\Models\User; use Rsgrinko\Proton\Queue\Queue; use Rsgrinko\Proton\Queue\Scheduler; +use Rsgrinko\Proton\Queue\Worker; use Rsgrinko\Proton\Support\Env; +use Rsgrinko\Proton\Support\Profiler; use Rsgrinko\Proton\Webhooks\Incoming; test('очередь: важная задача разбирается раньше обычной', function (): void { @@ -248,3 +250,38 @@ test('входящие вебхуки: упавший обработчик не Incoming::reset(); }); }); + +test('очередь: воркер пишет время задачи и число запросов к базе', function (): void { + withOwnDatabase(static function (): void { + withConfig(['app.debug' => true], static function (): void { + Profiler::reset(); + + $id = Queue::push(QueueTestJob::class, ['mark' => 'профиль']); + + (new Worker())->run(true); + + $row = assertNotNull(Connection::instance()->selectOne( + 'SELECT * FROM jobs WHERE id = :id', + ['id' => $id] + )); + + assertSame(Queue::DONE, (string) $row['status']); + assertTrue((int) $row['duration_ms'] >= 0, 'время выполнения записано'); + assertTrue((int) $row['queries_count'] >= 1, 'задача пишет настройку — хотя бы один запрос был'); + assertTrue((float) $row['queries_ms'] >= 0); + }); + }); +}); + +test('очередь: у упавшей задачи время тоже посчитано', function (): void { + withOwnDatabase(static function (): void { + Queue::push(QueueFailingJob::class); + + (new Worker())->run(true); + + $row = assertNotNull(Connection::instance()->selectOne('SELECT * FROM jobs LIMIT 1')); + + assertSame(Queue::QUEUED, (string) $row['status'], 'после первой ошибки задача ждёт повтора'); + assertTrue((int) $row['duration_ms'] >= 0, 'время посчитано даже у упавшей задачи'); + }); +});