mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
feat(admin): errors page built around issues, linked to repositories and users
The admin Errors page now shows one list of issues: records grouped by error code (or exception type), service and route, each with a plain-language title, a likely cause, its impact (failures, repositories, users), a trend and when it was last seen. Expected 4xx answers sit in a collapsed group; slow and interrupted requests are left out and counted, with a link to Performance. - GET /api/admin/errors/issues groups server-side (admin-error-issues.ts). It reads central logs when they answer and the Redis history otherwise, accepts validated repoId/userId/service/window filters and resolves repository owners and user names when the database is connected. - The cause is derived from external_request records of the same requests (#990 field names), fast 429s, storage and network codes, and the first application stack frame; otherwise it says nothing is known. - Issue page (?issue=) with cause, affected repositories and owners, who hit it, failures over time and occurrences. Request view (&occurrence=) with a waterfall from the existing correlation lookup and Request, Exception and All fields tabs; missing data shows as "not recorded". - Repositories (search = one repoId) and user admin pages list their issues, with a "failing now" banner. - The source switch, export, clear history, telemetry and 24-hour counters move to a collapsed "Settings and diagnostics" section. - Synthetic fixtures shared by dev-mock and preview-errors; old errors-page CSS removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c281841f91
commit
2abd6beaa9
21 files changed
+2053
-2323
No files matched your search
+13
-501
@@ -1,4 +1,5 @@
|
||||
import { installLogInvestigation } from "./admin-log-investigation.js";
|
||||
import { installEntityErrors } from "./admin-errors.js";
|
||||
export { errorsAdminController } from "./admin-errors.js";
|
||||
import { reactive, onScopeDispose, nextTick } from "vue";
|
||||
import { createTimers, createListeners } from "./state.js";
|
||||
import { duration, statusMsg, number as formatNumber, date as formatDate } from "./formatters.js";
|
||||
@@ -299,6 +300,7 @@ export const repositoriesAdminController = function (state, http, location) {
|
||||
state.totalPage = Math.ceil(res.data.total / state.query.limit);
|
||||
state.repositories = res.data.results;
|
||||
state.allSelected = false;
|
||||
state.loadEntityErrors();
|
||||
},
|
||||
(err) => {
|
||||
state.fetchError = (err && err.data && err.data.error) || "Failed to load repositories";
|
||||
@@ -325,6 +327,13 @@ export const repositoriesAdminController = function (state, http, location) {
|
||||
: state.statusCountFor(k),
|
||||
onChange: () => { state.query.page = 1; },
|
||||
});
|
||||
// A search that names exactly one repository (as the Errors page links do)
|
||||
// shows that repository's issues above the list.
|
||||
state.errorRepoId = () => {
|
||||
const search = String(state.query.search || "").trim();
|
||||
return /^[A-Za-z0-9_-]{3,200}$/.test(search) && (state.repositories || []).some((repo) => repo.repoId === search) ? search : "";
|
||||
};
|
||||
installEntityErrors(state, http, () => state.errorRepoId() ? { repoId: state.errorRepoId() } : null);
|
||||
getRepositories();
|
||||
getStatusCounts();
|
||||
|
||||
@@ -682,12 +691,15 @@ export const userAdminController = function (state, http, location, params) {
|
||||
http.get("/api/admin/users/" + username, {}).then(
|
||||
(res) => {
|
||||
state.userInfo = res.data;
|
||||
state.loadEntityErrors();
|
||||
},
|
||||
(err) => {
|
||||
console.error(err);
|
||||
}
|
||||
);
|
||||
}
|
||||
// Issues whose records carry this user's internal _id (#991).
|
||||
installEntityErrors(state, http, () => /^[a-f0-9]{24}$/.test(state.userInfo?._id || "") ? { userId: state.userInfo._id } : null);
|
||||
getUser(params.username);
|
||||
getUserRepositories(params.username);
|
||||
|
||||
@@ -1421,506 +1433,6 @@ export const queuesAdminController = function (state, http, location, interval,
|
||||
});
|
||||
};
|
||||
|
||||
export const errorsAdminController = function (state, http, location, interval) {
|
||||
installLogInvestigation(state, http);
|
||||
state.redisCollecting = null;
|
||||
state.redisLoading = false;
|
||||
let historyVersion = 0, statsVersion = 0, statsPending = false, disposed = false;
|
||||
state.redisStatsState = "loading";
|
||||
const timers = createTimers();
|
||||
state.watch("user.status", () => {
|
||||
if (state.user == null) {
|
||||
location.url("/");
|
||||
}
|
||||
});
|
||||
if (state.user == null) {
|
||||
location.url("/");
|
||||
}
|
||||
|
||||
state.entries = [];
|
||||
state.visible = [];
|
||||
state.available = null;
|
||||
state.cap = 1000;
|
||||
state.total = 0;
|
||||
state.pageSize = 250;
|
||||
state.expanded = {};
|
||||
state.historySelected = null;
|
||||
state.historyView = "overview";
|
||||
let historyOrigin = null, historyScroll = [];
|
||||
state.detailTab = {};
|
||||
state.copyHint = "";
|
||||
state.parsedFilterCount = 0;
|
||||
state.stats = { last24h: 0, prev24h: 0, delta: 0, severity: { error: 0, warn: 0, info: 0 }, unique: { error: 0, warn: 0, info: 0 }, buckets: [], dropped: 0 };
|
||||
state.query = {
|
||||
search: "",
|
||||
bucket: "",
|
||||
sort: "recent",
|
||||
group: "code",
|
||||
autoRefresh: true,
|
||||
};
|
||||
|
||||
state.relTime = (iso) => {
|
||||
if (!iso) return "";
|
||||
const t = new Date(iso).getTime();
|
||||
if (isNaN(t)) return iso;
|
||||
const diff = Math.max(0, Date.now() - t);
|
||||
const s = Math.floor(diff / 1000);
|
||||
if (s < 5) return "just now";
|
||||
if (s < 60) return `${s}s ago`;
|
||||
const m = Math.floor(s / 60);
|
||||
if (m < 60) return `${m}m ago`;
|
||||
const h = Math.floor(m / 60);
|
||||
if (h < 24) return `${h}h ago`;
|
||||
const d = Math.floor(h / 24);
|
||||
if (d < 7) return `${d}d ago`;
|
||||
return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
|
||||
};
|
||||
state.absTime = (iso) => {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
||||
};
|
||||
state.absTimeShort = (iso) => {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
|
||||
};
|
||||
|
||||
// Decorate each entry once with derived display fields. Pre-computing
|
||||
// avoids returning new arrays from template functions each digest
|
||||
// cycle (which trips Angular's $rootScope:infdig).
|
||||
// snake_case-ish identifier looking like an error key. Accepts both
|
||||
// pure lowercase ("repo_not_found") and the mixed-case style this
|
||||
// codebase uses ("repoId_already_used", "invalid_repoId").
|
||||
const errorKeyRe = /^[a-zA-Z][a-zA-Z0-9]*(?:_[a-zA-Z0-9]+)+$/;
|
||||
function bucketFor(detail, level) {
|
||||
const s =
|
||||
(detail && (detail.httpStatus || detail.status)) || null;
|
||||
if (typeof s === "number") {
|
||||
if (s >= 500) return "error";
|
||||
if (s === 401 || s === 403 || s === 404) return "info";
|
||||
if (s >= 400) return "warn";
|
||||
}
|
||||
if (level === "error") return "error";
|
||||
if (level === "warn") return "warn";
|
||||
return "info";
|
||||
}
|
||||
function decorate(e) {
|
||||
// Preserve the API's safe record before adding UI-only fields. Raw and
|
||||
// Copy JSON must not silently omit fields through the summary projection.
|
||||
e._rawJson = JSON.stringify(e, null, 2);
|
||||
const detail = (e.raw || []).find(
|
||||
(a) => a && typeof a === "object" && !Array.isArray(a)
|
||||
);
|
||||
if (detail) {
|
||||
if (detail.message && errorKeyRe.test(detail.message)) {
|
||||
e.displayMessage = detail.message;
|
||||
e.displayContext = e.message;
|
||||
} else if (detail.code && errorKeyRe.test(String(detail.code))) {
|
||||
e.displayMessage = String(detail.code);
|
||||
e.displayContext = e.message;
|
||||
} else if (
|
||||
detail.name &&
|
||||
detail.name !== "AnonymousError" &&
|
||||
detail.name !== "Error"
|
||||
) {
|
||||
// Plain JS errors (SyntaxError, TypeError, RangeError, ...) — use
|
||||
// the class name as the visible code; the original message is
|
||||
// shown as italic context.
|
||||
e.displayMessage = detail.name;
|
||||
e.displayContext = detail.message || e.message;
|
||||
} else {
|
||||
e.displayMessage = e.message;
|
||||
}
|
||||
e._status = detail.httpStatus || detail.status || null;
|
||||
e._url = detail.url || null;
|
||||
e._method = detail.method || null;
|
||||
e._repoId = detail.repoId || detail.detail || null;
|
||||
e._userId = /^[a-f0-9]{24}$/.test(String(detail.userId || "")) ? detail.userId : null;
|
||||
e._viewer = ["owner", "coauthor", "admin", "visitor", "anonymous"].includes(detail.viewer) ? detail.viewer : null;
|
||||
e._detail = detail.detail && detail.detail !== e._repoId ? detail.detail : null;
|
||||
// Walk into `cause` (and `err` for streamer-style entries) to
|
||||
// surface the deepest stack.
|
||||
let s = detail.errorStack || detail.causeStack ? [detail.errorType, detail.errorStack, detail.causeType ? "Caused by " + detail.causeType : null, detail.causeStack].filter(Boolean).join("\n") : (typeof detail.stack === "string" ? detail.stack : null);
|
||||
var roots = [detail.cause, detail.err].filter(Boolean);
|
||||
for (var ri = 0; !s && ri < roots.length; ri++) {
|
||||
var c = roots[ri];
|
||||
while (!s && c && typeof c === "object") {
|
||||
if (typeof c.stack === "string") s = c.stack;
|
||||
c = c.cause;
|
||||
}
|
||||
}
|
||||
e._stack = s;
|
||||
} else {
|
||||
e.displayMessage = e.message;
|
||||
e._status = null;
|
||||
e._url = null;
|
||||
e._stack = null;
|
||||
}
|
||||
e._bucket = bucketFor(detail, e.level);
|
||||
e._detailJson = renderDisplayPayload(e, detail);
|
||||
return e;
|
||||
}
|
||||
|
||||
// Build a curated, column-aligned payload for the readable Details tab. Mirrors
|
||||
// the reference admin design: name / code / kind / httpStatus / module /
|
||||
// detail / url / ts on aligned colons. We can't just JSON.stringify the
|
||||
// raw entry because it includes the human "anonymous error" wrapper
|
||||
// arg and the keys aren't column-aligned.
|
||||
function renderDisplayPayload(entry, detail) {
|
||||
const fields = [];
|
||||
const push = (k, v) => {
|
||||
if (v === undefined || v === null || v === "") return;
|
||||
fields.push([k, v]);
|
||||
};
|
||||
for (const key of ["service", "event", "severity", "requestId", "jobId"]) push(key, detail && detail[key]);
|
||||
push("name", detail && detail.name);
|
||||
push("code", entry.displayMessage || (detail && detail.message));
|
||||
if (entry._bucket) push("kind", entry._bucket);
|
||||
push("httpStatus", detail && detail.httpStatus);
|
||||
if (detail && detail.status && !(detail.httpStatus)) push("status", detail.status);
|
||||
push("module", entry.module);
|
||||
// AnonymousError.detail() can return a JSON-encoded string for
|
||||
// structured payloads (e.g. {"repoId":"...","terms":[],"fullName":...}).
|
||||
// Try to parse it so the renderer can pretty-print it multi-line
|
||||
// instead of dumping an unreadable escape-soup blob.
|
||||
let detailValue = detail && detail.detail;
|
||||
if (typeof detailValue === "string") {
|
||||
const trimmed = detailValue.trim();
|
||||
if (trimmed[0] === "{" || trimmed[0] === "[") {
|
||||
try {
|
||||
detailValue = JSON.parse(detailValue);
|
||||
} catch {
|
||||
/* leave as string */
|
||||
}
|
||||
}
|
||||
}
|
||||
push("detail", detailValue);
|
||||
push("repoId", detail && detail.repoId);
|
||||
push("filePath", detail && detail.filePath);
|
||||
push("upstreamStatus", detail && detail.upstreamStatus);
|
||||
push("upstreamBody", detail && detail.upstreamBody);
|
||||
push("url", entry._url);
|
||||
push("err", detail && detail.err);
|
||||
push("cause", detail && !detail.err && detail.cause);
|
||||
push("ts", entry.ts);
|
||||
if (!fields.length) return JSON.stringify(entry, null, 2);
|
||||
const keyW = fields.reduce((w, f) => Math.max(w, f[0].length), 0);
|
||||
const lines = ["{"];
|
||||
fields.forEach(([k, v], i) => {
|
||||
const key = `"${k}":`.padEnd(keyW + 3, " ");
|
||||
const prefix = ` ${key} `;
|
||||
const comma = i < fields.length - 1 ? "," : "";
|
||||
let val;
|
||||
if (v && typeof v === "object") {
|
||||
// Indent continuation lines under the value column so the nested
|
||||
// object reads like a column instead of breaking flow.
|
||||
const pad = " ".repeat(prefix.length);
|
||||
val = JSON.stringify(v, null, 2)
|
||||
.split("\n")
|
||||
.map((ln, idx) => (idx === 0 ? ln : pad + ln))
|
||||
.join("\n");
|
||||
} else if (typeof v === "number" || typeof v === "boolean") {
|
||||
val = String(v);
|
||||
} else {
|
||||
val = JSON.stringify(v);
|
||||
}
|
||||
lines.push(`${prefix}${val}${comma}`);
|
||||
});
|
||||
lines.push("}");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
// Lightweight filter parser. Pulls `key:value` and `status:>=400` style
|
||||
// tokens out of the search box; everything else falls back to a free
|
||||
// text contains-match against the rendered fields.
|
||||
function parseFilter(input) {
|
||||
const filters = [];
|
||||
let free = "";
|
||||
const re = /(\w+):(>=|<=|!=|>|<|=)?([^\s]+)/g;
|
||||
let lastEnd = 0;
|
||||
let m;
|
||||
while ((m = re.exec(input))) {
|
||||
free += input.slice(lastEnd, m.index);
|
||||
lastEnd = re.lastIndex;
|
||||
filters.push({ key: m[1], op: m[2] || "=", val: m[3] });
|
||||
}
|
||||
free += input.slice(lastEnd);
|
||||
return { filters, free: free.trim().toLowerCase() };
|
||||
}
|
||||
function matchFilter(row, parsed) {
|
||||
for (const f of parsed.filters) {
|
||||
const cmp = (a, b, op) => {
|
||||
const an = parseFloat(a);
|
||||
const bn = parseFloat(b);
|
||||
if (op === "=") return String(a) === String(b);
|
||||
if (op === "!=") return String(a) !== String(b);
|
||||
if (op === ">=") return an >= bn;
|
||||
if (op === "<=") return an <= bn;
|
||||
if (op === ">") return an > bn;
|
||||
if (op === "<") return an < bn;
|
||||
return true;
|
||||
};
|
||||
let v;
|
||||
if (f.key === "code") v = row.displayMessage;
|
||||
else if (f.key === "module") v = row.module;
|
||||
else if (f.key === "status") v = row._status;
|
||||
else if (f.key === "url") v = row._url;
|
||||
else if (f.key === "repo") v = row._repoId;
|
||||
else if (f.key === "level") v = row.level;
|
||||
else continue;
|
||||
if (v == null) return false;
|
||||
if (!cmp(v, f.val, f.op)) return false;
|
||||
}
|
||||
if (parsed.free) {
|
||||
const hay = (
|
||||
(row.displayMessage || "") + " " +
|
||||
(row.module || "") + " " +
|
||||
(row._url || "") + " " +
|
||||
JSON.stringify(row.raw || [])
|
||||
).toLowerCase();
|
||||
if (hay.indexOf(parsed.free) === -1) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function recompute() {
|
||||
const parsed = parseFilter(state.query.search || "");
|
||||
state.parsedFilterCount = parsed.filters.length;
|
||||
const bucket = state.query.bucket;
|
||||
let rows = state.entries.filter((e) => {
|
||||
if (bucket && e._bucket !== bucket) return false;
|
||||
return matchFilter(e, parsed);
|
||||
});
|
||||
|
||||
const group = state.query.group;
|
||||
if (group) {
|
||||
const keyOf = (r) =>
|
||||
group === "module" ? JSON.stringify([r.module, r._bucket]) : JSON.stringify([r.raw?.[0]?.service || "unknown", r.module, r.displayMessage || r.message || "_", r._bucket, r._status]);
|
||||
const map = new Map();
|
||||
for (const r of rows) {
|
||||
const k = keyOf(r);
|
||||
if (!map.has(k)) {
|
||||
const seed = Object.assign({}, r);
|
||||
seed._key = `${group}:${k}`;
|
||||
seed._related = [r];
|
||||
seed._firstSeen = r.ts;
|
||||
seed._lastHourCount = 0;
|
||||
seed.count = 1;
|
||||
map.set(k, seed);
|
||||
} else {
|
||||
const g = map.get(k);
|
||||
g.count++;
|
||||
g._related.push(r);
|
||||
if (new Date(r.ts) > new Date(g.ts)) {
|
||||
g.ts = r.ts;
|
||||
g._url = r._url;
|
||||
g._status = r._status;
|
||||
}
|
||||
if (new Date(r.ts) < new Date(g._firstSeen)) g._firstSeen = r.ts;
|
||||
}
|
||||
}
|
||||
// count "this hour"
|
||||
const cutoffH = Date.now() - 3600 * 1000;
|
||||
for (const g of map.values()) {
|
||||
g._lastHourCount = g._related.filter((r) => new Date(r.ts).getTime() >= cutoffH).length;
|
||||
}
|
||||
rows = Array.from(map.values());
|
||||
} else {
|
||||
rows = rows.map((r, i) => {
|
||||
r._key = "row:" + i + ":" + r.ts;
|
||||
r._related = [r];
|
||||
r._firstSeen = r.ts;
|
||||
r._lastHourCount = 0;
|
||||
r.count = 1;
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
// Errors surface first, then warnings, then routine info; within a level, the chosen order.
|
||||
const rank = (r) => ({ error: 0, warn: 1, info: 2 })[r._bucket] ?? 1;
|
||||
if (state.query.sort === "count") {
|
||||
rows.sort((a, b) => rank(a) - rank(b) || b.count - a.count || new Date(b.ts) - new Date(a.ts));
|
||||
} else {
|
||||
rows.sort((a, b) => rank(a) - rank(b) || new Date(b.ts) - new Date(a.ts));
|
||||
}
|
||||
state.visible = rows;
|
||||
// A filter that matches nothing in the loaded window keeps reading older pages
|
||||
// (bounded) so a 5xx counted in the tiles is not reported as "No errors captured".
|
||||
const filtering = !!(state.query.bucket || (state.query.search || "").trim());
|
||||
// The default view also reads on until the server errors counted in the tiles appear.
|
||||
const errorsHidden = !filtering && (state.stats?.severity?.error || 0) > 0 && !rows.some((r) => r._bucket === "error") && state.entries.length < 1500;
|
||||
if (((filtering && !rows.length) || errorsHidden) && state.canLoadMore?.() && !state._autoLoading && state.entries.length < 2500) {
|
||||
state._autoLoading = true;
|
||||
loadEntries(true);
|
||||
}
|
||||
}
|
||||
|
||||
function loadEntries(append) {
|
||||
if (append && state.redisLoading) return;
|
||||
const current = ++historyVersion;
|
||||
state.redisLoading = true;
|
||||
// On auto-refresh after the user has paginated ("Load older"),
|
||||
// request the SAME-sized window from the head so we don't blow away
|
||||
// their loaded tail. Newer entries take the top, the oldest visible
|
||||
// ones drop off naturally as the redis list rotates.
|
||||
const offset = append ? (state.redisNextOffset || state.entries.length) : 0;
|
||||
const limit = append
|
||||
? state.pageSize
|
||||
: Math.max(state.pageSize, state.redisNextOffset || state.entries.length || state.pageSize);
|
||||
http
|
||||
.get("/api/admin/errors", { params: { offset, limit } })
|
||||
.then(
|
||||
(res) => {
|
||||
if (disposed || current !== historyVersion) return;
|
||||
state.redisLoading = false;
|
||||
const next = (res.data.entries || []).map(decorate);
|
||||
state.entries = append ? state.entries.concat(next) : next;
|
||||
state.redisRedacted = (append ? state.redisRedacted || 0 : 0) + (res.data.redactedEntries || 0);
|
||||
state.redisNextOffset = res.data.nextOffset ?? (offset + (res.data.entries || []).length);
|
||||
state.available = !!res.data.available;
|
||||
state.redisCollecting = res.data.redisCollecting !== false;
|
||||
state.cap = res.data.max || state.cap;
|
||||
state.total = res.data.total || state.entries.length;
|
||||
state._autoLoading = false;
|
||||
recompute();
|
||||
},
|
||||
() => { if (disposed || current !== historyVersion) return; state.redisLoading = false; state._autoLoading = false; state.available = false; }
|
||||
);
|
||||
}
|
||||
state.loadMore = () => loadEntries(true);
|
||||
state.canLoadMore = () => (state.redisNextOffset || state.entries.length) < state.total;
|
||||
function loadStats(background = false) {
|
||||
if (background && statsPending) return;
|
||||
const current = ++statsVersion;
|
||||
statsPending = true;
|
||||
http.get("/api/admin/errors/stats").then(
|
||||
(res) => {
|
||||
if (disposed || current !== statsVersion) return;
|
||||
statsPending = false;
|
||||
const s = res.data || {};
|
||||
state.redisStatsState = s.available === false ? "unavailable" : "ready";
|
||||
const delta = s.prev24h ? Math.round(((s.last24h - s.prev24h) / s.prev24h) * 100) : 0;
|
||||
state.stats = {
|
||||
last24h: s.last24h || 0,
|
||||
prev24h: s.prev24h || 0,
|
||||
delta,
|
||||
severity: s.severity || { error: 0, warn: 0, info: 0 },
|
||||
unique: s.unique || { error: 0, warn: 0, info: 0 },
|
||||
buckets: s.buckets || [],
|
||||
dropped: s.dropped || 0,
|
||||
};
|
||||
recompute();
|
||||
},
|
||||
() => { if (!disposed && current === statsVersion) { statsPending = false; state.redisStatsState = "unavailable"; } }
|
||||
);
|
||||
}
|
||||
function load(background = false) {
|
||||
// Polls must not invalidate a slow head or pagination request. Explicit
|
||||
// refreshes still supersede it; stats refresh independently of entries.
|
||||
if (!background || !state.redisLoading) loadEntries();
|
||||
loadStats(background);
|
||||
}
|
||||
|
||||
// Volume chart: errors and warnings carry the height (scaled to their own peak, up to 44px);
|
||||
// routine info traffic is a faint band on top, capped at 16px. Exact counts are in the tooltip.
|
||||
state.barPx = (b, key) => {
|
||||
const all = state.stats.buckets || [];
|
||||
let maxEW = 0, maxInfo = 0;
|
||||
for (const x of all) { maxEW = Math.max(maxEW, (x.error || 0) + (x.warn || 0)); maxInfo = Math.max(maxInfo, x.info || 0); }
|
||||
const part = b[key] || 0;
|
||||
if (!part) return 0;
|
||||
if (key === "info") return maxInfo ? Math.max(2, Math.round((part / maxInfo) * (maxEW ? 16 : 60))) : 0;
|
||||
const ew = (b.error || 0) + (b.warn || 0);
|
||||
const h = Math.round((ew / maxEW) * 44);
|
||||
return Math.max(4, Math.round((part / ew) * h));
|
||||
};
|
||||
state.bucketTitle = (b) => {
|
||||
const t = new Date(b.hour);
|
||||
return `${t.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} · ${b.error || 0} err · ${b.warn || 0} warn · ${b.info || 0} info`;
|
||||
};
|
||||
|
||||
state.toggle = async (row, origin) => {
|
||||
historyOrigin = origin || document.activeElement;
|
||||
historyScroll = state.captureErrorScroll(historyOrigin);
|
||||
state.historySelected = row;
|
||||
state.historyView = "overview";
|
||||
state.expanded = {[row._key]:true};
|
||||
await nextTick();
|
||||
document.getElementById("history-inspector-title")?.focus({preventScroll:true});
|
||||
document.getElementById("history-inspector-title")?.scrollIntoView?.({block:"nearest"});
|
||||
};
|
||||
state.showHistoryTimeline = origin => {
|
||||
state.historyView = "timeline";
|
||||
if(state.traceSelection) return;
|
||||
const kind=["requestId","jobId"].find(key=>state.logTraceId(state.historySelected,key));
|
||||
if(kind) state.lookupTrace(kind,state.logTraceId(state.historySelected,kind),origin,state.historySelected);
|
||||
};
|
||||
state.closeHistory = async () => {
|
||||
const key = state.historySelected?._key;
|
||||
state.historySelected = null; state.expanded = {};
|
||||
if (state.traceSelection) await state.closeTrace();
|
||||
await nextTick();
|
||||
const target = historyOrigin?.isConnected ? historyOrigin : [...document.querySelectorAll('[data-history-key]')].find(node=>node.dataset.historyKey===key);
|
||||
target?.focus({preventScroll:true});
|
||||
state.restoreErrorScroll(historyScroll);
|
||||
};
|
||||
state.setBucket = (b) => {
|
||||
state.query.bucket = b;
|
||||
};
|
||||
|
||||
state.refreshNow = () => { state.historySelected = null; state.historyView = "overview"; state.expanded = {}; if (state.traceSelection) state.closeTrace(); load(); };
|
||||
state.clearAll = () => {
|
||||
if (!confirm("Clear Redis error history? Central logs are unaffected.")) return;
|
||||
http.delete("/api/admin/errors").then(() => state.refreshNow(), (err) => console.error(err));
|
||||
};
|
||||
state.exportCsv = () => {
|
||||
const cols = ["ts", "level", "module", "displayMessage", "_status", "_url", "_repoId"];
|
||||
const lines = [cols.join(",")];
|
||||
for (const r of state.visible) {
|
||||
lines.push(cols.map((c) => {
|
||||
const v = r[c] == null ? "" : String(r[c]);
|
||||
return /[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
|
||||
}).join(","));
|
||||
}
|
||||
const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `errors-${new Date().toISOString().slice(0, 19)}.csv`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
function flashCopy(label) {
|
||||
state.copyHint = `${label} copied`;
|
||||
timers.timeout(() => { state.copyHint = ""; }, 1500);
|
||||
}
|
||||
state.copyJson = (row) => {
|
||||
navigator.clipboard.writeText(row._rawJson).then(() => flashCopy("JSON"));
|
||||
};
|
||||
state.copyCurl = (row) => {
|
||||
if (!row._url) return;
|
||||
const method = row._method || "GET";
|
||||
const cmd = `curl -X ${method} '${window.location.origin}${row._url}'`;
|
||||
navigator.clipboard.writeText(cmd).then(() => flashCopy("curl"));
|
||||
};
|
||||
|
||||
load();
|
||||
const stop = interval(() => {
|
||||
if (state.query.autoRefresh) load(true);
|
||||
}, 15000);
|
||||
state.on("dispose", () => { disposed = true; historyVersion++; statsVersion++; interval.cancel(stop); });
|
||||
|
||||
state.watch("query.search", recompute);
|
||||
state.watch("query.bucket", recompute);
|
||||
state.watch("query.sort", recompute);
|
||||
state.watch("query.group", recompute);
|
||||
};
|
||||
|
||||
export const overviewAdminController = function (state, http, location, interval) {
|
||||
state.Math = Math;
|
||||
state.watch("user.status", () => {
|
||||
|
||||
Reference in new issue
Block a user