Профиль задач в очереди: время и число запросов

This commit is contained in:
rsgrinko committed 2026-09-16 10:45:23 +03:00
1 parent 31d63fee8d
commit 883943b24f
7 files changed
+149 -13

No files matched your search

+1 -1
View File
@@ -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'));
+7
View File
@@ -68,6 +68,13 @@ php bin/proton worker:restart # доработает круг и вый
доставок вебхуков, прочитанные уведомления и логи.
Приложению об этом заботиться не нужно.
У каждой выполненной или упавшей задачи в панели («Очередь») видно, сколько она
заняла и сколько раз сходила в базу — колонки «Время» и «SQL». Число запросов
считается, только если включён `APP_DEBUG`: полные тексты запросов не хранятся
(на очереди рассылок это были бы гигабайты), только счётчик и сумма времени —
задача, которая вдруг стала делать втрое больше запросов, чем обычно, видна
сразу. Время выполнения пишется всегда, без отладки.
### Разбор полётов
```bash
+31 -7
View File
@@ -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<string, mixed> $row
* @param array<string, mixed> $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<string, mixed>
*/
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,
];
}
/**
* Повторить неудавшуюся задачу.
*/
+31 -5
View File
@@ -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.
*/
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Migrations;
use Rsgrinko\Proton\Database\Migration;
use Rsgrinko\Proton\Database\Schema\Blueprint;
/**
* Профиль выполнения задачи: сколько времени заняла и сколько сходила в базу.
*
* Полные тексты запросов не хранятся — это были бы гигабайты на молчащей
* очереди рассылок. Только счётчик и сумма: этого хватает, чтобы увидеть
* задачу, которая внезапно стала делать втрое больше запросов, чем обычно.
*/
final class AddJobProfile extends Migration
{
public function up(): void
{
$this->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');
});
}
}
+6
View File
@@ -104,6 +104,8 @@ $badges = [
<th><?= View::partial('sort', ['filters' => $filters, 'route' => 'admin.queue', 'column' => 'priority', 'label' => 'Важность']) ?></th>
<th>Состояние</th>
<th class="hide-sm">Попытки</th>
<th class="hide-sm"><?= View::partial('sort', ['filters' => $filters, 'route' => 'admin.queue', 'column' => 'duration_ms', 'label' => 'Время']) ?></th>
<th class="hide-sm">SQL</th>
<th class="hide-sm"><?= View::partial('sort', ['filters' => $filters, 'route' => 'admin.queue', 'column' => 'created_at', 'label' => 'Создана']) ?></th>
</tr>
@@ -122,6 +124,10 @@ $badges = [
<td class="small"><?= (int) ($job['priority'] ?? 0) ?></td>
<td><span class="badge <?= View::e($badges[$status] ?? 'muted') ?>"><?= View::e($statuses[$status] ?? $status) ?></span></td>
<td class="hide-sm small"><?= (int) $job['attempts'] ?> из <?= (int) $job['max_attempts'] ?></td>
<td class="hide-sm small"><?= $job['duration_ms'] !== null ? (int) $job['duration_ms'] . ' мс' : '—' ?></td>
<td class="hide-sm small"><?= $job['queries_count'] !== null
? (int) $job['queries_count'] . ' / ' . number_format((float) $job['queries_ms'], 1, ',', ' ') . ' мс'
: '—' ?></td>
<td class="hide-sm muted small"><?= View::e(View::ago((string) $job['created_at'])) ?></td>
</tr>
<?php } ?>
+37
View File
@@ -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, 'время посчитано даже у упавшей задачи');
});
});