Уникальные ID сущностей, журнал событий и его UI с ротацией и очисткой
Глобально уникальные ID (docs/changes/016): - у устройств, групп, задач, резервных копий и записей журнала ID вида <префикс>_<uuid7> (dev_, grp_, job_, bkp_, evt_): типы не пересекаются, внутри типа ID не повторяются и сортируются по времени; - миграция БД v1 заменяет числовые ID с пересчётом ссылок (копия файла БД перед миграцией, сверка числа строк, одна транзакция); - резервная копия = пара файлов с одним bkp_ ID, файлы в S3 получают метаданные backup-id/device-id; синхронизация метаданных с бакетом; - журнал событий в БД (events): создание/изменение/удаление, задачи, бэкапы, смена online/offline, вход в UI; API чтения GET /api/v1/events. Журнал в UI, ротация и очистка (docs/changes/017): - страница «Журнал»: фильтры, подгрузка «Показать ещё», окно записи; - настройки ротации (срок и максимум записей) хранятся в БД (схема v2), ротация при старте, раз в час и после сохранения настроек; - очистка журнала только через окно с паролем пользователя, блокировка после 5 неверных попыток, остаётся запись о факте очистки; через API очистки нет. Тесты: 20 из 20. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1e5fb17755
commit
26dd1f8be4
43 files changed
+1677
-157
No files matched your search
@@ -26,7 +26,7 @@
|
||||
<label class="lbl">Группа
|
||||
<select class="field" name="group_id" data-newgroup style="width:100%">
|
||||
<option value="">— без группы —</option>
|
||||
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if v.group_id == g.id|string }}>{{ g.name }}</option>{% endfor %}
|
||||
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if v.group_id == g.id }}>{{ g.name }}</option>{% endfor %}
|
||||
<option value="__new__" {{ "selected" if v.group_id == "__new__" }}>+ Новая группа…</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{% import "_ui.html" as ui %}
|
||||
<div class="w640">
|
||||
<header class="modal-head">
|
||||
<h2 id="modal-title">Запись журнала</h2>
|
||||
{% if in_modal %}<button type="button" class="btn ghost-n icon" data-close aria-label="Закрыть">{{ ui.icon("x") }}</button>{% endif %}
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
{% macro idcell(value) -%}<span class="mono">{{ value }}</span><button type="button" class="btn ghost-n icon" data-copy="{{ value }}" aria-label="Копировать" title="Копировать">{{ ui.icon("copy") }}</button>{%- endmacro %}
|
||||
<div class="kv"><span>ID записи</span><div>{{ idcell(e.id) }}</div></div>
|
||||
<div class="kv"><span>Время</span><div>{{ e.ts|dts }} UTC</div></div>
|
||||
<div class="kv"><span>Тип</span><div><span class="badge {{ ev_kind(e.type) }}">{{ e.type }}</span></div></div>
|
||||
<div class="kv"><span>Актор</span><div>{{ e.actor }}</div></div>
|
||||
<div class="kv"><span>Сущность</span><div>{% if e.entity_id %}{{ ev_entity(e.entity_type) }} · {{ idcell(e.entity_id) }}{% else %}<span class="muted">{{ ev_entity(e.entity_type) }}</span>{% endif %}</div></div>
|
||||
<div class="kv"><span>Устройство</span><div>{% if e.device_id %}{% if device %}{{ device.name }} · {% endif %}{{ idcell(e.device_id) }}{% if not device %}<span class="muted">(удалено)</span>{% endif %}{% else %}<span class="muted">—</span>{% endif %}</div></div>
|
||||
<div class="kv"><span>Задача</span><div>{% if e.job_id %}{{ idcell(e.job_id) }}{% else %}<span class="muted">—</span>{% endif %}</div></div>
|
||||
<div class="kv"><span>Сообщение</span><div>{{ e.message or "—" }}</div></div>
|
||||
{% if data_json %}<div style="font:500 13px/1.3 var(--font)">Данные</div><pre class="json">{{ data_json }}</pre>{% endif %}
|
||||
</div>
|
||||
<footer class="modal-foot">
|
||||
<span class="grow"></span>
|
||||
{% if in_modal %}<button type="button" class="btn secondary" data-close>Закрыть</button>{% else %}<a class="btn secondary" href="/events">К журналу</a>{% endif %}
|
||||
</footer>
|
||||
</div>
|
||||
@@ -0,0 +1,2 @@
|
||||
{% include "_events_rows.html" %}
|
||||
{% include "_events_more.html" %}
|
||||
@@ -0,0 +1,20 @@
|
||||
{% import "_ui.html" as ui %}
|
||||
<form method="post" action="/events/clear" {% if in_modal %}hx-post="/events/clear" hx-target="#modal-body"{% endif %}>
|
||||
<header class="modal-head">
|
||||
<h2 id="modal-title">Очистить журнал</h2>
|
||||
{% if in_modal %}<button type="button" class="btn ghost-n icon" data-close aria-label="Закрыть">{{ ui.icon("x") }}</button>{% endif %}
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="note">Будет удалено <b>{{ st.count|num }} {{ st.count|plural("запись", "записи", "записей") }}</b> без возможности восстановления. В журнале останется одна запись об очистке: кто и когда её выполнил.</div>
|
||||
<label class="lbl"><span>Пароль пользователя <b style="font-weight:600">{{ user }}</b> <small>подтверждение нужно только для этого действия</small></span>
|
||||
<input class="input {{ 'invalid' if error }}" type="password" name="password" placeholder="Введите пароль" autocomplete="current-password"
|
||||
data-enables="#clear-confirm" {{ "disabled" if locked else "autofocus" }} {% if error %}aria-invalid="true" aria-describedby="clear-error"{% endif %}></label>
|
||||
{% if locked %}<div class="form-err" role="alert">Слишком много неверных попыток. Повторите через {{ minutes }} мин.</div>
|
||||
{% elif error %}<div class="field-err" id="clear-error" role="alert">{{ error }}</div>{% endif %}
|
||||
</div>
|
||||
<footer class="modal-foot">
|
||||
<span class="grow"></span>
|
||||
{% if in_modal %}<button type="button" class="btn ghost-n" data-close>Отмена</button>{% else %}<a class="btn ghost-n" href="/events">Отмена</a>{% endif %}
|
||||
<button class="btn danger" id="clear-confirm" disabled>{{ ui.icon("trash") }}Очистить журнал</button>
|
||||
</footer>
|
||||
</form>
|
||||
@@ -0,0 +1,2 @@
|
||||
<div id="events-more" class="more"{% if oob %} hx-swap-oob="true"{% endif %}>{% if more %}<button type="button" class="btn secondary" hx-get="/ui/events?{{ qs }}{{ '&' if qs }}before={{ next_before }}&shown={{ shown }}" hx-target="#events-body" hx-swap="beforeend">Показать ещё 100</button>{% endif %}</div>
|
||||
<div id="events-foot" class="tfoot"{% if oob %} hx-swap-oob="true"{% endif %}>Показано {{ shown }} из {{ total|num }} {{ total|plural("записи", "записей", "записей") }}</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
{% for e in rows %}
|
||||
<tr class="clickable">
|
||||
<td class="c-small">{{ e.ts|dts }}</td>
|
||||
<td><span class="badge {{ ev_kind(e.type) }}">{{ e.type }}</span></td>
|
||||
<td><span class="ent">{{ ev_entity(e.entity_type) }}</span><span class="c-mono muted" {% if e.entity_id %}title="{{ e.entity_id }}"{% endif %}>{{ (e.entity_id|short_id) if e.entity_id else "—" }}</span></td>
|
||||
<td class="msg-cell" title="{{ e.message }}">{{ e.message }}</td>
|
||||
<td class="c-small">{{ e.actor }}</td>
|
||||
<td><a class="c-mono row-link" href="/events/{{ e.id }}" hx-get="/ui/dialog/event/{{ e.id }}" hx-target="#modal-body" title="{{ e.id }}">{{ e.id|short_id }}</a></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
{% if not oob %}<tr><td colspan="6" class="empty">Записей не найдено.</td></tr>{% endif %}
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% import "_ui.html" as ui %}
|
||||
<form method="post" action="/events/settings" {% if in_modal %}hx-post="/events/settings" hx-target="#modal-body"{% endif %}>
|
||||
<header class="modal-head">
|
||||
<h2 id="modal-title">Настройки журнала</h2>
|
||||
{% if in_modal %}<button type="button" class="btn ghost-n icon" data-close aria-label="Закрыть">{{ ui.icon("x") }}</button>{% endif %}
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
{% if error %}<div class="form-err" role="alert">{{ error }}</div>{% endif %}
|
||||
<div class="sum">Сейчас в журнале: <b>{{ st.count|num }} {{ st.count|plural("запись", "записи", "записей") }}</b> · старейшая {{ st.oldest|dt }}</div>
|
||||
<label class="lbl"><span>Хранить записи, дней <small>0 — без ограничения по сроку</small></span>
|
||||
<input class="input" type="number" name="retention_days" min="0" max="3650" value="{{ values.retention_days }}" required></label>
|
||||
<label class="lbl"><span>Максимум записей <small>0 — без ограничения по количеству</small></span>
|
||||
<input class="input" type="number" name="max_rows" min="0" value="{{ values.max_rows }}" required></label>
|
||||
<div class="note info">Ротация запускается раз в час и при сохранении настроек: удаляет самые старые записи сверх срока и лимита. Каждая ротация фиксируется записью в журнале.</div>
|
||||
</div>
|
||||
<footer class="modal-foot">
|
||||
<span class="grow"></span>
|
||||
{% if in_modal %}<button type="button" class="btn ghost-n" data-close>Отмена</button>{% else %}<a class="btn ghost-n" href="/events">Отмена</a>{% endif %}
|
||||
<button class="btn primary">Сохранить</button>
|
||||
</footer>
|
||||
</form>
|
||||
@@ -11,12 +11,12 @@
|
||||
{% if flash %}<p class="err">{{ flash }}</p>{% endif %}
|
||||
<div class="card">
|
||||
<table class="grid jobs">
|
||||
<colgroup><col style="width:56px"><col style="width:16%"><col style="width:16%"><col style="width:130px"><col><col style="width:150px"></colgroup>
|
||||
<thead><tr><th>#</th><th>Устройство</th><th>Операция</th><th>Статус</th><th>Сообщение</th><th>Создана (UTC)</th></tr></thead>
|
||||
<colgroup><col style="width:96px"><col style="width:16%"><col style="width:16%"><col style="width:130px"><col><col style="width:150px"></colgroup>
|
||||
<thead><tr><th>ID</th><th>Устройство</th><th>Операция</th><th>Статус</th><th>Сообщение</th><th>Создана (UTC)</th></tr></thead>
|
||||
<tbody>
|
||||
{% for j in jobs %}
|
||||
<tr>
|
||||
<td class="muted">{{ j.id }}</td>
|
||||
<td class="c-mono muted" title="{{ j.id }}">{{ j.id|short_id }}</td>
|
||||
<td style="font-weight:500">{{ j.device_name }}</td>
|
||||
<td>{{ {"backup": "Бэкап", "ros_update": "Обновление ROS", "fw_update": "Обновление FW"}.get(j.type, j.type) }}</td>
|
||||
<td><span class="badge {{ {'running': 'run', 'done': 'ok', 'failed': 'bad'}.get(j.status, '') }}">{{ {"pending": "В очереди", "running": "Выполняется", "done": "Готово", "failed": "Ошибка"}.get(j.status, j.status) }}</span></td>
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<select class="field {{ 'on' if flt.group }}" name="group" onchange="this.form.submit()" aria-label="Группа" style="width:170px">
|
||||
<option value="">Группа: любая</option>
|
||||
<option value="none" {{ "selected" if flt.group == "none" }}>Группа: без группы</option>
|
||||
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if flt.group == g.id|string }}>Группа: {{ g.name }}</option>{% endfor %}
|
||||
{% for g in groups %}<option value="{{ g.id }}" {{ "selected" if flt.group == g.id }}>Группа: {{ g.name }}</option>{% endfor %}
|
||||
</select>
|
||||
<select class="field {{ 'on' if flt.device }}" name="device" onchange="this.form.submit()" aria-label="Устройство" style="width:190px">
|
||||
<option value="">Устройство: любое</option>
|
||||
@@ -57,7 +57,7 @@
|
||||
<td style="font-weight:600">{{ i.device or "—" }}</td>
|
||||
<td class="muted">{{ i.group or "—" }}</td>
|
||||
<td><span class="badge">{{ {"backup": ".backup", "rsc": ".rsc"}.get(i.kind, "—") }}</span></td>
|
||||
<td class="c-mono" title="{{ i.key }}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ i.key.split("/")[-1] }}</td>
|
||||
<td class="c-mono" title="{{ i.key }}{% if i.backup_id %} · {{ i.backup_id }}{% endif %}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ i.key.split("/")[-1] }}</td>
|
||||
<td class="c-small">{{ i.size|size }}</td>
|
||||
<td class="c-small">{{ i.last_modified|dt }}</td>
|
||||
<td class="c-menu">
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
</head>
|
||||
<body>
|
||||
{% if request.session.get("user") %}
|
||||
{% set nav = [("Устройства", "/", "devices"), ("Группы", "/groups", "groups"), ("Резервные копии", "/backups", "backups")] %}
|
||||
{% set nav = [("Устройства", "/", "devices"), ("Группы", "/groups", "groups"), ("Резервные копии", "/backups", "backups"), ("Журнал", "/events", "events")] %}
|
||||
<header class="app-header">
|
||||
<a class="brand" href="/"><span class="brand-logo">{{ ui.icon("router") }}</span>ros_control</a>
|
||||
<nav class="nav" aria-label="Разделы">
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="button" class="btn secondary" hx-post="/ui/refresh" hx-include="#dev-filters" hx-target="#devices" hx-indicator="#busy">{{ ui.icon("refresh") }}Обновить статус</button>
|
||||
<button type="button" class="btn primary" hx-get="/ui/dialog/device{{ '?group=' ~ flt.group if flt.group.isdigit() }}" hx-target="#modal-body">{{ ui.icon("plus") }}Добавить устройство</button>
|
||||
<button type="button" class="btn primary" hx-get="/ui/dialog/device{{ '?group=' ~ flt.group if flt.group.startswith('grp_') }}" hx-target="#modal-body">{{ ui.icon("plus") }}Добавить устройство</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<div class="card page-card" style="max-width:640px">{% include "_event_dialog.html" %}</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,48 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_ui.html" as ui %}
|
||||
{% block content %}
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>Журнал</h1>
|
||||
<div class="sub">{{ st.count|num }} {{ st.count|plural("запись", "записи", "записей") }} · старейшая {{ st.oldest|dt }} · ротация: {{ rotation }}</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<a class="btn secondary" href="/events{{ '?' ~ qs if qs }}">{{ ui.icon("refresh") }}Обновить</a>
|
||||
<button type="button" class="btn secondary" hx-get="/ui/dialog/events-settings" hx-target="#modal-body">{{ ui.icon("settings") }}Настройки</button>
|
||||
<button type="button" class="btn danger" hx-get="/ui/dialog/events-clear" hx-target="#modal-body">{{ ui.icon("trash") }}Очистить журнал</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="tools">
|
||||
<form method="get" action="/events">
|
||||
<select class="field {{ 'on' if flt.type }}" name="type" onchange="this.form.submit()" aria-label="Тип" style="width:170px">
|
||||
<option value="">Тип: любой</option>
|
||||
{% for c in categories %}<option value="{{ c }}" {{ "selected" if flt.type == c }}>Тип: {{ c }}</option>{% endfor %}
|
||||
{% for t in types %}<option value="{{ t }}" {{ "selected" if flt.type == t }}>Тип: {{ t }}</option>{% endfor %}
|
||||
</select>
|
||||
<select class="field {{ 'on' if flt.actor }}" name="actor" onchange="this.form.submit()" aria-label="Актор" style="width:170px">
|
||||
<option value="">Актор: любой</option>
|
||||
{% for a in actors %}<option value="{{ a }}" {{ "selected" if flt.actor == a }}>Актор: {{ a }}</option>{% endfor %}
|
||||
</select>
|
||||
<select class="field {{ 'on' if flt.device }}" name="device" onchange="this.form.submit()" aria-label="Устройство" style="width:200px">
|
||||
<option value="">Устройство: любое</option>
|
||||
{% for d in devices %}<option value="{{ d.id }}" {{ "selected" if flt.device == d.id }}>Устройство: {{ d.name }}</option>{% endfor %}
|
||||
</select>
|
||||
<label class="datefield">с <input type="date" name="date_from" value="{{ flt.date_from }}" onchange="this.form.submit()" aria-label="Дата с"></label>
|
||||
<label class="datefield">по <input type="date" name="date_to" value="{{ flt.date_to }}" onchange="this.form.submit()" aria-label="Дата по"></label>
|
||||
<label class="search">{{ ui.icon("search") }}<input type="search" name="q" value="{{ flt.q }}" placeholder="Сообщение или ID" aria-label="Поиск по сообщению или ID" style="width:240px"></label>
|
||||
<span class="grow"></span>
|
||||
{% if flt_active %}<a class="btn ghost" href="/events">Сбросить ({{ flt_active }})</a>{% endif %}
|
||||
</form>
|
||||
</div>
|
||||
<div class="table-wrap">
|
||||
<table class="grid events">
|
||||
<colgroup><col style="width:176px"><col style="width:180px"><col style="width:150px"><col><col style="width:110px"><col style="width:96px"></colgroup>
|
||||
<thead><tr><th>Время (UTC)</th><th>Тип</th><th>Сущность</th><th>Сообщение</th><th>Актор</th><th>ID записи</th></tr></thead>
|
||||
<tbody id="events-body">{% include "_events_rows.html" %}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% include "_events_more.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
Reference in new issue
Block a user