Files
anonymous_github/public/script/admin-errors.js
T
Thomas DurieuxandClaude Opus 5.5 d3860f29ad fix(admin): group errors by code and service, list the routes that failed
- An issue is now one error code (or exception type) per service: one cause,
  such as a rate-limit burst, hits many routes. Rows show the most frequent
  route and "+N routes"; the issue page lists them with a count and a bar.
- The request header shows the viewer as a role ("Viewer: owner", "Viewer not
  signed in") beside the owner chip, with a user link only for another user.
- List meta parts no longer leave a lone separator when they wrap.
- The issue page shows the 10 latest occurrences and a "Show all" button
  instead of clipping the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:55:02 +00:00

448 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { nextTick } from "vue";
// Admin › Errors: one list of issues built server-side (GET /api/admin/errors/issues)
// from central logs, or from the Redis history when central logs do not answer.
// The page has three views in one route, driven by the URL query so they are
// deep-linkable and the browser Back button works:
// /admin/errors the issue list
// /admin/errors?issue=<id> one issue
// /admin/errors?issue=<id>&occurrence=n one occurrence (request view)
export const WINDOW_LABELS = { "15m": "last 15 min", "1h": "last hour", "6h": "last 6 h", "24h": "last 24 h" };
const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
const REPO_ID = /^[A-Za-z0-9_-]{3,200}$/;
const USER_ID = /^[a-f0-9]{24}$/;
const SIGNED_IN = { owner: "Owner", coauthor: "Co-author", admin: "Admin" };
/** Splits the search box into server filters (repo:<id>, user:<id>) and free text. */
export function parseIssueSearch(text) {
const out = { repoId: "", userId: "", free: "", invalid: "" };
const rest = [];
for (const token of String(text || "").trim().split(/\s+/).filter(Boolean)) {
const match = token.match(/^(repo|user):(.*)$/i);
if (!match) { rest.push(token); continue; }
const value = match[2];
if (match[1].toLowerCase() === "repo" && REPO_ID.test(value)) out.repoId = value;
else if (match[1].toLowerCase() === "user" && USER_ID.test(value)) out.userId = value;
else out.invalid = token;
}
out.free = rest.join(" ").toLowerCase();
return out;
}
export function issueMatches(issue, free) {
if (!free) return true;
const hay = [issue.title, issue.code, issue.service, issue.route, issue.method, issue.queue, issue.status, issue.cause?.label, issue.cause?.summary]
.filter(value => value !== null && value !== undefined).join(" ").toLowerCase();
return free.split(" ").every(word => hay.includes(word));
}
const statusOf = event => Number(event?.status || event?.httpStatus) || 0;
const time = value => Date.parse(value);
const isExternal = event => event?.event === "external_request";
const DATA = new Set(["mongodb", "redis"]);
/** Rows for the request waterfall: one per recorded event, positioned by timestamp and duration. */
export function waterfall(events, issue) {
const rows = (events || []).filter(event => Number.isFinite(time(event.timestamp))).map((event, index) => {
const end = time(event.timestamp);
const ms = Number(event.ms);
const start = Number.isFinite(ms) && ms >= 0 ? end - ms : end;
const external = isExternal(event);
const host = String(event.upstreamHost || "");
const kind = external ? "external" : DATA.has(event.service) ? "data" : event.service === "nginx" ? "edge" : "app";
const label = external ? `${host === "storage" ? "Storage" : /github/.test(host) ? "GitHub" : "External"}${event.upstreamMethod ? " · " + event.upstreamMethod : ""}`
: event.errorCode || event.errorType || String(event.event || "event").replace(/_/g, " ");
const sub = external ? (event.upstreamEndpoint || host || "endpoint not recorded")
: [event.service, event.route || (event.queue ? "job " + event.queue : "")].filter(Boolean).join(" · ");
const status = external ? Number(event.upstreamStatus) || event.errorCode || "" : statusOf(event) || "";
const failed = external ? Number(event.upstreamStatus) >= 400 || !!event.errorCode : statusOf(event) >= 500 || event.severity === "error";
const failure = !external && !!issue && !["edge_request", "request_completed"].includes(event.event) &&
((issue.errorCode && event.errorCode === issue.errorCode) || (!issue.errorCode && issue.errorType && event.errorType === issue.errorType));
return { key: index, event, start, end, ms: Number.isFinite(ms) ? ms : null, kind, label, sub, status, failed, failure };
});
if (!rows.length) return { rows, span: 0 };
// Start order; at equal starts the enclosing (longer) step first.
rows.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));
rows.forEach((row, index) => { row.key = index; });
const min = Math.min(...rows.map(row => row.start)), max = Math.max(...rows.map(row => row.end));
const span = Math.max(1, max - min);
for (const row of rows) {
row.left = ((row.start - min) / span) * 100;
row.width = Math.max(0.6, ((row.end - row.start) / span) * 100);
if (row.left + row.width > 100) row.left = Math.max(0, 100 - row.width);
row.offset = Math.round(row.start - min);
}
if (!rows.some(row => row.failure)) {
const last = [...rows].reverse().find(row => row.failed && row.kind === "app");
if (last) last.failure = true;
}
return { rows, span: Math.round(span) };
}
/** Role-only chip for the request header: the owner is already linked beside it. */
export function viewerChip(viewer) {
if (!viewer) return "";
if (viewer === "visitor" || viewer === "anonymous") return "Viewer not signed in";
return `Viewer: ${(SIGNED_IN[viewer] || viewer).toLowerCase()}`;
}
/** Plain-language viewer label for #991's viewer field. */
export function viewerLabel(viewer) {
if (!viewer) return "";
if (SIGNED_IN[viewer]) return `Signed in as ${SIGNED_IN[viewer].toLowerCase()}`;
return "Viewer not signed in";
}
const relTime = (iso, now = Date.now()) => {
const t = time(iso);
if (!Number.isFinite(t)) return "";
const s = Math.max(0, Math.floor((now - t) / 1000));
if (s < 60) return "just now";
const m = Math.floor(s / 60);
if (m < 60) return `${m} min ago`;
const h = Math.floor(m / 60);
if (h < 24) return `${h} h ago`;
return `${Math.floor(h / 24)} d ago`;
};
const clock = (iso, seconds = false) => {
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? "" : d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", ...(seconds ? { second: "2-digit" } : {}), hour12: false });
};
const dayTime = iso => {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "";
const today = new Date().toDateString() === d.toDateString();
return (today ? "Today " : d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " · ") + clock(iso, true);
};
// Fills the fields the page reads, so a partial or unexpected answer renders as empty.
export function normalizeIssues(data) {
const value = data && typeof data === "object" && !Array.isArray(data) ? data : {};
return { source: "central", window: "24h", filters: {}, names: { repos: {}, users: {} }, captured: 0, ...value,
issues: Array.isArray(value.issues) ? value.issues : [],
expected: { count: 0, groups: [], ...(value.expected || {}) }, excluded: { slow: 0, interrupted: 0, ...(value.excluded || {}) },
summary: { issues: 0, failingNow: 0, failedRecords: 0, repositories: 0, users: 0, upstreamShare: 0, ...(value.summary || {}) } };
}
const fmtNumber = n => Number(n || 0).toLocaleString("en-US");
// Shared by the Errors page and the repository/user admin pages.
function installFormatters(state) {
state.errRelTime = iso => relTime(iso);
state.errClock = (iso, seconds) => clock(iso, seconds);
state.errDayTime = iso => dayTime(iso);
state.errNumber = fmtNumber;
state.errPlural = (n, word, many) => `${fmtNumber(n)} ${n === 1 ? word : (many || word + "s")}`;
state.errStatusClass = status => Number(status) >= 500 ? "is-error" : Number(status) >= 400 ? "is-warn" : "is-neutral";
state.errIssueHref = (id, extra = "") => `/admin/errors?issue=${encodeURIComponent(id)}${extra}`;
state.errRepoHref = id => `/admin/repositories?search=${encodeURIComponent(id)}`;
// Log records carry the internal _id; the admin user page takes it as "id:<_id>".
state.errUserHref = id => `/admin/users/id:${encodeURIComponent(id)}`;
state.errTrendMax = trend => Math.max(1, ...(trend || [0]));
state.viewerLabel = viewerLabel;
state.viewerChip = viewerChip;
}
/**
* Errors for one repository or user, shown on the admin Repositories (filtered to
* one repository) and User pages. `filter()` returns { repoId } or { userId } or null.
*/
export function installEntityErrors(state, http, filter, { onScopeDispose } = {}) {
installFormatters(state);
state.entityErrors = { loading: false, failed: false, data: null, key: "" };
let version = 0, disposed = false;
state.loadEntityErrors = async (force = false) => {
const params = filter();
const key = params ? JSON.stringify(params) : "";
if (!force && key === state.entityErrors.key) return;
const current = ++version;
state.entityErrors = { loading: !!params, failed: false, data: null, key };
if (!params) return;
try {
const response = await http.get("/api/admin/errors/issues", { params: { window: "24h", ...params } });
if (disposed || current !== version) return;
state.entityErrors = { loading: false, failed: false, data: normalizeIssues(response.data), key };
} catch {
if (!disposed && current === version) state.entityErrors = { loading: false, failed: true, data: null, key };
}
};
// Issues for this entity, the expected ones last and marked.
state.entityIssues = () => state.entityErrors.data?.issues || [];
state.entityFailingNow = () => state.entityIssues().filter(issue => issue.failingNow);
state.entityExpected = () => state.entityErrors.data?.expected?.groups || [];
const dispose = () => { disposed = true; version++; };
if (onScopeDispose) onScopeDispose(dispose); else state.on?.("dispose", dispose);
}
export const errorsAdminController = function (state, http, location, interval) {
state.watch("user.status", () => { if (state.user == null) location.url("/"); });
if (state.user == null) location.url("/");
installFormatters(state);
let version = 0, traceVersion = 0, statsVersion = 0, disposed = false;
let lastIssueId = null, lastOccurrence = null;
state.issueData = null;
state.issueLoading = true;
state.issueFailure = "";
state.issueFilters = { window: "24h", service: "", source: "auto" };
// ?q= pre-fills the search, so repository and user pages can link here filtered.
const initialQuery = location.search?.() || {};
state.issueSearch = typeof initialQuery.q === "string" ? initialQuery.q.slice(0, 200) : "";
state.errView = "list";
state.selectedIssue = null;
state.missingIssue = "";
state.showAllOccurrences = false;
state.occurrenceIndex = -1;
state.requestTab = "timeline";
state.trace = null;
state.traceLoading = false;
state.expandedSteps = {};
state.copyStatus = "";
state.settingsOpen = false;
state.telemetry = null;
state.telemetryState = "idle";
state.stats = null;
state.statsState = "idle";
state.redisCollecting = null;
state.windowLabels = WINDOW_LABELS;
const searchFilters = () => parseIssueSearch(state.issueSearch);
state.searchFilters = searchFilters;
state.visibleIssues = () => {
const { free } = searchFilters();
return (state.issueData?.issues || []).filter(issue => issueMatches(issue, free));
};
state.sourceLine = () => {
const data = state.issueData;
if (!data) return "";
const from = data.source === "central" ? "From central logs" : "From application history (Redis)";
return `${from} · ${WINDOW_LABELS[data.window] || data.window}`;
};
state.sourceNote = () => {
const data = state.issueData;
if (!data) return "";
if (data.source === "history" && data.centralState === "skipped") return "Central logs are not used while this switch is on.";
if (data.source === "history") return ({ disabled: "Central logs are not configured.", unreachable: "Central logs did not answer.", busy: "Central logs are busy.", misconfigured: "Central log configuration is invalid." })[data.centralState] || "";
if (data.state === "partial") return "Partial: a record limit or an invalid record reduced coverage.";
return "";
};
state.ownerOf = repoId => state.issueData?.names?.repos?.[repoId] || state.entityErrors?.data?.names?.repos?.[repoId] || null;
state.userName = userId => state.issueData?.names?.users?.[userId] || null;
async function load({ quiet = false } = {}) {
const current = ++version;
const search = searchFilters();
const params = { window: state.issueFilters.window };
if (state.issueFilters.service) params.service = state.issueFilters.service;
if (state.issueFilters.source === "history") params.source = "history";
if (search.repoId) params.repoId = search.repoId;
if (search.userId) params.userId = search.userId;
if (!quiet) state.issueLoading = true;
state.issueFailure = "";
try {
const response = await http.get("/api/admin/errors/issues", { params });
if (disposed || current !== version) return;
state.issueData = normalizeIssues(response.data);
state.redisCollecting = response.data?.redisCollecting !== false;
state.issueLoading = false;
syncFromRoute(false);
} catch (error) {
if (disposed || current !== version) return;
state.issueFailure = error?.status === 400 ? "These filters are not valid. Check repo: and user: values." : "Could not load errors. Check the connection and retry.";
} finally { if (!disposed && current === version) state.issueLoading = false; }
}
state.refreshIssues = () => load();
let serverKey = "";
const serverFilterKey = () => { const s = searchFilters(); return [state.issueFilters.window, state.issueFilters.service, state.issueFilters.source, s.repoId, s.userId].join("|"); };
state.applyFilters = () => { const key = serverFilterKey(); if (key !== serverKey) { serverKey = key; load(); } };
serverKey = serverFilterKey();
state.setSource = source => { state.issueFilters.source = source; state.applyFilters(); };
state.watch("issueFilters.window", () => state.applyFilters(), false, false);
state.watch("issueFilters.service", () => state.applyFilters(), false, false);
// repo:<id> and user:<id> are server filters; free text filters the loaded issues.
let searchTimer = null;
state.watch("issueSearch", () => { window.clearTimeout(searchTimer); searchTimer = window.setTimeout(() => { if (!disposed) state.applyFilters(); }, 300); }, false, false);
// ---- Views and routing -------------------------------------------------
const query = () => location.search?.() || {};
function syncFromRoute(moveFocus = true) {
const q = query();
const issueId = typeof q.issue === "string" ? q.issue : "";
if (!issueId) {
const was = state.errView;
state.errView = "list"; state.selectedIssue = null; state.occurrenceIndex = -1; state.missingIssue = "";
clearTrace();
if (moveFocus && was !== "list") focusRow();
return;
}
const issue = (state.issueData?.issues || []).find(item => item.id === issueId) || null;
if (issue?.id !== state.selectedIssue?.id) state.showAllOccurrences = false;
state.selectedIssue = issue;
state.missingIssue = issue || state.issueLoading ? "" : issueId;
const index = Number.parseInt(q.occurrence, 10);
const occurrence = issue && Number.isInteger(index) && index >= 0 && index < issue.occurrences.length ? index : -1;
const view = occurrence >= 0 ? "request" : "issue";
const changed = view !== state.errView || issueId !== lastIssueId || occurrence !== state.occurrenceIndex;
state.errView = view;
lastIssueId = issueId;
if (occurrence !== state.occurrenceIndex) { state.occurrenceIndex = occurrence; state.expandedSteps = {}; if (occurrence >= 0) loadTrace(); else clearTrace(); }
if (view === "request" && ["timeline", "request", "exception", "fields"].includes(q.tab)) state.requestTab = q.tab;
if (moveFocus && changed) focusHeading();
}
async function focusHeading() {
await nextTick();
if (disposed) return;
const heading = document.getElementById("errs-detail-title");
heading?.focus({ preventScroll: true });
const view = document.querySelector(".app-view");
if (view) view.scrollTop = 0;
}
async function focusRow() {
await nextTick();
if (disposed) return;
const link = lastIssueId && document.querySelector(`[data-issue-link="${lastIssueId}"]`);
if (link) { link.focus({ preventScroll: true }); link.scrollIntoView?.({ block: "nearest" }); }
else document.getElementById("errs-search")?.focus();
}
state.on("routeUpdate", () => syncFromRoute(true));
state.currentOccurrence = () => state.selectedIssue?.occurrences?.[state.occurrenceIndex] || null;
state.occurrenceHref = index => state.errIssueHref(state.selectedIssue?.id || "", `&occurrence=${index}`);
state.openOccurrence = index => { if (state.selectedIssue) { lastOccurrence = index; location.url(state.occurrenceHref(index)); } };
state.lastOccurrence = () => lastOccurrence;
// ---- Request view ------------------------------------------------------
function clearTrace() { traceVersion++; state.trace = null; state.traceLoading = false; }
async function loadTrace() {
const occurrence = state.currentOccurrence();
clearTrace();
const kind = UUID.test(occurrence?.requestId || "") ? "requestId" : UUID.test(occurrence?.jobId || "") ? "jobId" : "";
if (!kind || state.issueData?.source !== "central") return;
const current = traceVersion;
state.traceLoading = true;
try {
const response = await http.get("/api/admin/errors/correlation", { params: { kind, id: occurrence[kind], window: state.issueData?.window || "24h" } });
if (!disposed && current === traceVersion) state.trace = response.data;
} catch {
if (!disposed && current === traceVersion) state.trace = { state: "unreachable", events: [] };
} finally { if (!disposed && current === traceVersion) state.traceLoading = false; }
}
state.traceKind = () => {
const occurrence = state.currentOccurrence();
return UUID.test(occurrence?.requestId || "") ? "request" : UUID.test(occurrence?.jobId || "") ? "job" : "";
};
state.waterfall = () => waterfall(state.trace?.events?.length ? state.trace.events : [state.occurrenceRecord()].filter(Boolean), state.selectedIssue);
// The fullest record of this occurrence: the matching trace event, else the occurrence projection.
state.occurrenceRecord = () => {
const occurrence = state.currentOccurrence();
if (!occurrence) return null;
const issue = state.selectedIssue;
const events = state.trace?.events || [];
const match = events.find(event => event.timestamp === occurrence.timestamp && event.service === occurrence.service)
|| events.find(event => !["edge_request", "request_completed", "external_request"].includes(event.event) &&
((issue?.errorCode && event.errorCode === issue.errorCode) || (!issue?.errorCode && issue?.errorType && event.errorType === issue.errorType)));
if (match) return match;
return state.occurrenceIndex === 0 && issue?.sample ? issue.sample : occurrence;
};
state.exceptionRecord = () => {
const record = state.occurrenceRecord();
if (record?.errorStack || record?.errorType) return { record, fromSample: false };
const sample = state.selectedIssue?.sample;
return sample?.errorStack || sample?.errorType ? { record: sample, fromSample: true } : { record: null, fromSample: false };
};
state.toggleStep = key => { state.expandedSteps = { ...state.expandedSteps, [key]: !state.expandedSteps[key] }; };
state.requestTabs = [["timeline", "Timeline"], ["request", "Request"], ["exception", "Exception"], ["fields", "All fields"]];
state.selectRequestTab = (tab, focus = false) => {
state.requestTab = tab;
if (focus) nextTick(() => document.getElementById("errs-tab-" + tab)?.focus());
};
state.requestTabKey = (event, tab) => {
const keys = state.requestTabs.map(([key]) => key);
const index = keys.indexOf(tab);
const next = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: keys.length - 1 }[event.key];
if (next === undefined) return;
event.preventDefault();
state.selectRequestTab(keys[(next + keys.length) % keys.length], true);
};
state.requestTitle = () => {
const o = state.currentOccurrence();
if (!o) return "";
const where = o.requestPath || o.route || state.selectedIssue?.route;
if (!where) return o.jobId ? `Job ${state.selectedIssue?.queue || ""}`.trim() : `${state.selectedIssue?.code || "Record"} · route not recorded`;
return `${o.method || state.selectedIssue?.method || ""} ${where}`.trim();
};
// The failing record rarely carries a duration; the request's own records do.
state.requestMs = () => {
const o = state.currentOccurrence();
if (Number.isFinite(Number(o?.ms)) && o.ms !== undefined) return Number(o.ms);
const envelope = (state.trace?.events || []).find(event => event.event === "request_completed" && Number.isFinite(Number(event.ms)));
return envelope ? Number(envelope.ms) : null;
};
state.curlFor = occurrence => occurrence?.requestPath && ["GET", "HEAD"].includes(occurrence.method || "GET")
? `curl -i ${occurrence.method === "HEAD" ? "-I " : ""}'${window.location.origin}${occurrence.requestPath}'` : "";
state.copyValue = async (value, label) => {
try { await navigator.clipboard.writeText(String(value)); state.copyStatus = `${label} copied.`; }
catch { state.copyStatus = "Copy is not available in this browser. Select the text instead."; }
};
state.recordJson = record => JSON.stringify(record || {}, null, 2);
// ---- Settings and diagnostics (lazy) -----------------------------------
state.toggleSettings = event => {
state.settingsOpen = !!event?.target?.open;
if (!state.settingsOpen) return;
if (state.statsState === "idle") loadStats();
if (state.telemetryState === "idle") loadTelemetry();
};
async function loadStats() {
const current = ++statsVersion;
state.statsState = "loading";
try {
const response = await http.get("/api/admin/errors/stats");
if (disposed || current !== statsVersion) return;
state.stats = response.data;
state.statsState = response.data?.available === false ? "unavailable" : "ready";
} catch { if (!disposed && current === statsVersion) state.statsState = "unavailable"; }
}
async function loadTelemetry() {
state.telemetryState = "loading";
try {
const response = await http.get("/api/admin/errors/investigation", { params: { window: "1h" } });
if (disposed) return;
state.telemetry = response.data;
state.telemetryState = "ready";
} catch { if (!disposed) state.telemetryState = "unavailable"; }
}
state.telemetryText = value => ({
ready: "Central logs answer.", empty: "Central logs answer; nothing to report in the last hour.", partial: "Central logs answer with partial coverage.",
stale: "Central logs answer, but expected application telemetry is stale or missing.", disabled: "Central logs are not configured.",
misconfigured: "Central log configuration is invalid.", unreachable: "Central logs did not answer.", busy: "Central logs are busy. Retry shortly.",
})[value] || "Central log status is unknown.";
state.statBarHeight = (bucket, key) => {
const max = Math.max(1, ...(state.stats?.buckets || []).map(b => (b.error || 0) + (b.warn || 0) + (b.info || 0)));
return Math.round(((bucket[key] || 0) / max) * 40);
};
state.clearHistory = async () => {
if (!window.confirm("Clear the Redis error history? Central logs are not affected.")) return;
try { await http.delete("/api/admin/errors"); state.copyStatus = "Redis history cleared."; state.statsState = "idle"; loadStats(); load(); }
catch { state.copyStatus = "Could not clear the Redis history."; }
};
state.exportHistory = async () => {
try {
const response = await http.get("/api/admin/errors", { params: { offset: 0, limit: 5000 } });
const cols = ["ts", "level", "module", "message", "service", "status", "route", "repoId", "userId", "viewer", "requestId"];
const lines = [cols.join(",")];
for (const entry of response.data?.entries || []) {
const row = { ...(entry.raw?.[0] || {}), ...entry };
lines.push(cols.map(col => { const v = row[col] == null ? "" : String(row[col]); return /[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v; }).join(","));
}
const url = URL.createObjectURL(new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8" }));
const a = document.createElement("a");
a.href = url; a.download = `errors-${new Date().toISOString().slice(0, 19)}.csv`;
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
state.copyStatus = "Redis history exported.";
} catch { state.copyStatus = "Could not export the Redis history."; }
};
load().then(() => { if (state.errView !== "list") focusHeading(); });
const poll = interval(() => { if (state.errView === "list" && !state.issueLoading && document.visibilityState !== "hidden") load({ quiet: true }); }, 60000);
state.on("dispose", () => { disposed = true; window.clearTimeout(searchTimer); version++; traceVersion++; statsVersion++; interval.cancel(poll); });
};