This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 17:36:53 +01:00
1 parent 5b6d4a7903
commit 4d1087e357
160 files changed
+2407 -1933

No files matched your search

+67 -35
View File
@@ -44,72 +44,104 @@
function renderDonut(id, entries, enabled = true) {
const chart = $(`traffic-chart-${id}`), legend = $(`traffic-chart-${id}-legend`), totalNode = $(`traffic-chart-${id}-total`);
if (!chart || !legend || !totalNode) return;
if (!chart || !legend) return;
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled);
const total = values.reduce((sum, item) => sum + Number(item.count || 0), 0);
totalNode.textContent = number(total); if (empty) empty.hidden = total > 0;
if (totalNode) totalNode.textContent = number(total); if (empty) empty.hidden = total > 0;
if (!total) {
chart.style.background = "var(--chart-surface)"; chart.setAttribute("aria-label", t("trafficNoData"));
chart.replaceChildren(); chart.classList.add("is-empty"); chart.setAttribute("aria-label", t("trafficNoData"));
legend.replaceChildren(el("li", t("trafficNoData"), "fine")); return;
}
chart.classList.remove("is-empty");
const shown = values.slice(0, 7).map(item => ({ value: item.value || "-", count: Number(item.count) || 0 }));
if (values.length > shown.length) shown.push({ value: t("trafficOther"), count: values.slice(shown.length).reduce((sum, item) => sum + Number(item.count || 0), 0) });
let cursor = 0;
chart.style.background = `conic-gradient(${shown.map((item, index) => {
const start = cursor / total * 100; cursor += item.count; const end = cursor / total * 100;
return `${chartPalette[index % chartPalette.length]} ${start.toFixed(4)}% ${end.toFixed(4)}%`;
}).join(", ")})`;
if (values.length > shown.length) shown.push({ value: t("trafficOther"), count: values.slice(shown.length).reduce((sum, item) => sum + Number(item.count || 0), 0), other: true });
chart.replaceChildren(...shown.map((item, index) => {
const part = el("i"); part.style.width = `${(item.count / total * 100).toFixed(3)}%`; part.style.background = chartPalette[index % chartPalette.length];
part.title = `${item.value}: ${number(item.count)} (${(item.count / total * 100).toFixed(1)}%)`; return part;
}));
const heading = chart.closest(".traffic-chart-card")?.querySelector("h3")?.textContent || t("trafficDimensionsTitle");
chart.setAttribute("aria-label", `${heading}: ${shown.map(item => `${item.value} ${Math.round(item.count / total * 100)}%`).join(", ")}`);
legend.replaceChildren(...shown.map((item, index) => {
const row = el("li"), label = el("span"), swatch = el("i", undefined, "traffic-chart-swatch");
swatch.style.background = chartPalette[index % chartPalette.length];
const text = copyButton(item.value || "-", "traffic-chart-label"); text.title = `${t("copyValue")}: ${item.value || "-"}`;
label.append(swatch, text); row.append(label, el("b", `${(item.count / total * 100).toFixed(1)}%`)); return row;
const text = item.other ? el("span", item.value, "traffic-chart-label") : copyButton(item.value || "-", "traffic-chart-label"); if (!item.other) text.title = `${t("copyValue")}: ${item.value || "-"}`;
label.append(swatch, text); row.append(label, el("b", number(item.count)), el("span", `${(item.count / total * 100).toFixed(1)}%`, "traffic-share")); return row;
}));
}
function renderBars(id, entries, enabled = true, formatter = number) {
function renderBars(id, entries, enabled = true, formatter = number, options = {}) {
const chart = $(`traffic-chart-${id}`); if (!chart) return;
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled).slice(0, 12);
const total = values.reduce((sum, item) => sum + Number(item.count || 0), 0), peak = Math.max(1, ...values.map(item => Number(item.count) || 0));
const empty = $(`traffic-chart-${id}-empty`), values = chartEntries(entries, enabled).slice(0, options.limit || 12);
const listed = values.reduce((sum, item) => sum + Number(item.count || 0), 0), peak = Math.max(1, ...values.map(item => Number(item.count) || 0));
const total = Math.max(listed, Number(options.share) || 0);
if (empty) empty.hidden = values.length > 0;
chart.replaceChildren(...values.map(item => {
const count = Number(item.count) || 0, row = el("div", undefined, "traffic-bar-row");
const label = copyButton(item.value || "-", "traffic-bar-label"); label.title = `${t("copyValue")}: ${item.value || "-"}`;
const track = el("span", undefined, "traffic-bar-track"), fill = el("i", undefined, "traffic-bar-fill"); fill.style.width = `${Math.max(1.5, count / peak * 100)}%`; track.append(fill);
const value = el("span", formatter(count), "traffic-bar-value"); value.title = total ? `${(count / total * 100).toFixed(1)}%` : "";
row.append(label, track, value); return row;
const rows = values.map(item => ({ value: item.value || "-", count: Number(item.count) || 0 }));
if (options.share && values.length && total > listed) rows.push({ value: t("trafficOther"), count: total - listed, other: true });
chart.replaceChildren(...rows.map(item => {
const count = item.count, row = el("div", undefined, `traffic-bar-row${item.other ? " is-other" : ""}`);
const label = item.other ? el("span", item.value, "traffic-bar-label") : copyButton(item.value, "traffic-bar-label"); if (!item.other) label.title = `${t("copyValue")}: ${item.value}`;
const track = el("span", undefined, "traffic-bar-track"), fill = el("i", undefined, "traffic-bar-fill"); fill.style.width = `${Math.max(1.5, Math.min(100, count / (item.other ? total : peak) * 100))}%`; track.append(fill);
const value = el("span", formatter(count), "traffic-bar-value"), share = el("span", total ? `${(count / total * 100).toFixed(1)}%` : "", "traffic-share");
row.append(label, value, share, track); return row;
}));
chart.setAttribute("aria-label", values.length ? values.map(item => `${item.value}: ${formatter(Number(item.count) || 0)}`).join(", ") : t("trafficNoData"));
}
function renderCapture(settings, geoip) {
const box = $("traffic-capture-status"); if (!box) return;
const pill = (key, on) => { const node = el("span", t(key), `pill${on ? " live" : ""}`); node.dataset.i18n = key; return node; };
const country = settings.capture_country ? (geoip?.loaded ? ["trafficCountryEnabled", true] : ["trafficCountryNoDb", false]) : ["trafficCountryDisabled", false];
const open = el("button", t("trafficOpenCaptureSettings"), "quiet traffic-capture-open"); open.type = "button"; open.dataset.i18n = "trafficOpenCaptureSettings"; open.dataset.trafficOpenSettings = "logging"; open.dataset.uiIconName = "settings"; open.addEventListener("click", openCaptureSettings);
box.replaceChildren(pill(settings.capture_user_agent ? "trafficUserAgentEnabled" : "trafficUserAgentDisabled", !!settings.capture_user_agent), pill(country[0], country[1]), open);
}
function openCaptureSettings() { setPanel("settings"); window.rustProxySettings?.select("logging"); }
function render(data) {
lastData = data; configure(data);
const analytics = data.analytics || {}, stats = analytics.data || {}, settings = data.settings || {};
$("traffic-requests").textContent = number(stats.requests); $("traffic-errors").textContent = number(stats.errors);
const requests = Number(stats.requests) || 0, errors = Number(stats.errors) || 0;
$("traffic-error-ratio").textContent = `${requests ? (errors / requests * 100).toFixed(2) : "0.00"}%`;
$("traffic-error-ratio").textContent = `${requests ? (errors / requests * 100).toFixed(2) : "0.00"}% ${t("trafficOfRequests")}`;
$("traffic-response-bytes").textContent = fmtBytes(Number(stats.response_bytes) || 0);
$("traffic-request-bytes").textContent = `${t("trafficRequestBytes")}: ${fmtBytes(Number(stats.request_bytes) || 0)}`;
$("traffic-latency").textContent = stats.mean_duration_ms == null ? "-" : `${fmt(stats.mean_duration_ms, 2)} ms`;
$("traffic-dropped").textContent = `${t("trafficDroppedSamples")}: ${number(analytics.queue_dropped)}`;
const capture = [settings.capture_user_agent ? t("trafficUserAgentEnabled") : t("trafficUserAgentDisabled")];
capture.push(settings.capture_country ? (data.geoip?.loaded ? t("trafficCountryEnabled") : t("trafficCountryNoDb")) : t("trafficCountryDisabled"));
$("traffic-capture-status").textContent = capture.join(" · ");
$("traffic-dropped").textContent = number(analytics.queue_dropped);
$("traffic-dropped-help").textContent = Number(analytics.queue_dropped) ? t("trafficDroppedSome") : t("trafficDroppedNone");
document.querySelector(".traffic-kpi-errors")?.classList.toggle("is-warn", errors > 0);
renderCapture(settings, data.geoip);
renderDonut("countries", stats.countries, !!settings.capture_country);
renderBars("user-agents", stats.user_agents, !!settings.capture_user_agent);
renderBars("client-ips", stats.client_ips);
renderBars("paths", stats.paths); renderBars("routes", stats.routes);
const share = requests;
renderBars("countries", stats.countries, !!settings.capture_country, number, { share });
const countryEmpty = $("traffic-chart-countries-empty"); if (countryEmpty) countryEmpty.hidden = chartEntries(stats.countries, !!settings.capture_country).length > 0;
renderBars("user-agents", stats.user_agents, !!settings.capture_user_agent, number, { share });
renderBars("client-ips", stats.client_ips, true, number, { share });
renderBars("client-ips-overview", stats.client_ips, true, number, { share, limit: 5 });
renderBars("paths", stats.paths, true, number, { share }); renderBars("paths-overview", stats.paths, true, number, { share, limit: 5 });
renderBars("routes", stats.routes, true, number, { share });
renderDonut("methods", stats.methods); renderDonut("methods-detail", stats.methods);
renderDonut("statuses", stats.statuses); renderDonut("statuses-detail", stats.statuses);
renderDonut("cache", stats.cache); renderDonut("cache-detail", stats.cache);
renderBars("volume", [
{ value: t("trafficRequestBytes"), count: Number(stats.request_bytes) || 0 },
{ value: t("trafficResponseBytes"), count: Number(stats.response_bytes) || 0 },
{ value: t("trafficRequestBytes"), count: Number(stats.request_bytes) || 0 },
], true, fmtBytes);
$("traffic-panel-state").textContent = `${t("trafficUpdated")}: ${formatTime(new Date())}`;
renderRecent();
}
const RECENT_KEY = "rustproxy.traffic.recent";
function readRecent() { try { const value = JSON.parse(localStorage.getItem(RECENT_KEY) || "[]"); return Array.isArray(value) ? value.filter(item => typeof item === "string").slice(0, 3) : []; } catch { return []; } }
function rememberScope(value) { if (!value || value === "*") return; try { localStorage.setItem(RECENT_KEY, JSON.stringify([value, ...readRecent().filter(item => item !== value)].slice(0, 3))); } catch { } }
function renderRecent() {
const box = $("traffic-recent"); if (!box) return;
const select = $("traffic-scope"), known = new Set([...select.options].map(option => option.value));
const chips = ["*", ...readRecent().filter(value => known.has(value))].map(value => {
const chip = el("button", value === "*" ? t("logAllVhosts") : value, "traffic-recent-chip"); chip.type = "button"; chip.dataset.uiIconName = "none";
chip.setAttribute("aria-pressed", String(select.value === value));
chip.addEventListener("click", () => { if (select.value === value) return; select.value = value; select.dispatchEvent(new Event("change", { bubbles: true })); });
return chip;
});
box.replaceChildren(...(chips.length > 1 ? chips : []));
}
async function loadTraffic({ signal, isCurrent }) {
@@ -121,8 +153,6 @@
try {
data = await api(staticData ? `${base}&view=live` : base, { signal });
} catch (error) {
// Labels are inventory-derived. If the selected publication
// vanished, fall back to All rather than polling a stale ID.
if (error?.status !== 404 || scope() === "*") throw error;
$("traffic-scope").value = "*";
staticData = null; staticRevision = null;
@@ -149,7 +179,7 @@
document.querySelectorAll(".traffic-bar-chart").forEach(chart => chart.replaceChildren());
for (const id of ["countries", "methods", "methods-detail", "statuses", "statuses-detail", "cache", "cache-detail"]) {
const chart = $(`traffic-chart-${id}`), legend = $(`traffic-chart-${id}-legend`), total = $(`traffic-chart-${id}-total`);
if (chart) chart.style.background = "var(--chart-surface)"; legend?.replaceChildren(); if (total) total.textContent = "-";
chart?.replaceChildren(); legend?.replaceChildren(); if (total) total.textContent = "-";
}
selectTab("overview");
}
@@ -165,8 +195,10 @@
event.preventDefault(); selectTab(trafficTabs[next].dataset.trafficTab); trafficTabs[next].focus();
});
});
$("traffic-refresh")?.addEventListener("click", () => void refresh()); $("traffic-scope")?.addEventListener("change", () => void refresh());
$("traffic-settings")?.addEventListener("click", () => { setPanel("settings"); window.rustProxySettings?.select("logging"); });
$("traffic-refresh")?.addEventListener("click", () => void refresh()); $("traffic-scope")?.addEventListener("change", () => { rememberScope($("traffic-scope").value); renderRecent(); void refresh(); });
$("traffic-settings")?.addEventListener("click", openCaptureSettings);
document.querySelectorAll("[data-traffic-more]").forEach(button => button.addEventListener("click", () => selectTab(button.dataset.trafficMore)));
document.querySelectorAll("#panel-traffic button[data-traffic-open-settings]").forEach(button => button.addEventListener("click", openCaptureSettings));
rustProxyRefresh.register("traffic", {
interval: () => rustProxyRefresh.current().traffic_seconds,
active: () => currentPanel === "traffic" && !!$("traffic-live")?.checked,