Профиль задач в очереди: время и число запросов
This commit is contained in:
1 parent
31d63fee8d
commit
883943b24f
7 files changed
+149
-13
No files matched your search
@@ -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,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Повторить неудавшуюся задачу.
|
||||
*/
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user