"use strict"; (() => { let loading = false, lastData = null, activeTab = "overview", staticData = null, staticRevision = null; const chartPalette = ["var(--chart-accent)", "var(--chart-secondary)", "var(--chart-tertiary)", "var(--chart-quaternary)", "var(--chart-quinary)", "var(--chart-senary)", "var(--chart-septenary)", "var(--chart-octonary)"]; const scope = () => $("traffic-scope")?.value || "*"; const number = value => fmt(Number(value) || 0); async function copyText(value) { if (navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(value); toast(t("copied")); return; } catch { } } const area = document.createElement("textarea"); area.value = value; area.setAttribute("readonly", ""); area.style.position = "fixed"; area.style.opacity = "0"; document.body.append(area); area.select(); document.execCommand("copy"); area.remove(); toast(t("copied")); } function copyButton(value, className) { const button = el("button", value || "-", `${className} traffic-copy-value`); button.type = "button"; button.title = t("copyValue"); button.addEventListener("click", () => void copyText(value || "-")); return button; } function selectTab(name) { activeTab = name; document.querySelectorAll("[data-traffic-tab]").forEach(button => { const active = button.dataset.trafficTab === name; button.classList.toggle("active", active); button.setAttribute("aria-selected", String(active)); button.tabIndex = active ? 0 : -1; }); document.querySelectorAll("[data-traffic-page]").forEach(page => { page.hidden = page.dataset.trafficPage !== name; }); } function configure(data) { const selected = scope(), options = [el("option", t("logAllVhosts"))]; options[0].value = "*"; for (const vhost of data.vhosts || []) { const option = el("option", vhost.label || `${vhost.id} / ${(vhost.hosts || []).join(", ")}`); option.value = vhost.id; option.title = vhost.id; options.push(option); } $("traffic-scope").replaceChildren(...options); $("traffic-scope").value = options.some(option => option.value === selected) ? selected : "*"; } function chartEntries(entries, enabled = true) { return (enabled ? (entries || []) : []).filter(item => Number(item.count) > 0); } function renderDonut(id, entries, enabled = true) { const chart = $(`traffic-chart-${id}`), legend = $(`traffic-chart-${id}-legend`), totalNode = $(`traffic-chart-${id}-total`); 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); if (totalNode) totalNode.textContent = number(total); if (empty) empty.hidden = total > 0; if (!total) { 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), 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 = 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, options = {}) { const chart = $(`traffic-chart-${id}`); if (!chart) return; 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; 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"}% ${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 = 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); 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("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 }) { if (!authenticated || currentPanel !== "traffic" || loading) return; loading = true; try { const base = `/api/traffic?vhost=${encodeURIComponent(scope())}`; let data; try { data = await api(staticData ? `${base}&view=live` : base, { signal }); } catch (error) { if (error?.status !== 404 || scope() === "*") throw error; $("traffic-scope").value = "*"; staticData = null; staticRevision = null; data = await api("/api/traffic?vhost=*", { signal }); } if (staticData && (data.revision !== staticRevision || data.catalog_version !== staticData.catalog_version)) { data = await api(base, { signal }); } if (Array.isArray(data.vhosts)) { staticData = { vhosts: data.vhosts, catalog_version: data.catalog_version }; staticRevision = data.revision; } else if (staticData) { data = { ...staticData, ...data }; } if (isCurrent()) render(data); } catch (error) { if (error?.name !== "AbortError" && isCurrent()) $("traffic-panel-state").textContent = error.message; } finally { loading = false; } } function refresh() { return rustProxyRefresh.manual("traffic"); } function reset() { lastData = null; staticData = null; staticRevision = null; if ($("traffic-panel-state")) $("traffic-panel-state").textContent = ""; 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`); chart?.replaceChildren(); legend?.replaceChildren(); if (total) total.textContent = "-"; } selectTab("overview"); } const trafficTabs = [...document.querySelectorAll("[data-traffic-tab]")]; trafficTabs.forEach(button => { button.addEventListener("click", () => selectTab(button.dataset.trafficTab)); button.addEventListener("keydown", event => { const index = trafficTabs.indexOf(button); let next; if (event.key === "ArrowRight" || event.key === "ArrowDown") next = (index + 1) % trafficTabs.length; else if (event.key === "ArrowLeft" || event.key === "ArrowUp") next = (index + trafficTabs.length - 1) % trafficTabs.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = trafficTabs.length - 1; else return; event.preventDefault(); selectTab(trafficTabs[next].dataset.trafficTab); trafficTabs[next].focus(); }); }); $("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, run: loadTraffic }); $("traffic-live")?.addEventListener("change", () => rustProxyRefresh.sync()); selectTab(activeTab); window.rustProxyTrafficPanel = { refresh, reset, rerender: () => lastData && render(lastData), select: selectTab }; })();