Улучшить работу чата и устойчивость сервисов

This commit is contained in:
Никита
2026-11-10 12:46:37 +03:00
parent 30450dcd73
commit e7a3ad2469
10 changed files with 214 additions and 27 deletions
+20
View File
@@ -283,3 +283,23 @@ operations.css и operations.js. Добавлены 16 SVG на общей се
В браузере проверены реальные состояния восьми карточек API/зависимостей.
SVG разобраны XML-парсером, все новые asset URL отвечают 200. make check,
make validate и публичный smoke-сценарий прошли после изменений.
## Удобство и устойчивость интерфейса
В чате добавлены копирование текста, вставка PNG/JPEG из буфера и перенос файла
мышью. Поиск чатов открывается сочетанием ⌘K/Ctrl+K, результаты можно очистить
кнопкой или Escape. В панели задания фильтруются среди последних 30 записей;
состояние кнопки повтора не перерисовывается без изменения данных. При смене
пользователя содержимое панели удаляется из страницы. Анимации уважают настройку
уменьшения движения.
Формы входа и регистрации ожидают загрузки скриптов; их резервный метод POST не
помещает поля в адрес страницы. HAProxy проверяет API с тайм-аутом 2 секунды и
интервалом 1 секунда. Docker healthcheck RabbitMQ проверяет TCP-порт 5672 без
запуска Erlang-процесса на каждый опрос; проверка панели дополнительно выполняет
AMQP-запрос. Лимит RabbitMQ по умолчанию 512 МиБ, настраивается BROKER_MEMORY.
При прежней проверке регулярные Erlang-процессы исчерпывали лимит при запуске.
Результаты повторных проверок и переключения API: evidence/ui-reliability.txt.
Предыдущие измерения нагрузки относятся к настройкам и версии, указанным в их
исходных результатах; повторный эксперимент для новых параметров не проводился.
+2 -2
View File
@@ -141,10 +141,10 @@ services:
volumes:
- broker_data:/var/lib/rabbitmq
cpus: 0.5
mem_limit: 384m
mem_limit: ${BROKER_MEMORY:-512m}
restart: unless-stopped
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/5672'"]
interval: 3s
timeout: 5s
retries: 30
+19
View File
@@ -0,0 +1,19 @@
Проверка после изменений интерфейса и настроек сервисов:
make check: PASS
make validate: PASS
make test: PASS
student-tests/chunked_login.py: PASS
student-tests/processing_panel.py: PASS
make operations-test: PASS (повторное задание обработано worker)
make test-failover ACTION_SCRIPT=scripts/stop-one.sh:
observed_instances_before: 2
successful_writes: 109
failed_attempts: 1
first_recovery_seconds: 2.756
PASS: подтверждённые данные и сессия сохранены.
Первый запуск failover остановился до сценария из-за тайм-аута регистрации,
пока RabbitMQ запускался. После готовности сервисов повторный запуск прошёл.
В браузере проверены поиск, копирование сообщения, вставка PNG, превью и удаление
черновика, фильтр ошибок и отображение состояний сервисов.
+3 -3
View File
@@ -5,8 +5,8 @@ global
defaults
mode http
timeout connect 500ms
timeout check 500ms
timeout connect 2s
timeout check 2s
timeout client 15s
timeout server 12s
timeout http-request 5s
@@ -36,5 +36,5 @@ backend messenger
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost
http-check expect status 200
default-server check inter 500ms fastinter 250ms downinter 500ms fall 2 rise 2
default-server check inter 1s fastinter 500ms downinter 1s fall 2 rise 2
server-template api 1-8 api:8080 resolvers docker resolve-prefer ipv4 init-addr none
+78 -9
View File
@@ -94,6 +94,9 @@ function selectAuthTab(register) {
function setFormBusy(form, busy) {
form.querySelectorAll("input, textarea, button").forEach(element => { element.disabled = busy; });
form.setAttribute("aria-busy", String(busy));
const label = form.querySelector(".button-label");
if (label) label.textContent = busy ? label.dataset.busy : label.dataset.label;
}
function persistSession(session) {
@@ -131,6 +134,7 @@ async function enterSession(session) {
$("profile-username").textContent = "@" + session.user.username;
paintAvatar($("profile-avatar"), session.user.id, session.user.display_name);
$("chat-search").value = "";
$("clear-chat-search").hidden = true;
renderChats();
try { await loadChats(false, true); } catch (error) {
if (state.session?.token === session.token) { $("welcome").hidden = true; $("workspace-error").hidden = false; }
@@ -221,6 +225,9 @@ $("register-form").addEventListener("submit", async event => {
} finally { setFormBusy(form, false); }
});
$("login-submit").disabled = false;
$("register-submit").disabled = false;
function memberCount(count) { const n = count % 100, d = count % 10; return count + " " + (n >= 11 && n <= 14 ? "участников" : d === 1 ? "участник" : d >= 2 && d <= 4 ? "участника" : "участников"); }
function chatActivity(chat) { return chat.last_message?.created_at || chat.created_at; }
function chatTime(value) {
@@ -333,12 +340,29 @@ $("retry-messages").addEventListener("click", async () => {
finally { button.disabled = false; }
});
$("chat-search").addEventListener("input", renderChats);
$("chat-search").addEventListener("input", () => {
$("clear-chat-search").hidden = !$("chat-search").value;
renderChats();
});
$("clear-chat-search").addEventListener("click", () => {
$("chat-search").value = ""; $("clear-chat-search").hidden = true; renderChats(); $("chat-search").focus();
});
$("chat-search").addEventListener("keydown", event => {
if (event.key === "Escape" && event.currentTarget.value) { event.stopPropagation(); $("clear-chat-search").click(); }
});
document.addEventListener("keydown", event => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k" && state.session && !document.querySelector("dialog[open]")) {
event.preventDefault();
if (matchMedia("(max-width: 720px)").matches && $("app-screen").classList.contains("chat-open")) $("back-to-chats").click();
$("chat-search").focus();
}
});
$("message-list").addEventListener("messagecopy", event => toast(event.detail.success ? "Текст скопирован" : "Не удалось скопировать текст", !event.detail.success));
$("refresh-chats").addEventListener("click", async () => { try { await loadChats(); } catch (error) { toast(error.message, true); } });
$("more-chats").addEventListener("click", async () => { try { await loadChats(true); } catch (error) { toast(error.message, true); } });
async function selectChat(chat) {
if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); return; }
if (state.current?.id === chat.id) { $("app-screen").classList.add("chat-open"); if(matchMedia("(min-width: 721px)").matches) $("message-input").focus({preventScroll:true}); return; }
if (state.current) state.drafts.set(state.current.id, $("message-input").value);
state.epoch++;
reactions.clear(); reactionBusy.clear(); reactionVersion++;
@@ -369,6 +393,7 @@ async function selectChat(chat) {
$("older-messages").hidden = true;
$("messages-loading").hidden = false;
$("message-list").setAttribute("aria-busy", "true");
if(matchMedia("(min-width: 721px)").matches) $("message-input").focus({preventScroll:true});
if (!matchMedia("(prefers-reduced-motion: reduce)").matches) $("conversation").animate([{ opacity: 0, transform: "translateY(5px)" }, { opacity: 1, transform: "none" }], { duration: 180, easing: "ease-out" });
try { await Promise.all([syncRecent(true), loadMembers(state.epoch, chat.id)]); }
catch (error) { if (state.historyReady) toast(error.message, true); }
@@ -583,7 +608,10 @@ $("new-chat-form").addEventListener("submit", async event => {
else {
const username=entry.replace(/^@/,'').toLowerCase();
if(!/^[a-z0-9_]{3,32}$/.test(username))throw new Error('Введите логин или полный ID участника.');
const user=await request('/api/ui/users/'+encodeURIComponent(username));ids.push(user.id);
let user;
try { user=await request('/api/ui/users/'+encodeURIComponent(username)); }
catch(error) { if(error.status===404)throw new Error('Пользователь @'+username+' не найден.');throw error; }
ids.push(user.id);
}
}
if(token!==state.session?.token)return;
@@ -621,7 +649,11 @@ $("logout").addEventListener("click", async () => {
catch (error) { if (error.status !== 401) toast(error.message, true); }
finally { $("logout").disabled = false; }
});
$("back-to-chats").addEventListener("click", () => $("app-screen").classList.remove("chat-open"));
$("back-to-chats").addEventListener("click", () => {
$("app-screen").classList.remove("chat-open");
const row=chatRows.get(state.current?.id)?.button;
if(row?.isConnected)row.focus({preventScroll:true});
});
$("refresh-messages").addEventListener("click", async () => {
try { await syncRecent(); } catch (error) { toast(error.message, true); }
});
@@ -691,18 +723,21 @@ function renderAttachedDrafts() {
}
}
$("pick-file").addEventListener("click",()=>$("image-file").click());
$("image-file").addEventListener("change",async()=>{
const file=$("image-file").files[0];$("image-file").value="";
$("image-file").addEventListener("change",()=>{
const file=$("image-file").files[0];$("image-file").value="";void attachImage(file);
});
async function attachImage(file) {
if(!file || !state.current || uploadBusy || state.sending) return;
if(file.size>10485760) {toast("Максимум 10 MiB",true);return;}
if(file.size>10485760) {toast("Максимум 10 МБ",true);return;}
if(!["image/png","image/jpeg"].includes(file.type)) {toast("Выберите PNG или JPEG",true);return;}
if((attachedDrafts.get(state.current.id)||[]).length>=10) {toast("Максимум 10 вложений",true);return;}
const chat=state.current.id, session=state.session.token;
const draft={filename:file.name,previewUrl:URL.createObjectURL(file),id:null,removed:false};
const filename=file.name && !/[\/\\\x00-\x1f]/.test(file.name) ? file.name : (file.type === "image/png" ? "image.png" : "image.jpg");
const draft={filename,previewUrl:URL.createObjectURL(file),id:null,removed:false};
attachedDrafts.set(chat,[...(attachedDrafts.get(chat)||[]),draft]);renderAttachedDrafts();
uploadBusy=true;$("pick-file").disabled=true;updateComposer();
try {
const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(file.name)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}});
const attachment=await request(`/api/v1/chats/${chat}/attachments?filename=${encodeURIComponent(filename)}`,{method:"POST",raw:file,headers:{"Content-Type":file.type}});
if(state.session?.token!==session || draft.removed) return;
Object.assign(draft,attachment);renderAttachedDrafts();
}catch(error){
@@ -713,4 +748,38 @@ $("image-file").addEventListener("change",async()=>{
if(state.session?.token===session) toast(error.message,true);
}
finally {uploadBusy=false;$("pick-file").disabled=state.sending;updateComposer();}
}
const dropArea = $("conversation");
let dragDepth = 0;
function resetDrag() { dragDepth = 0; dropArea.classList.remove("is-dragging-file"); }
for (const type of ["dragenter", "dragover"]) dropArea.addEventListener(type, event => {
if (!event.dataTransfer?.types.includes("Files") || !state.current || state.sending) return;
event.preventDefault();
if (type === "dragenter") dragDepth++;
event.dataTransfer.dropEffect = "copy";
dropArea.classList.add("is-dragging-file");
});
dropArea.addEventListener("dragleave", event => {
if (!event.dataTransfer?.types.includes("Files")) return;
dragDepth = Math.max(0, dragDepth - 1);
if (!dragDepth) resetDrag();
});
dropArea.addEventListener("drop", event => {
if (!event.dataTransfer?.types.includes("Files")) return;
event.preventDefault(); resetDrag();
if (uploadBusy || state.sending) { toast("Дождитесь завершения загрузки", true); return; }
const files = [...event.dataTransfer.files];
if (files.length > 1) { toast("Добавляйте изображения по одному", true); return; }
void attachImage(files[0]);
});
$("message-input").addEventListener("paste", event => {
const file = [...(event.clipboardData?.files || [])].find(item => item.type.startsWith("image/"));
if (!file) return;
event.preventDefault();
if (uploadBusy || state.sending) { toast("Дождитесь завершения загрузки", true); return; }
void attachImage(file);
});
window.addEventListener("dragend", resetDrag);
window.addEventListener("drop", resetDrag);
+25
View File
@@ -107,3 +107,28 @@ dialog::backdrop {background:#10130db3;}
@keyframes dialog-appear{from{opacity:0;transform:translateY(8px) scale(.985);}to{opacity:1;transform:none;}}
@keyframes welcome-appear{from{opacity:0;transform:translateY(9px);}to{opacity:1;transform:none;}}
@media(prefers-reduced-motion:reduce){.chat-row,.button,.icon-button,.processing-results a,.auth-switch button{transition:none;}.chat-row:hover{transform:none;}}
.search-field {position:relative;}
.search-field input[type=search]::-webkit-search-cancel-button {-webkit-appearance:none;}
.search-clear {display:grid;place-items:center;width:24px;height:24px;padding:0;border:0;border-radius:7px;background:#ffffff0b;color:#aeb8a3;font-size:18px;line-height:1;flex-shrink:0;}
.search-clear:hover {background:#ffe13518;color:#ffe135;}
.message {position:relative;}
.message-copy {position:absolute;right:-34px;bottom:2px;display:grid;place-items:center;width:28px;height:28px;border:1px solid #ffffff10;border-radius:8px;background:#2b2e27;color:#b2bca5;opacity:0;pointer-events:none;transition:opacity .18s,background .18s;}
.message-copy svg {width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;}
.message.mine .message-copy {right:auto;left:-34px;}
.message:hover .message-copy,.message:focus-within .message-copy {opacity:1;pointer-events:auto;}
.message-copy:hover {color:#ffe135;background:#353a2d;}
.conversation {position:relative;}
.conversation.is-dragging-file::after {content:'Отпустите изображение';position:absolute;z-index:6;inset:12px;display:grid;place-items:center;border:2px dashed #ffe13599;border-radius:16px;background:#20231def;color:#ffe135;font-size:16px;font-weight:550;pointer-events:none;}
@media(hover:none) {.message-copy {opacity:.8;pointer-events:auto;} .reaction-picker {opacity:.75;}}
@media(max-width:720px) {.message {max-width:calc(100% - 36px);}.message-copy {opacity:.8;pointer-events:auto;}}
@media(prefers-reduced-motion:reduce) {.message-copy {transition:none;}}
.auth-card .wide > .button-label {font-size:13px;line-height:1.4;}
.message-copy.is-copied {color:#ffe135;border-color:#ffe13550;background:#ffe1350d;}
@media(prefers-reduced-motion:no-preference) {
.messages-loading i {animation:message-loading 1.5s ease-in-out infinite alternate;}
.messages-loading i:nth-child(2) {animation-delay:.18s;}
.messages-loading i:nth-child(3) {animation-delay:.36s;}
.attachment-preview img {transition:opacity .28s ease;}
.draft-image {animation:dialog-appear .22s ease-out;}
}
@keyframes message-loading {from{opacity:.45}to{opacity:1}}
+3 -3
View File
@@ -109,10 +109,10 @@
<div class="auth-card">
<div class="auth-switch" aria-label="Выберите действие"><button id="tab-login" class="active" type="button" aria-pressed="true">Вход</button><button id="tab-register" type="button" aria-pressed="false">Регистрация</button></div>
<div id="login-panel"><h2>С возвращением.</h2>
<form id="login-form"><label>Имя пользователя<input id="login-username" name="username" autocomplete="username" placeholder="например, n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"></label><label>Пароль<span class="password-field"><input id="login-password" aria-label="Пароль" name="password" type="password" autocomplete="current-password" placeholder="Пароль" required><button class="password-toggle" type="button" data-password-toggle="login-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span></label><button class="button primary wide" type="submit">Войти <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
<form id="login-form" method="post"><label>Имя пользователя<input id="login-username" name="username" autocomplete="username" placeholder="например, n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"></label><label>Пароль<span class="password-field"><input id="login-password" aria-label="Пароль" name="password" type="password" autocomplete="current-password" placeholder="Пароль" required><button class="password-toggle" type="button" data-password-toggle="login-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span></label><button id="login-submit" class="button primary wide" type="submit" disabled><span class="button-label" data-label="Войти" data-busy="Входим…">Войти</span> <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
</div>
<div id="register-panel" hidden><h2>Создайте аккаунт.</h2><p class="muted">Присоединяйтесь к разговору.</p>
<form id="register-form"><label>Имя<input id="register-name" name="display_name" autocomplete="nickname" placeholder="Никита" required></label><label>Имя пользователя<input id="register-username" name="username" autocomplete="username" placeholder="n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"><span class="field-note">3-32 символа: a-z, цифры и _</span></label><label>Пароль<span class="password-field"><input id="register-password" aria-label="Пароль" name="password" type="password" autocomplete="new-password" placeholder="Придумайте пароль" required><button class="password-toggle" type="button" data-password-toggle="register-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span><span class="field-note">12-128 символов</span></label><button class="button primary wide" type="submit">Создать аккаунт <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
<form id="register-form" method="post"><label>Имя<input id="register-name" name="display_name" autocomplete="nickname" placeholder="Никита" required></label><label>Имя пользователя<input id="register-username" name="username" autocomplete="username" placeholder="n1k0der" pattern="[a-z0-9_]{3,32}" required autocapitalize="none" spellcheck="false"><span class="field-note">3-32 символа: a-z, цифры и _</span></label><label>Пароль<span class="password-field"><input id="register-password" aria-label="Пароль" name="password" type="password" autocomplete="new-password" placeholder="Придумайте пароль" required><button class="password-toggle" type="button" data-password-toggle="register-password" aria-label="Показать пароль" aria-pressed="false"><svg><use href="#i-eye"/></svg></button></span><span class="field-note">12-128 символов</span></label><button id="register-submit" class="button primary wide" type="submit" disabled><span class="button-label" data-label="Создать аккаунт" data-busy="Создаём…">Создать аккаунт</span> <svg class="action-arrow" aria-hidden="true"><use href="#i-arrow-up-right"/></svg></button></form>
</div>
<img id="auth-error-art" class="auth-error-art" src="/assets/kolovertysh-reconnect-320.webp" width="320" height="320" alt="" loading="lazy" decoding="async" hidden>
<p id="auth-notice" class="form-notice" role="status" aria-live="polite" hidden></p>
@@ -125,7 +125,7 @@
<aside class="sidebar">
<div class="sidebar-top"><a class="brand" href="/" aria-label="n1k0der"><span class="brand-mark"><i></i><i></i><i></i></span>n1k0der<span class="brand-dot">.</span></a><button class="icon-button" id="refresh-chats" title="Обновить чаты" aria-label="Обновить чаты"><svg><use href="#i-refresh"/></svg></button></div>
<div class="sidebar-heading"><div><span class="eyebrow">На связи</span><h2>Ваши чаты<span id="chat-count" class="count"></span></h2></div><button id="new-chat" class="icon-button filled" aria-label="Создать чат" title="Создать чат"><svg><use href="#i-plus"/></svg></button></div>
<label class="search-field"><span class="visually-hidden">Поиск среди загруженных чатов</span><svg aria-hidden="true"><use href="#i-search"/></svg><input id="chat-search" placeholder="Найти разговор" type="search" autocomplete="off"></label>
<div class="search-field"><label class="visually-hidden" for="chat-search">Поиск среди загруженных чатов</label><svg aria-hidden="true"><use href="#i-search"/></svg><input id="chat-search" placeholder="Найти разговор" title="Поиск чата: ⌘K или Ctrl+K" type="search" autocomplete="off"><button id="clear-chat-search" class="search-clear" type="button" aria-label="Очистить поиск" hidden>×</button></div>
<div id="chat-list" class="chat-list" aria-label="Список чатов"></div><button id="more-chats" class="text-button" hidden>Ещё чаты</button>
<button id="open-operations" class="diagnostics-toggle sidebar-diagnostics" type="button" hidden><svg viewBox="0 0 48 48" aria-hidden="true"><use href="/assets/system-icons.svg#overview"/></svg>Система</button>
<button class="diagnostics-toggle sidebar-diagnostics" type="button" data-diagnostics-toggle aria-controls="diagnostics-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Запросы API</button>
+10 -1
View File
@@ -48,7 +48,15 @@ export class MessageView {
stamp.className = "message-time";
bubble.append(text, ...((message.attachment_ids || []).map(attachmentCard)), stamp);
const reactions = new ReactionControls(message.id);
article.append(author, bubble, reactions.root);
const copy = document.createElement("button"); copy.type = "button"; copy.className = "message-copy";
copy.setAttribute("aria-label", "Скопировать текст сообщения"); copy.title = "Скопировать текст";
copy.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><use href="#i-copy"></use></svg>';
copy.addEventListener("click", async () => {
let success = false;
try { await navigator.clipboard.writeText(entry.text.textContent); success = true; copy.classList.add("is-copied"); setTimeout(() => copy.classList.remove("is-copied"), 1200); } catch { /* clipboard may be unavailable */ }
article.dispatchEvent(new CustomEvent("messagecopy", {bubbles:true, detail:{success}}));
});
article.append(author, bubble, reactions.root, copy);
entry = { article, author, text, stamp, reactions };
this.messages.set(message.id, entry);
if (animate && hadMessages) entering.push(article);
@@ -64,6 +72,7 @@ export class MessageView {
setText(entry.author, members.get(message.sender_id)?.display_name || "Участник " + message.sender_id.slice(0, 8));
setText(entry.text, message.text);
entry.text.hidden = !message.text;
entry.article.querySelector(".message-copy").hidden = !message.text;
entry.stamp.dateTime = message.created_at;
setText(entry.stamp, date.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }));
nodes.push(entry.article);
+12
View File
@@ -106,3 +106,15 @@
@media(max-width:720px){.ops-shell{display:block;}.ops-rail{position:sticky;top:0;z-index:3;height:auto;padding:9px 12px;border:0;border-bottom:1px solid #ffffff0d;}.ops-brand,.ops-rail-art,.ops-close{display:none!important;}.ops-rail nav{display:flex;gap:4px;margin:0;overflow:auto;scrollbar-width:none;}.ops-rail nav button{padding:10px;font-size:10px;white-space:nowrap;gap:6px;}.ops-rail nav button svg{width:15px;height:15px;}.ops-content{padding:0 14px;}.ops-header{padding:20px 0 15px;gap:12px;}.ops-header h1{font-size:21px;}.ops-live{font-size:9px;}.ops-panel .ops-mobile-close{display:block;padding:6px 12px;font-size:20px;}.ops-panel .ops-refresh{display:none;}.ops-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;margin:4px 0 14px;}.ops-metrics article{padding:16px;gap:11px;}.ops-metrics strong{font-size:30px;}.ops-box{padding:17px;scroll-margin-top:70px;}.ops-section-head{margin-bottom:18px;}.ops-flow{flex-wrap:wrap;gap:10px;}.ops-node{flex-basis:calc(50% - 25px);padding:15px;}.ops-arrow{flex-basis:20px;}.ops-arrow:nth-of-type(4){display:none;}.ops-api-nodes{flex-basis:100%;grid-template-columns:repeat(2,minmax(0,1fr));}.ops-api-nodes .ops-service{display:flex;flex-direction:column;padding:12px;gap:6px;}.ops-api-nodes .ops-service>svg{display:none;}.ops-services{gap:8px;}.ops-service{padding:13px;grid-template-columns:22px 1fr;gap:5px 8px;}.ops-service>svg{width:22px;height:22px;}.ops-service strong{font-size:11px;}.ops-service small{font-size:9px;}.ops-service-status{font-size:8px;}.ops-pipeline{gap:7px;justify-content:flex-start;}.ops-pipeline span{font-size:9px;padding:4px 7px;}.ops-charts{grid-template-columns:1fr;gap:14px;margin-top:14px;scroll-margin-top:70px;}.ops-bottom{gap:14px;margin-top:14px;}.ops-job{flex-wrap:wrap;}.ops-job button{margin-left:auto;}.ops-metrics{scroll-margin-top:70px;}}
@media(prefers-reduced-motion:reduce){.ops-panel{scroll-behavior:auto;}.ops-service.served{animation:none;}.ops-panel button,.ops-service{transition:none;}}
.ops-arrow i {position:absolute;width:5px;height:5px;border-radius:50%;top:-2px;left:0;background:#ffe135;opacity:0;box-shadow:0 0 7px #ffe13544;}
.ops-filters {display:flex;gap:6px;flex-wrap:wrap;margin:-3px 0 16px;}
.ops-panel .ops-filters button {padding:7px 11px;border-color:transparent;background:#ffffff05;color:#a6ad9c;font-size:10px;}
.ops-panel .ops-filters button[aria-pressed=true] {background:#ffe13512;border-color:#ffe13525;color:#ffe135;}
.ops-panel .ops-filters button:hover {background:#ffffff0d;}
.ops-rail nav button[aria-current=location] {color:#ffe135;background:#ffe1350d;border-color:#ffe1351a;}
@media(prefers-reduced-motion:no-preference) {
.ops-service,.ops-node,.ops-metrics article {transition:border-color .25s,background .25s,box-shadow .25s;}
.ops-service:hover,.ops-node:hover {border-color:#ffe13530;background:#ffe13504;}
.ops-rail nav button svg {transition:transform .25s ease;}
.ops-rail nav button:hover svg {transform:translateX(2px);}
.ops-job-state {transition:background .2s,color .2s;}
}
+42 -9
View File
@@ -1,10 +1,12 @@
let token=null, epoch=0, panel, timer, abort, samples=[], knownInstances=new Set();
let token=null, epoch=0, panel, timer, abort, samples=[], knownInstances=new Set(), lastJobs=[], jobFilter="all";
const $=selector=>panel.querySelector(selector);
const labels={queued:'В очереди',processing:'Обработка',ready:'Готово',failed:'Ошибка'};
const eventLabels={accepted:'Файл принят',published:'В очереди RabbitMQ',processing:'Обработчик начал работу',ready:'Результаты сохранены',retry_scheduled:'Назначен повтор',failed:'Ошибка обработки',lease_recovered:'Восстановлено после остановки',operator_replay:'Повторный запуск'};
function node(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
export async function operationsSession(value){
token=value;epoch++;panel?.close();clearTimeout(timer);abort?.abort();samples=[];knownInstances.clear();
token=value;epoch++;clearTimeout(timer);abort?.abort();
if(panel){panel.close();panel.remove();panel=null;}
samples=[];knownInstances.clear();lastJobs=[];jobFilter="all";
const button=document.getElementById('open-operations');button.hidden=true;
const version=epoch;if(!value)return;
try {const response=await fetch('/api/ui/operator',{headers:{Authorization:'Bearer '+value},cache:'no-store',signal:AbortSignal.timeout(8000)});const data=await response.json();if(version===epoch)button.hidden=!response.ok||!data.enabled;}catch{}
@@ -28,7 +30,7 @@ function init(){
<div class="ops-pipeline"><span>Файл</span><i>→</i><span>Outbox</span><i>→</i><span>Dispatcher</span><i>→</i><span>RabbitMQ</span><i>→</i><span>Worker</span><i>→</i><span>S3</span></div>
</section>
<section id="ops-charts" class="ops-charts"><article class="ops-box"><div class="ops-section-head"><h2>Активные задания</h2><strong class="ops-queue-value">0</strong></div><div class="ops-chart-legend"><i></i>В очереди и в обработке</div><div class="ops-queue-chart"></div><p class="ops-footnote">Последние 60 замеров открытой панели</p></article><article class="ops-box"><div class="ops-section-head"><h2>Отклик системы</h2><strong class="ops-latency-value">…</strong></div><div class="ops-chart-legend secondary"><i></i>Запрос с проверкой зависимостей</div><div class="ops-latency-chart"></div><p class="ops-footnote">Миллисекунды · наведите на точку для деталей</p></article></section>
<section class="ops-bottom"><article id="ops-jobs" class="ops-box"><div class="ops-section-head"><h2>Последние задания</h2><span class="ops-job-count"></span></div><div class="ops-job-heading"><span>Файл</span><span>Состояние</span></div><div class="ops-jobs"></div></article><article id="ops-events" class="ops-box"><div class="ops-section-head"><h2>События</h2><span class="ops-event-dot" aria-hidden="true"></span></div><ol class="ops-events"></ol></article></section>
<section class="ops-bottom"><article id="ops-jobs" class="ops-box"><div class="ops-section-head"><h2>Последние задания</h2><span class="ops-job-count"></span></div><div class="ops-filters" role="group" aria-label="Фильтр заданий"><button type="button" data-job-filter="all" aria-pressed="true">Все</button><button type="button" data-job-filter="active" aria-pressed="false">Активные</button><button type="button" data-job-filter="failed" aria-pressed="false">Ошибки</button></div><div class="ops-job-heading"><span>Файл</span><span>Состояние</span></div><div class="ops-jobs"></div></article><article id="ops-events" class="ops-box"><div class="ops-section-head"><h2>События</h2><span class="ops-event-dot" aria-hidden="true"></span></div><ol class="ops-events"></ol></article></section>
</main><footer><span class="ops-cycle"></span></footer></div></div>`;
document.body.append(panel);$('.ops-close').onclick=()=>panel.close();$('.ops-mobile-close').onclick=()=>panel.close();$('.ops-brand').onclick=e=>e.preventDefault();$('.ops-refresh').onclick=()=>{clearTimeout(timer);void refresh();};
const navIcons=['overview','proxy','activity','image','clock'];
@@ -37,7 +39,25 @@ function init(){
$('#'+button.dataset.section).scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'instant':'smooth',block:'start'});
};});
panel.querySelectorAll('[data-icon]').forEach(card=>card.prepend(icon(card.dataset.icon)));
panel.addEventListener('close',()=>{clearTimeout(timer);abort?.abort();});
panel.querySelectorAll('[data-job-filter]').forEach(button=>button.addEventListener('click',()=>{
jobFilter=button.dataset.jobFilter;
panel.querySelectorAll('[data-job-filter]').forEach(item=>item.setAttribute('aria-pressed',String(item===button)));
renderJobs();
}));
const sections=[...panel.querySelectorAll('[data-section]')].map(button=>$('#'+button.dataset.section));
let scrollFrame=0;
panel.addEventListener('scroll',()=>{
if(scrollFrame)return;
scrollFrame=requestAnimationFrame(()=>{
scrollFrame=0;const top=panel.getBoundingClientRect().top+Math.min(170,panel.clientHeight*.3);
let active=sections[0];for(const section of sections)if(section.getBoundingClientRect().top<=top)active=section;
panel.querySelectorAll('[data-section]').forEach(button=>{
const selected=button.dataset.section===active.id;button.classList.toggle('is-active',selected);
if(selected)button.setAttribute('aria-current','location');else button.removeAttribute('aria-current');
});
});
},{passive:true});
const currentPanel=panel;panel.addEventListener('close',()=>{if(panel===currentPanel&&!currentPanel.open){clearTimeout(timer);abort?.abort();}});
}
function chart(target,key,color){
const host=$(target);host.replaceChildren();const ns='http://www.w3.org/2000/svg';
@@ -57,7 +77,7 @@ function chart(target,key,color){
svg.append(shape('polyline',{points:line,stroke:color,'stroke-width':2.5,fill:'none','stroke-linejoin':'round','stroke-linecap':'round'}));
for(let i=0;i<points.length;i++){
const circle=shape('circle',{cx:points[i][0],cy:points[i][1],r:i===points.length-1?4:7,fill:i===points.length-1?color:'transparent',class:'ops-chart-point'});
const title=shape('title',{});title.textContent=`${new Date(samples[i].at).toLocaleTimeString()} · ${values[i]}${key==='latency'?' мс':' заданий'}`;circle.append(title);svg.append(circle);
circle.setAttribute('aria-hidden','true');const title=shape('title',{});title.textContent=`${new Date(samples[i].at).toLocaleTimeString()} · ${values[i]}${key==='latency'?' мс':' заданий'}`;circle.append(title);svg.append(circle);
}
}
host.append(svg);const caption=node('div',undefined,'ops-chart-caption');caption.append(node('span',samples.length?new Date(samples[0].at).toLocaleTimeString():'…'),node('span','Макс. '+Math.round(Math.max(0,...values))),node('span',samples.length?new Date(samples.at(-1).at).toLocaleTimeString():'…'));host.append(caption);
@@ -65,6 +85,20 @@ function chart(target,key,color){
const serviceIcons={PostgreSQL:'database',Redis:'cache',S3:'storage',RabbitMQ:'queue',Dispatcher:'dispatcher',Worker:'worker'};
function service(name,up,detail){const card=node('div',undefined,'ops-service');card.dataset.state=up?'up':'down';card.append(icon(serviceIcons[name]||'api'),node('span',up?'На связи':'Нет ответа','ops-service-status'),node('strong',name),node('small',detail));return card;}
function stale(message){$('.ops-notice').textContent=message;panel.classList.add('is-stale');$('.ops-live').textContent='Нет свежих данных';for(const item of panel.querySelectorAll('[data-state]'))item.dataset.state='unknown';for(const label of panel.querySelectorAll('.ops-service-status'))label.textContent='Нет данных';}
function renderJobs(){
const jobs=$('.ops-jobs');const signature=jobFilter+JSON.stringify(lastJobs);
if(jobs.dataset.signature===signature)return;
jobs.dataset.signature=signature;jobs.replaceChildren();
const visible=lastJobs.filter(job=>jobFilter==='all'||(jobFilter==='active'&&['queued','processing'].includes(job.state))||(jobFilter==='failed'&&job.state==='failed'));
if(!visible.length)jobs.append(node('p',lastJobs.length?'Нет заданий в этой категории':'Загрузите изображение в чат. Здесь появится его задание.','ops-empty'));
for(const job of visible){
const row=node('div',undefined,'ops-job'),info=node('div');
info.append(node('strong',job.filename),node('small',`Попыток: ${job.attempts}${job.error_code?' · '+job.error_code:''}`));
row.append(icon('image'),info,node('span',labels[job.state]||job.state,'ops-job-state '+job.state));
if(job.can_replay){const button=node('button','Повторить');button.type='button';button.onclick=()=>replay(job.attachment_id,button);row.append(button);}
jobs.append(row);
}
}
async function refresh(){
if(!panel?.open||!token)return;if(document.hidden){timer=setTimeout(refresh,3000);return;}
if(abort&&!abort.signal.aborted)abort.abort();abort=new AbortController();const version=epoch,session=token,signal=abort.signal;const started=performance.now();
@@ -76,7 +110,7 @@ async function refresh(){
panel.classList.remove('is-stale');$('.ops-live').textContent='Данные обновлены';$('.ops-notice').textContent='';
if(!matchMedia('(prefers-reduced-motion: reduce)').matches)panel.querySelectorAll('.ops-arrow').forEach((arrow,index)=>arrow.querySelector('i')?.animate([{opacity:0,transform:'translateX(0)'},{opacity:1,offset:.25},{opacity:0,transform:`translateX(${arrow.clientWidth-5}px)`}],{duration:850,delay:index*170,easing:'ease-in-out'}));
$('.ops-checked').textContent='Проверено '+new Date(data.checked_at).toLocaleTimeString();
$('.ops-metrics').replaceChildren(...Object.entries(labels).map(([key,label])=>{const card=node('article');card.dataset.kind=key;card.append(icon({queued:'clock',processing:'worker',ready:'check',failed:'error'}[key]),node('span',label),node('strong',String(data.counts[key])));return card;}));
const metrics=$('.ops-metrics'),metricsSignature=JSON.stringify(data.counts);if(metrics.dataset.signature!==metricsSignature){metrics.dataset.signature=metricsSignature;metrics.replaceChildren(...Object.entries(labels).map(([key,label])=>{const card=node('article');card.dataset.kind=key;card.append(icon({queued:'clock',processing:'worker',ready:'check',failed:'error'}[key]),node('span',label),node('strong',String(data.counts[key])));return card;}));}
const apis=$('.ops-api-nodes');data.instances.filter(n=>n.ready).forEach(n=>knownInstances.add(n.id));
const instances=data.instances.filter(n=>n.ready||knownInstances.has(n.id));
apis.replaceChildren(...instances.map(n=>service('API · '+n.id.slice(0,8),n.ready,'Heartbeat · '+new Date(n.last_seen).toLocaleTimeString())));
@@ -87,9 +121,8 @@ async function refresh(){
$('.ops-queue-value').textContent=String(samples.at(-1).queue);$('.ops-latency-value').textContent=elapsed+' мс';chart('.ops-queue-chart','queue','#ffe135');chart('.ops-latency-chart','latency','#a6cf9a');
$('.ops-cycle').textContent=`Outbox: ${data.pending_outbox} · Средний цикл за 15 мин: ${data.average_cycle_seconds===null?'нет завершённых заданий':data.average_cycle_seconds.toFixed(2)+' с'}`;
$('.ops-job-count').textContent='Последние '+data.jobs.length;
const jobs=$('.ops-jobs');const jobSignature=JSON.stringify(data.jobs);if(jobs.dataset.signature!==jobSignature){jobs.dataset.signature=jobSignature;jobs.replaceChildren();if(!data.jobs.length)jobs.append(node('p','Загрузите изображение в чат. Здесь появится его задание.','ops-empty'));
for(const job of data.jobs){const row=node('div',undefined,'ops-job');const info=node('div');info.append(node('strong',job.filename),node('small',`${labels[job.state]} · попыток ${job.attempts}${job.error_code?' · '+job.error_code:''}`));info.querySelector('small').textContent=`Попыток: ${job.attempts}${job.error_code?' · '+job.error_code:''}`;row.append(icon('image'),info,node('span',labels[job.state],'ops-job-state '+job.state));if(job.can_replay){const button=node('button','Повторить');button.type='button';button.onclick=()=>replay(job.attachment_id,button);row.append(button);}jobs.append(row);}}
const list=$('.ops-events');list.replaceChildren();for(const event of data.events){const item=node('li');item.append(node('time',new Date(event.at).toLocaleTimeString()),node('strong',eventLabels[event.name]||event.name),node('span',event.filename));list.append(item);}if(!data.events.length)list.append(node('li','Событий пока нет'));
lastJobs=data.jobs;renderJobs();
const list=$('.ops-events'),eventSignature=JSON.stringify(data.events);if(list.dataset.signature!==eventSignature){list.dataset.signature=eventSignature;list.replaceChildren();for(const event of data.events){const item=node('li');item.append(node('time',new Date(event.at).toLocaleTimeString()),node('strong',eventLabels[event.name]||event.name),node('span',event.filename));list.append(item);}if(!data.events.length)list.append(node('li','Событий пока нет'));}
}catch(error){if(version===epoch&&panel.open&&!signal.aborted)stale(error.message);}finally{if(version===epoch&&panel?.open){clearTimeout(timer);timer=setTimeout(refresh,3000);}}
}
async function replay(id,button){button.disabled=true;button.textContent='Запускаем…';try{const response=await fetch(`/api/ui/operations/attachments/${id}/replay`,{method:'POST',headers:{Authorization:'Bearer '+token},signal:AbortSignal.timeout(10000)});const data=await response.json();if(!response.ok)throw new Error(data.error?.message||'Повтор недоступен');clearTimeout(timer);await refresh();}catch(error){$('.ops-notice').textContent=error.message;button.disabled=false;button.textContent='Повторить';}}