Отчёты, показатели работы и присмотр за порогами
This commit is contained in:
1 parent
c4e9f6fc37
commit
f66391261d
17 files changed
+1124
-6
No files matched your search
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Admin;
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Models\WebhookDelivery;
|
||||
use Rsgrinko\Proton\Support\Csv;
|
||||
use Rsgrinko\Proton\Support\Export;
|
||||
use Rsgrinko\Proton\Support\Reports;
|
||||
|
||||
/**
|
||||
* Отчёты: что происходило за период. Считает база, страница только рисует.
|
||||
*
|
||||
* Свой отчёт добавляется одним элементом в reports(): запрос, колонка времени
|
||||
* и подпись — остальное общее, включая выгрузку.
|
||||
*/
|
||||
final class ReportsController extends Controller
|
||||
{
|
||||
/** Периоды, за которые показываем отчёты */
|
||||
private const RANGES = [
|
||||
'7' => 'неделя',
|
||||
'30' => 'месяц',
|
||||
'90' => 'три месяца',
|
||||
'365' => 'год',
|
||||
];
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
[$from, $to, $days, $step] = $this->period($request);
|
||||
|
||||
$reports = [];
|
||||
|
||||
foreach ($this->sources() as $key => $source) {
|
||||
$series = Reports::series($source['query'](), $source['column'], $from, $to, $step);
|
||||
|
||||
$reports[$key] = [
|
||||
'label' => $source['label'],
|
||||
'series' => $series,
|
||||
'total' => Reports::total($series),
|
||||
'max' => max([1, ...array_values($series)]),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->view('admin/reports', [
|
||||
'active' => 'reports',
|
||||
'reports' => $reports,
|
||||
'actions' => Reports::breakdown(AuditEntry::query(), 'action'),
|
||||
'hooks' => Reports::breakdown(WebhookDelivery::query(), 'status'),
|
||||
'ranges' => self::RANGES,
|
||||
'days' => $days,
|
||||
'step' => $step,
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
], 'Отчёты');
|
||||
}
|
||||
|
||||
/**
|
||||
* Выгрузка одного отчёта рядом: период, значение.
|
||||
*/
|
||||
public function export(Request $request): Response
|
||||
{
|
||||
[$from, $to, , $step] = $this->period($request);
|
||||
|
||||
$sources = $this->sources();
|
||||
$key = (string) $request->query('report', '');
|
||||
|
||||
if (!isset($sources[$key])) {
|
||||
$this->flash('Неизвестный отчёт', 'error');
|
||||
|
||||
return $this->redirect('admin.reports');
|
||||
}
|
||||
|
||||
$series = Reports::series($sources[$key]['query'](), $sources[$key]['column'], $from, $to, $step);
|
||||
$rows = [];
|
||||
|
||||
foreach ($series as $period => $count) {
|
||||
$rows[] = [$period, $count];
|
||||
}
|
||||
|
||||
return Response::download(
|
||||
Csv::write($rows, ['Период', $sources[$key]['label']]),
|
||||
Export::fileName('report-' . $key),
|
||||
'text/csv; charset=utf-8'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отчёты приложения: запрос и колонка времени.
|
||||
*
|
||||
* @return array<string, array{label: string, column: string, query: callable}>
|
||||
*/
|
||||
private function sources(): array
|
||||
{
|
||||
return [
|
||||
'users' => [
|
||||
'label' => 'Регистрации',
|
||||
'column' => 'created_at',
|
||||
'query' => static fn () => User::query(),
|
||||
],
|
||||
'logins' => [
|
||||
'label' => 'Входы',
|
||||
'column' => 'created_at',
|
||||
'query' => static fn () => AuditEntry::query()->where('action', AuditEntry::LOGIN),
|
||||
],
|
||||
'notes' => [
|
||||
'label' => 'Заметки',
|
||||
'column' => 'created_at',
|
||||
'query' => static fn () => Note::query(),
|
||||
],
|
||||
'webhooks' => [
|
||||
'label' => 'Посылки вебхуков',
|
||||
'column' => 'created_at',
|
||||
'query' => static fn () => WebhookDelivery::query(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Период отчёта: сколько дней назад смотрим и с каким шагом.
|
||||
*
|
||||
* @return array{0: string, 1: string, 2: int, 3: string}
|
||||
*/
|
||||
private function period(Request $request): array
|
||||
{
|
||||
$days = (int) $request->query('days', 30);
|
||||
|
||||
if (!isset(self::RANGES[(string) $days])) {
|
||||
$days = 30;
|
||||
}
|
||||
|
||||
// На длинном периоде дневной ряд нечитаем — переходим на недели и месяцы
|
||||
$step = match (true) {
|
||||
$days > 180 => Reports::MONTH,
|
||||
$days > 60 => Reports::WEEK,
|
||||
default => Reports::DAY,
|
||||
};
|
||||
|
||||
return [date('Y-m-d', time() - ($days - 1) * 86400), date('Y-m-d'), $days, $step];
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use Rsgrinko\Proton\Queue\Scheduler;
|
||||
use Rsgrinko\Proton\Queue\Worker;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Diagnostics;
|
||||
use Rsgrinko\Proton\Support\Metrics;
|
||||
|
||||
/**
|
||||
* Состояние: самопроверка, очередь, расписание и кнопки обслуживания.
|
||||
@@ -33,6 +34,8 @@ final class SystemController extends Controller
|
||||
'active' => 'system',
|
||||
'checks' => $checks,
|
||||
'health' => Diagnostics::worst($checks),
|
||||
'metrics' => Metrics::requests(24),
|
||||
'storage' => Metrics::storage(),
|
||||
'queue' => Queue::stats(),
|
||||
'schedule' => Scheduler::tasks(),
|
||||
'events' => Events::registered(),
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
@@ -11,6 +12,7 @@ use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Metrics;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -39,6 +41,19 @@ final class SystemController extends ApiController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Показатели работы для мониторинга. В отличие от /health, здесь цифры
|
||||
* о внутренностях, поэтому нужен ключ и право system.view.
|
||||
*/
|
||||
public function metrics(Viewer $viewer): Response
|
||||
{
|
||||
if (!$viewer->can(Permission::SYSTEM_VIEW)) {
|
||||
return Response::error('Нет доступа к показателям', 403);
|
||||
}
|
||||
|
||||
return $this->data(Metrics::snapshot());
|
||||
}
|
||||
|
||||
/**
|
||||
* Здоровье сервиса — его дёргает мониторинг, поэтому ключ здесь не нужен.
|
||||
* Наружу отдаём только то, что не жалко: живость базы и размер очереди.
|
||||
|
||||
@@ -23,6 +23,7 @@ return [
|
||||
['key' => 'webhooks', 'label' => 'Вебхуки', 'route' => 'admin.webhooks', 'permission' => Permission::WEBHOOKS_MANAGE],
|
||||
['key' => 'settings', 'label' => 'Настройки', 'route' => 'admin.settings', 'permission' => Permission::SETTINGS_MANAGE],
|
||||
['key' => 'backups', 'label' => 'Копии', 'route' => 'admin.backups', 'permission' => Permission::SYSTEM_MANAGE],
|
||||
['key' => 'reports', 'label' => 'Отчёты', 'route' => 'admin.reports', 'permission' => Permission::SYSTEM_VIEW],
|
||||
['key' => 'audit', 'label' => 'Журнал', 'route' => 'admin.audit', 'permission' => Permission::AUDIT_VIEW],
|
||||
['key' => 'logs', 'label' => 'Логи', 'route' => 'admin.logs', 'permission' => Permission::LOGS_VIEW],
|
||||
['key' => 'system', 'label' => 'Состояние', 'route' => 'admin.system', 'permission' => Permission::SYSTEM_VIEW],
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Отчёты, показатели и присмотр
|
||||
|
||||
Три разные вещи, которые легко перепутать: **отчёты** — что происходило за период,
|
||||
**показатели** — как сейчас работает приложение, **присмотр** — кто сообщит, когда
|
||||
показатели уехали.
|
||||
|
||||
## Отчёты
|
||||
|
||||
Раздел **Отчёты** (право `system.view`) показывает ряды по периодам: регистрации,
|
||||
входы, заметки, посылки вебхуков. Считает база, страница рисует столбики и отдаёт
|
||||
тот же ряд файлом.
|
||||
|
||||
Свой отчёт — строка в `ReportsController::sources()`: запрос, колонка времени
|
||||
и подпись. Выгрузка, периоды и график общие.
|
||||
|
||||
```php
|
||||
'orders' => [
|
||||
'label' => 'Заказы',
|
||||
'column' => 'created_at',
|
||||
'query' => static fn () => Order::query()->where('paid', 1),
|
||||
],
|
||||
```
|
||||
|
||||
Ряд можно взять и напрямую:
|
||||
|
||||
```php
|
||||
Reports::series(Order::query(), 'created_at', '2026-09-01', '2026-09-30'); // по дням
|
||||
Reports::series(Order::query(), 'created_at', $from, $to, Reports::WEEK); // по неделям
|
||||
Reports::breakdown(Order::query(), 'status'); // разбивка
|
||||
```
|
||||
|
||||
Периоды без записей приходят нулями — иначе график врёт, а в выгрузке пропадают
|
||||
пустые сутки. Неделя обозначается датой понедельника: номера недель у SQLite,
|
||||
MySQL и PHP считаются по-разному и на стыке годов разъезжаются.
|
||||
|
||||
## Показатели
|
||||
|
||||
`Support\Metrics` считает две разные вещи.
|
||||
|
||||
Счётчики запросов ведёт ядро: время ответа, коды 5xx, медленные ответы
|
||||
(`METRICS_SLOW_MS`). Живут они в кэше почасовыми ведёрками, 25 часов. Своей
|
||||
таблицы под них нет нарочно — запись в базу на каждый запрос стоит дороже, чем
|
||||
стоят сами цифры. Очистка кэша их обнуляет, и это нормально.
|
||||
|
||||
```php
|
||||
Metrics::requests(24); // ['requests' => …, 'average_ms' => …, 'errors' => …, 'slow' => …]
|
||||
```
|
||||
|
||||
Снимок состояния считается из базы и не зависит от того, работал ли сбор:
|
||||
|
||||
```php
|
||||
Metrics::snapshot(); // пользователи, очередь, вебхуки, журнал, место на диске
|
||||
```
|
||||
|
||||
Снимком отвечает `GET /api/v1/metrics` — ключ API плюс право `system.view`
|
||||
у владельца ключа. Для внешнего мониторинга этого хватает; `/health` остаётся
|
||||
без ключа, там только живость.
|
||||
|
||||
Сбор выключается `METRICS_ENABLED=false`.
|
||||
|
||||
## Присмотр
|
||||
|
||||
`Support\Monitor` сравнивает показатели с порогами и уведомляет тех, у кого право
|
||||
`system.manage` (лента плюс письмо). Зовёт его расписание, то есть воркер, раз
|
||||
в `MONITOR_INTERVAL` секунд.
|
||||
|
||||
Пороги:
|
||||
|
||||
| Настройка | Что значит | По умолчанию |
|
||||
|---|---|---|
|
||||
| `MONITOR_FAILED_JOBS` | задач с ошибкой в очереди | 10 |
|
||||
| `MONITOR_QUEUE_BACKLOG` | задач ждёт разбора | 500 |
|
||||
| `MONITOR_ERRORS` | ошибок 5xx за час | 20 |
|
||||
| `MONITOR_FREE_BYTES` | осталось места на диске | 500 МБ |
|
||||
|
||||
Про одну и ту же беду сообщается не чаще раза в `MONITOR_REPEAT_MINUTES` (60):
|
||||
кончающийся диск не должен превращаться в сотню писем. Отметки лежат в `settings`
|
||||
под ключами `monitor:alert:*` — сбросив такую, получите сообщение сразу.
|
||||
|
||||
Порог, о котором не хочется знать, отключается большим числом; весь присмотр —
|
||||
`MONITOR_ENABLED=false`. Проверить, что видит присмотр прямо сейчас, можно и
|
||||
без уведомлений: `Monitor::check(false)` возвращает найденные проблемы.
|
||||
@@ -16,6 +16,7 @@ use Rsgrinko\Proton\Http\Middleware\Throttle;
|
||||
use Rsgrinko\Proton\Http\Middleware\VerifyCsrf;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\Metrics;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
use Rsgrinko\Proton\Support\RequestId;
|
||||
use Rsgrinko\Proton\Support\Settings;
|
||||
@@ -43,6 +44,8 @@ final class Kernel
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
$started = microtime(true);
|
||||
|
||||
// Сквозная цепочка: клиент прислал свою или заводим новую
|
||||
RequestId::set($request->header(RequestId::HEADER));
|
||||
|
||||
@@ -50,14 +53,24 @@ final class Kernel
|
||||
Settings::apply();
|
||||
|
||||
try {
|
||||
return $this->finish($this->router()->dispatch($request));
|
||||
$response = $this->finish($this->router()->dispatch($request));
|
||||
} catch (RecordNotFound $e) {
|
||||
return $this->finish($this->notFound($request, $e));
|
||||
$response = $this->finish($this->notFound($request, $e));
|
||||
} catch (ValidationException $e) {
|
||||
return $this->finish($this->invalid($request, $e));
|
||||
$response = $this->finish($this->invalid($request, $e));
|
||||
} catch (Throwable $e) {
|
||||
return $this->finish($this->crashed($request, $e));
|
||||
$response = $this->finish($this->crashed($request, $e));
|
||||
}
|
||||
|
||||
// Счётчики пишутся после ответа и молча: сорванный подсчёт не повод
|
||||
// портить страницу
|
||||
try {
|
||||
Metrics::track((microtime(true) - $started) * 1000, $response->status());
|
||||
} catch (Throwable $e) {
|
||||
$this->logger->warning('Не удалось записать показатели', ['error' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Notifications;
|
||||
|
||||
use Rsgrinko\Proton\Http\Router;
|
||||
|
||||
/**
|
||||
* Показатель вышел за порог: очередь встала, посыпались ошибки, кончается диск.
|
||||
*
|
||||
* Уходит тем, кто отвечает за обслуживание (право system.manage), и письмом:
|
||||
* такое замечают не глядя в панель, а когда уже поздно.
|
||||
*/
|
||||
final class HealthAlertNotification extends Notification
|
||||
{
|
||||
public function __construct(private string $problem, private string $message)
|
||||
{
|
||||
}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'health.' . $this->problem;
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return 'Приложение просит внимания';
|
||||
}
|
||||
|
||||
public function body(): string
|
||||
{
|
||||
return $this->message . '. Подробности — на странице «Состояние»; пороги задаются'
|
||||
. ' настройками MONITOR_* в .env.';
|
||||
}
|
||||
|
||||
public function url(): string
|
||||
{
|
||||
return Router::absolute('admin.system');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function channels(): array
|
||||
{
|
||||
return [Notify::DATABASE, Notify::MAIL];
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use Rsgrinko\Proton\Backup\BackupJob;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\Monitor;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -174,5 +175,16 @@ final class Scheduler
|
||||
Queue::push(BackupJob::class);
|
||||
});
|
||||
}
|
||||
|
||||
// Присмотр за порогами: о беде лучше узнать от приложения, чем от людей
|
||||
if ((bool) Config::get('monitor.enabled', true)) {
|
||||
self::every(
|
||||
max(60, (int) Config::get('monitor.interval', 300)),
|
||||
'monitor:check',
|
||||
static function (): void {
|
||||
Monitor::check();
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Отчёты за период.
|
||||
*
|
||||
* @var array<string, array{label: string, series: array<string, int>, total: int, max: int}> $reports
|
||||
* @var array<string, int> $actions действия в журнале
|
||||
* @var array<string, int> $hooks посылки вебхуков по состояниям
|
||||
* @var array<string, string> $ranges периоды
|
||||
* @var int $days выбранный период
|
||||
* @var string $step шаг ряда
|
||||
* @var string $from
|
||||
* @var string $to
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$stepLabel = match ($step) {
|
||||
'month' => 'по месяцам',
|
||||
'week' => 'по неделям',
|
||||
default => 'по дням',
|
||||
};
|
||||
?>
|
||||
<h1>Отчёты</h1>
|
||||
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<?php foreach ($ranges as $value => $label) { ?>
|
||||
<?php if ((int) $value === $days) { ?>
|
||||
<span class="badge info"><?= View::e($label) ?></span>
|
||||
<?php } else { ?>
|
||||
<a class="btn small" href="<?= View::e(View::route('admin.reports', ['days' => $value])) ?>"><?= View::e($label) ?></a>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
|
||||
<span class="spacer"></span>
|
||||
<span class="muted small"><?= View::e($from) ?> — <?= View::e($to) ?>, <?= View::e($stepLabel) ?></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php foreach ($reports as $key => $report) { ?>
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<h2 style="margin: 0;"><?= View::e($report['label']) ?></h2>
|
||||
<span class="spacer"></span>
|
||||
<span class="muted small">всего: <?= (int) $report['total'] ?></span>
|
||||
<a class="btn small" href="<?= View::e(View::route('admin.reports.export', ['report' => $key, 'days' => $days])) ?>">CSV</a>
|
||||
</div>
|
||||
|
||||
<?php if ($report['total'] === 0) { ?>
|
||||
<p class="muted small">За период пусто.</p>
|
||||
<?php } else { ?>
|
||||
<div class="chart">
|
||||
<?php foreach ($report['series'] as $period => $count) { ?>
|
||||
<div class="col<?= $count === 0 ? ' empty' : '' ?>"
|
||||
style="height: <?= max(2, (int) round($count / $report['max'] * 100)) ?>%;"
|
||||
title="<?= View::e($period) ?>: <?= (int) $count ?>"></div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<div class="chart-legend muted small">
|
||||
<span><?= View::e((string) array_key_first($report['series'])) ?></span>
|
||||
<span>максимум за период: <?= (int) $report['max'] ?></span>
|
||||
<span><?= View::e((string) array_key_last($report['series'])) ?></span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="card">
|
||||
<h2>Действия в журнале</h2>
|
||||
|
||||
<?php if ($actions === []) { ?>
|
||||
<p class="muted small">Журнал пуст.</p>
|
||||
<?php } else { ?>
|
||||
<table class="list">
|
||||
<?php foreach ($actions as $action => $count) { ?>
|
||||
<tr>
|
||||
<td><?= View::e(AuditEntry::label((string) $action)) ?></td>
|
||||
<td class="right"><?= (int) $count ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Посылки вебхуков по состояниям</h2>
|
||||
|
||||
<?php if ($hooks === []) { ?>
|
||||
<p class="muted small">Посылок не было.</p>
|
||||
<?php } else { ?>
|
||||
<table class="list">
|
||||
<?php foreach ($hooks as $status => $count) { ?>
|
||||
<tr>
|
||||
<td><?= View::e((string) $status) ?></td>
|
||||
<td class="right"><?= (int) $count ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
<?php } ?>
|
||||
</div>
|
||||
@@ -7,6 +7,8 @@ declare(strict_types=1);
|
||||
*
|
||||
* @var array<int, array{level: string, title: string, value: string, hint: string}> $checks
|
||||
* @var string $health
|
||||
* @var array{requests: int, average_ms: float, errors: int, slow: int, hours: int} $metrics
|
||||
* @var array<string, int|string> $storage
|
||||
* @var array<string, int> $queue
|
||||
* @var array<int, array{name: string, interval: int, at: string, last: string}> $schedule
|
||||
* @var array<string, int> $events
|
||||
@@ -15,6 +17,7 @@ declare(strict_types=1);
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Support\Diagnostics;
|
||||
use Rsgrinko\Proton\Support\Str;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$badges = [Diagnostics::OK => 'ok', Diagnostics::WARN => 'warn', Diagnostics::ERROR => 'error'];
|
||||
@@ -40,6 +43,38 @@ $labels = [Diagnostics::OK => 'в порядке', Diagnostics::WARN => 'вни
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Показатели за <?= (int) $metrics['hours'] ?> ч</h2>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<tr>
|
||||
<td>Запросов</td>
|
||||
<td class="right"><?= (int) $metrics['requests'] ?></td>
|
||||
<td>Среднее время ответа</td>
|
||||
<td class="right"><?= View::e((string) $metrics['average_ms']) ?> мс</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Ошибок 5xx</td>
|
||||
<td class="right"><?= (int) $metrics['errors'] ?></td>
|
||||
<td>Медленных ответов</td>
|
||||
<td class="right"><?= (int) $metrics['slow'] ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>База</td>
|
||||
<td class="right"><?= View::e(Str::bytes((int) $storage['database_bytes'])) ?></td>
|
||||
<td>Каталог var</td>
|
||||
<td class="right"><?= View::e(Str::bytes((int) $storage['var_bytes'])) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Свободно на диске</td>
|
||||
<td class="right"><?= View::e(Str::bytes((int) $storage['free_bytes'])) ?></td>
|
||||
<td colspan="2" class="muted small">Счётчики запросов живут в кэше: очистка кэша их обнуляет</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-2">
|
||||
<div class="card">
|
||||
<h2>Очередь задач</h2>
|
||||
|
||||
@@ -20,6 +20,7 @@ return static function (Router $router): void {
|
||||
|
||||
$router->group(['middleware' => ['api', 'throttle:120,60']], function (Router $router): void {
|
||||
$router->get('/me', [SystemController::class, 'me'])->name('api.me');
|
||||
$router->get('/metrics', [SystemController::class, 'metrics'])->name('api.metrics');
|
||||
|
||||
$router->get('/notes', [NotesController::class, 'index'])->name('api.notes.index');
|
||||
$router->post('/notes', [NotesController::class, 'store'])->name('api.notes.store');
|
||||
|
||||
+76
-2
@@ -174,7 +174,7 @@ test('http: все страницы администратора отвечаю
|
||||
'/admin/roles', '/admin/roles/new', '/admin/roles/' . (Role::admin()?->id() ?? 1),
|
||||
'/admin/tokens', '/admin/audit', '/admin/logs', '/admin/system',
|
||||
'/admin/webhooks', '/admin/webhooks/new', '/admin/webhooks/' . httpWebhook()->id(),
|
||||
'/admin/settings', '/admin/backups',
|
||||
'/admin/settings', '/admin/backups', '/admin/reports',
|
||||
];
|
||||
|
||||
foreach ($paths as $path) {
|
||||
@@ -186,7 +186,7 @@ test('http: обычный пользователь не попадает в с
|
||||
$closed = [
|
||||
'/admin', '/admin/users', '/admin/roles', '/admin/tokens',
|
||||
'/admin/audit', '/admin/logs', '/admin/system', '/admin/webhooks', '/admin/settings',
|
||||
'/admin/backups',
|
||||
'/admin/backups', '/admin/reports',
|
||||
];
|
||||
|
||||
foreach ($closed as $path) {
|
||||
@@ -358,6 +358,63 @@ test('http: подписка на события заводится и пров
|
||||
assertSame(0, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'журнал ушёл вместе с подпиской');
|
||||
});
|
||||
|
||||
test('http: список фильтруется и сортируется параметрами адреса', function (): void {
|
||||
$admin = httpAdmin();
|
||||
$user = httpUser();
|
||||
|
||||
// Поиск по логину: чужой строки в ответе быть не должно
|
||||
$response = httpRequest('GET', '/admin/users', $admin, [], ['q' => (string) $admin->login]);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertContains((string) $admin->login, $response->body());
|
||||
assertNotContains((string) $user->login, $response->body());
|
||||
|
||||
// Отбор по роли и по признаку «активен» работает вместе с поиском
|
||||
$response = httpRequest('GET', '/admin/users', $admin, [], [
|
||||
'q' => (string) $admin->login,
|
||||
'role_id' => (string) $user->raw('role_id'),
|
||||
]);
|
||||
|
||||
// Логин админа остался в поле поиска, поэтому смотрим на ссылку карточки
|
||||
assertNotContains('/admin/users/' . $admin->id() . '"', $response->body());
|
||||
|
||||
// Сортировка по чужой колонке ничего не роняет — её просто нет в белом списке
|
||||
$response = httpRequest('GET', '/admin/users', $admin, [], ['sort' => 'password_hash', 'dir' => 'asc']);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertNotContains('password_hash', $response->body());
|
||||
|
||||
$response = httpRequest('GET', '/admin/users', $admin, [], ['sort' => 'login', 'dir' => 'asc']);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertContains('sort=login', $response->body(), 'ссылки страниц тащат сортировку за собой');
|
||||
});
|
||||
|
||||
test('http: список выгружается файлом с учётом фильтров', function (): void {
|
||||
$admin = httpAdmin();
|
||||
|
||||
$response = httpRequest('GET', '/admin/users/export', $admin, [], ['q' => (string) $admin->login]);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertContains('attachment', $response->header('Content-Disposition'));
|
||||
assertContains('users-', $response->header('Content-Disposition'));
|
||||
assertContains((string) $admin->login, $response->body());
|
||||
assertNotContains((string) httpUser()->login, $response->body(), 'фильтр действует и в файле');
|
||||
|
||||
// Выгрузка уносит данные наружу, поэтому попадает в журнал
|
||||
$entry = Rsgrinko\Proton\Models\AuditEntry::query()
|
||||
->where('entity', 'user')
|
||||
->orderBy('id', 'desc')
|
||||
->first();
|
||||
|
||||
assertContains('выгружен список', (string) assertNotNull($entry)->raw('description'));
|
||||
|
||||
// Предел строк — не совет: за ним выгрузка отказывается и возвращает в список
|
||||
withConfig(['export.max_rows' => 1], static function () use ($admin): void {
|
||||
assertStatus(302, httpRequest('GET', '/admin/users/export', $admin));
|
||||
});
|
||||
});
|
||||
|
||||
test('http: пользователь удаляется из панели, а себя удалить нельзя', function (): void {
|
||||
$victim = User::register('http_victim_' . bin2hex(random_bytes(3)), 'секрет123', [
|
||||
'email' => 'victim' . bin2hex(random_bytes(3)) . '@example.com',
|
||||
@@ -425,6 +482,23 @@ test('api: заметки создаются, читаются и удаляют
|
||||
assertStatus(404, httpRequest('GET', '/api/v1/notes/' . $id, null, [], [], $headers));
|
||||
});
|
||||
|
||||
test('api: показатели отдаются по ключу и только с правом', function (): void {
|
||||
$issued = ApiToken::issue('для мониторинга', httpAdmin()->id());
|
||||
|
||||
$response = httpRequest('GET', '/api/v1/metrics', null, [], [], ['authorization' => 'Bearer ' . $issued['key']]);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertContains('"requests"', $response->body());
|
||||
assertContains('"queue"', $response->body());
|
||||
|
||||
// Ключ обычного пользователя показатели не получает
|
||||
$limited = ApiToken::issue('без права', httpUser()->id());
|
||||
|
||||
assertStatus(403, httpRequest('GET', '/api/v1/metrics', null, [], [], [
|
||||
'authorization' => 'Bearer ' . $limited['key'],
|
||||
]));
|
||||
});
|
||||
|
||||
test('api: здоровье отвечает без ключа', function (): void {
|
||||
$response = httpRequest('GET', '/api/v1/health');
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Показатели работы и присмотр за порогами.
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Cache\Cache;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Support\Metrics;
|
||||
use Rsgrinko\Proton\Support\Monitor;
|
||||
|
||||
test('показатели: запросы складываются, ошибки и медленные считаются отдельно', function (): void {
|
||||
Cache::flush();
|
||||
|
||||
withConfig(['metrics.slow_ms' => 100], static function (): void {
|
||||
Metrics::track(10, 200);
|
||||
Metrics::track(30, 200);
|
||||
Metrics::track(500, 500);
|
||||
|
||||
$stats = Metrics::requests(1);
|
||||
|
||||
assertSame(3, $stats['requests']);
|
||||
assertSame(180.0, $stats['average_ms']);
|
||||
assertSame(1, $stats['errors']);
|
||||
assertSame(1, $stats['slow'], 'медленным считается ответ дольше порога');
|
||||
});
|
||||
|
||||
Cache::flush();
|
||||
|
||||
assertSame(0, Metrics::requests(1)['requests'], 'счётчики живут в кэше и чистятся вместе с ним');
|
||||
});
|
||||
|
||||
test('показатели: сбор выключается настройкой', function (): void {
|
||||
Cache::flush();
|
||||
|
||||
withConfig(['metrics.enabled' => false], static function (): void {
|
||||
Metrics::track(10, 200);
|
||||
|
||||
assertSame(0, Metrics::requests(1)['requests']);
|
||||
});
|
||||
});
|
||||
|
||||
test('показатели: снимок отвечает без запущенного сбора', function (): void {
|
||||
$snapshot = Metrics::snapshot();
|
||||
|
||||
assertTrue(isset($snapshot['users']['total']), 'в снимке есть пользователи');
|
||||
assertTrue(isset($snapshot['queue']), 'и очередь');
|
||||
assertTrue(($snapshot['storage']['var_bytes'] ?? -1) >= 0);
|
||||
});
|
||||
|
||||
test('присмотр: порог сработал — сообщение уходит один раз за окно', function (): void {
|
||||
Cache::flush();
|
||||
|
||||
withConfig([
|
||||
'monitor.errors' => 1,
|
||||
'monitor.repeat_minutes' => 60,
|
||||
'monitor.failed_jobs' => 1000,
|
||||
'monitor.queue_backlog' => 1000,
|
||||
'monitor.free_bytes' => 0,
|
||||
], static function (): void {
|
||||
Setting::set('monitor:alert:http.errors', '0');
|
||||
|
||||
Metrics::track(5, 500);
|
||||
|
||||
$problems = Monitor::check();
|
||||
|
||||
assertTrue(isset($problems['http.errors']), 'ошибки 5xx выше порога — это проблема');
|
||||
|
||||
$mark = (int) Setting::get('monitor:alert:http.errors', '0');
|
||||
|
||||
assertTrue($mark > 0, 'отметка о сообщении поставлена');
|
||||
|
||||
// Второй проход в том же окне отметку не двигает — значит, и не сообщает
|
||||
Monitor::check();
|
||||
|
||||
assertSame($mark, (int) Setting::get('monitor:alert:http.errors', '0'));
|
||||
});
|
||||
|
||||
Setting::set('monitor:alert:http.errors', '0');
|
||||
Cache::flush();
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Сводки отчётов.
|
||||
*/
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Support\Reports;
|
||||
|
||||
test('отчёты: ряд по дням идёт без дырок', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$today = date('Y-m-d');
|
||||
$yesterday = date('Y-m-d', time() - 86400);
|
||||
|
||||
Note::create(['title' => 'сегодня раз']);
|
||||
Note::create(['title' => 'сегодня два']);
|
||||
|
||||
$old = Note::create(['title' => 'позавчера']);
|
||||
$old->forceFill(['created_at' => date('Y-m-d H:i:s', time() - 2 * 86400)])->save();
|
||||
|
||||
$series = Reports::series(Note::query(), 'created_at', date('Y-m-d', time() - 2 * 86400), $today);
|
||||
|
||||
assertCount(3, $series, 'три дня — три точки, даже если в середине пусто');
|
||||
assertSame(0, $series[$yesterday], 'пустой день в ряду нулём, а не пропуском');
|
||||
assertSame(2, $series[$today]);
|
||||
assertSame(3, Reports::total($series));
|
||||
});
|
||||
});
|
||||
|
||||
test('отчёты: недели считаются по понедельникам', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$note = Note::create(['title' => 'на прошлой неделе']);
|
||||
$note->forceFill(['created_at' => date('Y-m-d H:i:s', time() - 7 * 86400)])->save();
|
||||
|
||||
$series = Reports::series(
|
||||
Note::query(),
|
||||
'created_at',
|
||||
date('Y-m-d', time() - 14 * 86400),
|
||||
date('Y-m-d'),
|
||||
Reports::WEEK
|
||||
);
|
||||
|
||||
foreach (array_keys($series) as $key) {
|
||||
assertSame('Monday', date('l', (int) strtotime((string) $key)), 'ключ недели — дата понедельника');
|
||||
}
|
||||
|
||||
assertSame(1, Reports::total($series));
|
||||
});
|
||||
});
|
||||
|
||||
test('отчёты: разбивка по колонке идёт от большего', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
Note::create(['title' => 'раз', 'pinned' => 1]);
|
||||
Note::create(['title' => 'два', 'pinned' => 0]);
|
||||
Note::create(['title' => 'три', 'pinned' => 0]);
|
||||
|
||||
$breakdown = Reports::breakdown(Note::query(), 'pinned');
|
||||
|
||||
assertSame([0 => 2, 1 => 1], array_map('intval', $breakdown));
|
||||
assertSame(2, array_values($breakdown)[0], 'первым идёт то, чего больше');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user