Реализовать лабораторную работу 4
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
// Only explicitly selected HTTP metadata reaches this view. Never pass request
|
||||
// headers, bodies, session objects or raw response JSON into the panel.
|
||||
import { observeClusterRequest, setClusterIdentity } from '/cluster-view.js';
|
||||
const $ = id => document.getElementById(id);
|
||||
const preferenceKey = "n1k0der.diagnostics";
|
||||
const requests = [];
|
||||
let session = null, history = null, backgroundRequest = null, returnFocus = null;
|
||||
|
||||
function setOpen(open) {
|
||||
$("diagnostics-panel").hidden = !open;
|
||||
document.body.classList.toggle("diagnostics-open", open);
|
||||
document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.setAttribute("aria-expanded", String(open)));
|
||||
try { sessionStorage.setItem(preferenceKey, open ? "on" : "off"); } catch { /* optional preference */ }
|
||||
if (open) { render(); $("diagnostics-close").focus(); }
|
||||
else if (returnFocus?.isConnected) returnFocus.focus();
|
||||
}
|
||||
|
||||
document.querySelectorAll("[data-diagnostics-toggle]").forEach(button => button.addEventListener("click", () => {
|
||||
returnFocus = button;
|
||||
setOpen($("diagnostics-panel").hidden);
|
||||
}));
|
||||
$("diagnostics-close").addEventListener("click", () => setOpen(false));
|
||||
document.addEventListener("keydown", event => {
|
||||
if (event.key === "Escape" && !$("diagnostics-panel").hidden && !document.querySelector("dialog[open]")) {
|
||||
event.preventDefault(); setOpen(false);
|
||||
}
|
||||
});
|
||||
|
||||
export function updateSessionInfo(value) {
|
||||
setClusterIdentity(Boolean(value));
|
||||
session = value ? { name: value.name, expiresAt: value.expiresAt } : null;
|
||||
document.body.classList.toggle("has-session", Boolean(session));
|
||||
if (!$("diagnostics-panel").hidden) renderSession();
|
||||
}
|
||||
|
||||
export function updateHistoryInfo(value) {
|
||||
history = value ? { title: value.title, loaded: value.loaded, hasOlder: value.hasOlder, ready: value.ready } : null;
|
||||
if (!$("diagnostics-panel").hidden) renderHistory();
|
||||
}
|
||||
|
||||
export function recordRequest(value) {
|
||||
const entry = {
|
||||
method: value.method, path: value.path.split("?")[0], status: value.status,
|
||||
authorization: value.authorization, durationMs: value.durationMs,
|
||||
requestId: value.requestId, instanceId: value.instanceId, outcome: value.outcome, source: value.source, at: new Date()
|
||||
};
|
||||
observeClusterRequest(entry);
|
||||
if (value.background) backgroundRequest = entry;
|
||||
else { requests.unshift(entry); requests.length = Math.min(requests.length, 4); }
|
||||
if (!$("diagnostics-panel").hidden) renderRequests();
|
||||
}
|
||||
|
||||
function renderSession() {
|
||||
$("diagnostics-user").textContent = session?.name || "Вход не выполнен";
|
||||
const seconds = session ? Math.max(0, Math.ceil((new Date(session.expiresAt).getTime() - Date.now()) / 1000)) : null;
|
||||
$("diagnostics-session").textContent = seconds === null ? "-" : seconds === 0 ? "Срок истёк" : `${Math.floor(seconds / 60)} мин ${String(seconds % 60).padStart(2, "0")} с`;
|
||||
}
|
||||
|
||||
function renderHistory() {
|
||||
$("diagnostics-chat").textContent = history?.title || "Выберите чат";
|
||||
$("diagnostics-messages").textContent = history
|
||||
? `Загружено: ${history.loaded} · ${!history.ready ? "страница ещё не получена" : history.hasOlder ? "есть старые сообщения ↑" : "старых страниц нет"}`
|
||||
: "Сообщения ещё не загружены";
|
||||
}
|
||||
|
||||
function result(entry) {
|
||||
if (entry.status === null) return "Ответ не получен: соединение или таймаут. Результат записи может быть неизвестен.";
|
||||
if (entry.outcome === "unreadable") return "HTTP-ответ получен, но его данные не удалось прочитать.";
|
||||
if (entry.status === 204 && entry.method === "DELETE" && entry.path === "/api/v1/auth/sessions/current") return "Сессия отозвана. Ответ без тела.";
|
||||
return ({200: "Запрос выполнен", 201: "Объект создан", 204: "Выполнено без тела ответа",
|
||||
400: "Некорректные данные", 401: "Нужен действующий вход", 404: "Ресурс отсутствует или недоступен",
|
||||
409: "Конфликт данных", 415: "Неподдерживаемый формат", 503: "Сервис временно недоступен",
|
||||
500: "Внутренняя ошибка сервера"})[entry.status] || `HTTP ${entry.status}`;
|
||||
}
|
||||
|
||||
function shortPath(path) { return path.replace(/\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?=\/|$)/gi, "/…"); }
|
||||
|
||||
function renderRequests() {
|
||||
const current = requests[0];
|
||||
$("diagnostics-empty").hidden = Boolean(current);
|
||||
$("diagnostics-request-details").hidden = !current;
|
||||
$("diagnostics-request-time").textContent = current ? current.at.toLocaleTimeString("ru-RU") : "";
|
||||
if (current) {
|
||||
const failed = current.status === null || current.status >= 400 || current.outcome === "unreadable";
|
||||
$("diagnostics-method").textContent = current.method;
|
||||
$("diagnostics-status").textContent = current.status ?? "Нет ответа";
|
||||
$("diagnostics-status").classList.toggle("failed", failed);
|
||||
$("diagnostics-origin").textContent = current.source || "Основной интерфейс";
|
||||
$("diagnostics-path").textContent = shortPath(current.path);
|
||||
$("diagnostics-path").title = current.path;
|
||||
$("diagnostics-result").textContent = result(current);
|
||||
$("diagnostics-result").classList.toggle("failed", failed);
|
||||
$("diagnostics-auth").textContent = current.authorization;
|
||||
$("diagnostics-duration").textContent = `${current.durationMs} мс`;
|
||||
$("diagnostics-request-id").textContent = current.requestId || "Не получен";
|
||||
$("diagnostics-instance-id").textContent = current.instanceId || "Не получен";
|
||||
}
|
||||
const previous = requests.slice(1).map(entry => {
|
||||
const item = document.createElement("li");
|
||||
const status = document.createElement("span"); status.textContent = entry.status ?? "-";
|
||||
status.className = "diagnostics-mini-status" + (entry.status === null || entry.status >= 400 ? " failed" : "");
|
||||
const route = document.createElement("code"); route.textContent = `${entry.method} ${shortPath(entry.path)}`;
|
||||
route.title = entry.path; item.append(status, route); return item;
|
||||
});
|
||||
$("diagnostics-previous").replaceChildren(...previous);
|
||||
$("diagnostics-previous").hidden = previous.length === 0;
|
||||
$("diagnostics-background").hidden = !backgroundRequest;
|
||||
if (backgroundRequest) $("diagnostics-background").textContent = `Фоновый запрос: ${backgroundRequest.status ?? "нет ответа"} · ${backgroundRequest.durationMs} мс · ${backgroundRequest.at.toLocaleTimeString("ru-RU")}`;
|
||||
}
|
||||
|
||||
function render() { renderSession(); renderHistory(); renderRequests(); }
|
||||
setInterval(() => { if (!$("diagnostics-panel").hidden) renderSession(); }, 1000);
|
||||
try { if (sessionStorage.getItem(preferenceKey) === "on") setOpen(true); } catch { /* optional preference */ }
|
||||
Reference in New Issue
Block a user