Отчёты, показатели работы и присмотр за порогами
This commit is contained in:
1 parent
c4e9f6fc37
commit
f66391261d
17 files changed
+1124
-6
No files matched your search
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Cache\Cache;
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Models\UserNotification;
|
||||
use Rsgrinko\Proton\Models\WebhookDelivery;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
|
||||
/**
|
||||
* Показатели работы: сколько запросов и с какой скоростью их обслужили,
|
||||
* что в очереди, как дела у вебхуков и базы.
|
||||
*
|
||||
* Счётчики запросов живут в кэше почасовыми ведёрками — своей таблицы под них
|
||||
* нет нарочно: показатели не данные, терять их не жалко, а лишняя запись
|
||||
* в базу на каждый запрос стоит дороже, чем стоят сами цифры.
|
||||
*
|
||||
* Снимок (`snapshot()`) считается из того, что и так лежит в базе, поэтому
|
||||
* не зависит от того, работал ли сбор.
|
||||
*/
|
||||
final class Metrics
|
||||
{
|
||||
/** Сколько часов держим ведёрки счётчиков */
|
||||
private const KEEP_HOURS = 25;
|
||||
|
||||
private const PREFIX = 'metrics:hour:';
|
||||
|
||||
/**
|
||||
* Записать обслуженный запрос. Зовётся ядром в конце обработки.
|
||||
*/
|
||||
public static function track(float $milliseconds, int $status): void
|
||||
{
|
||||
if (!(bool) Config::get('metrics.enabled', true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$key = self::key();
|
||||
$bucket = (array) (Cache::get($key) ?? ['requests' => 0, 'ms' => 0.0, 'errors' => 0, 'slow' => 0]);
|
||||
|
||||
$bucket['requests'] = (int) $bucket['requests'] + 1;
|
||||
$bucket['ms'] = (float) $bucket['ms'] + $milliseconds;
|
||||
|
||||
if ($status >= 500) {
|
||||
$bucket['errors'] = (int) $bucket['errors'] + 1;
|
||||
}
|
||||
|
||||
if ($milliseconds >= (float) Config::get('metrics.slow_ms', 1000)) {
|
||||
$bucket['slow'] = (int) $bucket['slow'] + 1;
|
||||
}
|
||||
|
||||
Cache::put($key, $bucket, self::KEEP_HOURS * 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* Счётчики запросов за последние часы: сколько, как быстро, сколько ошибок.
|
||||
*
|
||||
* @return array{requests: int, average_ms: float, errors: int, slow: int, hours: int}
|
||||
*/
|
||||
public static function requests(int $hours = 24): array
|
||||
{
|
||||
$requests = 0;
|
||||
$ms = 0.0;
|
||||
$errors = 0;
|
||||
$slow = 0;
|
||||
|
||||
for ($back = 0; $back < max(1, $hours); $back++) {
|
||||
$bucket = Cache::get(self::key(time() - $back * 3600));
|
||||
|
||||
if (!is_array($bucket)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$requests += (int) ($bucket['requests'] ?? 0);
|
||||
$ms += (float) ($bucket['ms'] ?? 0);
|
||||
$errors += (int) ($bucket['errors'] ?? 0);
|
||||
$slow += (int) ($bucket['slow'] ?? 0);
|
||||
}
|
||||
|
||||
return [
|
||||
'requests' => $requests,
|
||||
'average_ms' => $requests > 0 ? round($ms / $requests, 1) : 0.0,
|
||||
'errors' => $errors,
|
||||
'slow' => $slow,
|
||||
'hours' => max(1, $hours),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Снимок состояния приложения — им же отвечает `/api/v1/metrics`.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function snapshot(): array
|
||||
{
|
||||
$day = date('Y-m-d H:i:s', time() - 86400);
|
||||
|
||||
return [
|
||||
'time' => date('c'),
|
||||
'app' => [
|
||||
'name' => (string) Config::get('app.name', 'Proton'),
|
||||
'env' => (string) Config::get('app.env', 'production'),
|
||||
'php' => PHP_VERSION,
|
||||
'memory' => memory_get_peak_usage(true),
|
||||
],
|
||||
'users' => [
|
||||
'total' => User::query()->count(),
|
||||
'active' => User::query()->where('active', 1)->count(),
|
||||
'new_24h' => User::query()->where('created_at', '>=', $day)->count(),
|
||||
],
|
||||
'requests' => self::requests(24),
|
||||
'queue' => Queue::stats(),
|
||||
'webhooks' => Reports::breakdown(WebhookDelivery::query()->where('created_at', '>=', $day), 'status'),
|
||||
'audit' => [
|
||||
'logins_24h' => AuditEntry::query()
|
||||
->where('action', AuditEntry::LOGIN)
|
||||
->where('created_at', '>=', $day)
|
||||
->count(),
|
||||
'total_24h' => AuditEntry::query()->where('created_at', '>=', $day)->count(),
|
||||
],
|
||||
'notifications' => [
|
||||
'unread' => UserNotification::query()->whereNull('read_at')->count(),
|
||||
],
|
||||
'storage' => self::storage(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Место: размер базы, папки var и сколько свободно на диске.
|
||||
*
|
||||
* @return array<string, int|string>
|
||||
*/
|
||||
public static function storage(): array
|
||||
{
|
||||
$database = (string) Config::get('db.sqlite.path', APP_ROOT . '/var/app.sqlite');
|
||||
$free = @disk_free_space(APP_ROOT);
|
||||
|
||||
return [
|
||||
'database_bytes' => is_file($database) ? (int) filesize($database) : 0,
|
||||
'var_bytes' => self::size(APP_ROOT . '/var'),
|
||||
'free_bytes' => $free === false ? 0 : (int) $free,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Размер папки. Обходим без рекурсии по всему дереву глубоко: var/ и так
|
||||
* плоская, а считать миллион файлов на каждый запрос незачем.
|
||||
*/
|
||||
private static function size(string $path): int
|
||||
{
|
||||
if (!is_dir($path)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$total = 0;
|
||||
|
||||
foreach ((array) glob($path . '/*') as $item) {
|
||||
if (is_file((string) $item)) {
|
||||
$total += (int) filesize((string) $item);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ((array) glob($item . '/*') as $nested) {
|
||||
if (is_file((string) $nested)) {
|
||||
$total += (int) filesize((string) $nested);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
private static function key(?int $time = null): string
|
||||
{
|
||||
return self::PREFIX . date('Y-m-d-H', $time ?? time());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Notifications\HealthAlertNotification;
|
||||
use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Присмотр за приложением: сравнивает показатели с порогами и, когда что-то
|
||||
* вышло за край, шлёт уведомление тем, у кого право system.manage.
|
||||
*
|
||||
* Зовётся расписанием, то есть воркером. Про одну и ту же беду сообщается
|
||||
* не чаще, чем раз в `monitor.repeat_minutes`: сорвавшийся диск не должен
|
||||
* превращаться в сотню писем.
|
||||
*/
|
||||
final class Monitor
|
||||
{
|
||||
/** Отметки о последних сообщениях */
|
||||
private const MARK = 'monitor:alert:';
|
||||
|
||||
/**
|
||||
* Проверить пороги и, если надо, сообщить. Возвращает найденные проблемы —
|
||||
* их же показывает консольная самопроверка.
|
||||
*
|
||||
* @return array<string, string> ключ проблемы => что случилось
|
||||
*/
|
||||
public static function check(bool $notify = true): array
|
||||
{
|
||||
$problems = [];
|
||||
|
||||
$queue = Queue::stats();
|
||||
|
||||
$failed = (int) ($queue['failed'] ?? 0);
|
||||
$queued = (int) ($queue['queued'] ?? 0);
|
||||
|
||||
if ($failed >= (int) Config::get('monitor.failed_jobs', 10)) {
|
||||
$problems['queue.failed'] = 'Задач с ошибкой в очереди: ' . $failed;
|
||||
}
|
||||
|
||||
if ($queued >= (int) Config::get('monitor.queue_backlog', 500)) {
|
||||
$problems['queue.backlog'] = 'Очередь не разбирается, ждёт задач: ' . $queued;
|
||||
}
|
||||
|
||||
$requests = Metrics::requests(1);
|
||||
|
||||
if ($requests['errors'] >= (int) Config::get('monitor.errors', 20)) {
|
||||
$problems['http.errors'] = 'Ошибок 5xx за час: ' . $requests['errors'];
|
||||
}
|
||||
|
||||
$free = (int) (Metrics::storage()['free_bytes'] ?? 0);
|
||||
$limit = (int) Config::get('monitor.free_bytes', 500 * 1024 * 1024);
|
||||
|
||||
if ($free > 0 && $free < $limit) {
|
||||
$problems['disk.free'] = 'На диске осталось ' . Str::bytes($free);
|
||||
}
|
||||
|
||||
if ($notify) {
|
||||
foreach ($problems as $key => $message) {
|
||||
self::announce($key, $message);
|
||||
}
|
||||
}
|
||||
|
||||
return $problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщить о проблеме, если о ней давно не говорили.
|
||||
*/
|
||||
private static function announce(string $key, string $message): void
|
||||
{
|
||||
$repeat = max(1, (int) Config::get('monitor.repeat_minutes', 60)) * 60;
|
||||
$last = (int) Setting::get(self::MARK . $key, '0');
|
||||
|
||||
if (time() - $last < $repeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
Setting::set(self::MARK . $key, (string) time());
|
||||
|
||||
try {
|
||||
Notify::toPermission(Permission::SYSTEM_MANAGE, new HealthAlertNotification($key, $message));
|
||||
} catch (Throwable $e) {
|
||||
(new Logger('monitor'))->error('Не удалось разослать предупреждение', [
|
||||
'problem' => $key,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
|
||||
/**
|
||||
* Сводки для отчётов: сколько записей по дням и как они делятся по колонке.
|
||||
* Считает база — в память поднимается готовый ряд, а не таблица.
|
||||
*
|
||||
* Reports::series(User::query(), 'created_at', '2026-09-01', '2026-09-15');
|
||||
* // ['2026-09-01' => 3, '2026-09-02' => 0, …] — дни без записей тоже в ряду
|
||||
*
|
||||
* Дни без записей возвращаются нулями: иначе график врёт, а в выгрузке
|
||||
* пропадают пустые сутки.
|
||||
*/
|
||||
final class Reports
|
||||
{
|
||||
public const DAY = 'day';
|
||||
public const WEEK = 'week';
|
||||
public const MONTH = 'month';
|
||||
|
||||
/**
|
||||
* Ряд «период => сколько» по колонке времени.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function series(Builder $query, string $column, string $from, string $to, string $step = self::DAY): array
|
||||
{
|
||||
$expression = self::period($query, $column, $step);
|
||||
|
||||
// Группируем по алиасу, а не по выражению: имена колонок построитель
|
||||
// проверяет, и strftime() он справедливо не пропустит
|
||||
$rows = self::rows(
|
||||
(clone $query)
|
||||
->select($expression . ' AS period', 'COUNT(*) AS total')
|
||||
->where($column, '>=', $from . ' 00:00:00')
|
||||
->where($column, '<=', $to . ' 23:59:59')
|
||||
->groupBy('period')
|
||||
->orderBy('period')
|
||||
);
|
||||
|
||||
$counted = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$counted[(string) ($row['period'] ?? '')] = (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
$series = [];
|
||||
|
||||
foreach (self::steps($from, $to, $step) as $key) {
|
||||
$series[$key] = $counted[$key] ?? 0;
|
||||
}
|
||||
|
||||
return $series;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ряд «значение колонки => сколько», от большего к меньшему.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function breakdown(Builder $query, string $column, int $limit = 10): array
|
||||
{
|
||||
$rows = self::rows(
|
||||
(clone $query)
|
||||
->select($column, 'COUNT(*) AS total')
|
||||
->groupBy($column)
|
||||
->orderBy('total', 'desc')
|
||||
->limit($limit)
|
||||
);
|
||||
|
||||
$out = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$key = (string) ($row[$column] ?? '');
|
||||
|
||||
$out[$key === '' ? '—' : $key] = (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Строки как есть: у построителя моделей для этого свой метод, иначе
|
||||
* агрегат приехал бы моделью без нужных колонок.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private static function rows(Builder $query): array
|
||||
{
|
||||
return method_exists($query, 'rows') ? $query->rows() : $query->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Сумма ряда — подпись под сводкой.
|
||||
*
|
||||
* @param array<string, int> $series
|
||||
*/
|
||||
public static function total(array $series): int
|
||||
{
|
||||
return array_sum($series);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выражение группировки по периоду. Диалекты разные, ряд одинаковый.
|
||||
*/
|
||||
private static function period(Builder $query, string $column, string $step): string
|
||||
{
|
||||
$sqlite = $query->connection()->isSqlite();
|
||||
|
||||
return match ($step) {
|
||||
self::MONTH => $sqlite ? "strftime('%Y-%m', " . $column . ')' : "DATE_FORMAT(" . $column . ", '%Y-%m')",
|
||||
// Неделю обозначаем датой понедельника: номера недель у SQLite, MySQL
|
||||
// и PHP считаются по-разному и на стыке годов разъезжаются
|
||||
self::WEEK => $sqlite
|
||||
? "date(" . $column . ", 'weekday 0', '-6 days')"
|
||||
: "DATE(DATE_SUB(" . $column . ", INTERVAL WEEKDAY(" . $column . ") DAY))",
|
||||
default => $sqlite ? "strftime('%Y-%m-%d', " . $column . ')' : "DATE_FORMAT(" . $column . ", '%Y-%m-%d')",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Все периоды между датами — чтобы в ряду не было дырок.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function steps(string $from, string $to, string $step): array
|
||||
{
|
||||
$start = strtotime($from);
|
||||
$end = strtotime($to);
|
||||
|
||||
if ($start === false || $end === false || $start > $end) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
$current = $start;
|
||||
|
||||
while ($current <= $end) {
|
||||
$keys[] = match ($step) {
|
||||
self::MONTH => date('Y-m', $current),
|
||||
self::WEEK => date('Y-m-d', (int) strtotime('monday this week', $current)),
|
||||
default => date('Y-m-d', $current),
|
||||
};
|
||||
|
||||
$current = strtotime(match ($step) {
|
||||
self::MONTH => '+1 month',
|
||||
self::WEEK => '+1 week',
|
||||
default => '+1 day',
|
||||
}, $current);
|
||||
}
|
||||
|
||||
return array_values(array_unique($keys));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user