mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-03 17:43:54 +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
@@ -0,0 +1,264 @@
|
||||
import { createHash } from "crypto";
|
||||
import { validProjectId, validTraceId, validUserId } from "../core/log-context";
|
||||
import { EXPECTED_CLIENT_ERRORS } from "./routes/route-utils";
|
||||
|
||||
// Groups safe admin log rows (already projected by admin-log-investigation) into
|
||||
// issues: one per error code (or exception type), service and route. Pure and
|
||||
// bounded so the central-log and Redis-history paths share it.
|
||||
export type Row = Record<string, string | number>;
|
||||
export type CauseSource = "github" | "limit" | "storage" | "network" | "code" | "configuration" | "unknown";
|
||||
export interface Cause { source: CauseSource; label: string; summary: string; detail: string; evidence: string[] }
|
||||
|
||||
const TITLES: Record<string, string> = {
|
||||
github_rate_limit_exceeded: "GitHub rate limit reached",
|
||||
rate_limited: "Request rate limit reached",
|
||||
github_unavailable: "GitHub did not answer",
|
||||
upstream_error: "GitHub returned an error",
|
||||
upstream_timeout: "GitHub took too long to answer",
|
||||
github_token_invalid: "GitHub token is no longer valid",
|
||||
token_refresh_failed: "GitHub token could not be refreshed",
|
||||
token_expired: "Owner's GitHub token expired",
|
||||
github_app_reconnect_required: "GitHub App needs to be reconnected",
|
||||
github_app_disabled: "GitHub App disabled",
|
||||
repo_not_accessible: "Repository not accessible on GitHub",
|
||||
repo_access_limited: "GitHub limits access to the repository",
|
||||
unable_to_download: "Repository download failed",
|
||||
repository_tree_too_large: "Repository tree too large",
|
||||
repository_tree_incomplete: "Repository tree incomplete",
|
||||
file_listing_too_large: "File listing too large",
|
||||
storage_write_size_mismatch: "Storage write size mismatch",
|
||||
storage_delete_failed: "Storage could not delete files",
|
||||
zip_not_available: "ZIP download not available",
|
||||
zip_unsafe_entry_path: "ZIP entry with an unsafe path",
|
||||
preparation_interrupted: "Repository preparation interrupted",
|
||||
quota_exceeded: "Quota exceeded",
|
||||
server_error: "Internal error with no detail",
|
||||
invalid_signature: "Webhook signature rejected",
|
||||
webhook_processing_failed: "Webhook processing failed",
|
||||
ECONNRESET: "Connection reset", ECONNREFUSED: "Connection refused", ETIMEDOUT: "Connection timed out",
|
||||
ENOTFOUND: "Host not found", EPIPE: "Connection closed while writing", ABORT_ERR: "Request aborted",
|
||||
};
|
||||
const GITHUB_CODES = new Set(["github_unavailable", "upstream_error", "upstream_timeout", "repo_not_accessible", "repo_access_limited", "unable_to_download"]);
|
||||
const LIMIT_CODES = new Set(["github_rate_limit_exceeded", "rate_limited"]);
|
||||
const CONFIG_CODES = new Set(["github_token_invalid", "token_refresh_failed", "token_expired", "github_app_reconnect_required", "github_app_disabled", "invalid_signature"]);
|
||||
const NETWORK_CODES = new Set(["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE"]);
|
||||
const IGNORED = new Set(["process_heartbeat", "queue_heartbeat", "process_started", "job_started", "job_completed", "deployment"]);
|
||||
// Request envelopes repeat a failure that a more specific record of the same request describes.
|
||||
const ENVELOPES = new Set(["edge_request", "request_completed"]);
|
||||
const SIGNED_IN = new Set(["owner", "coauthor", "admin"]);
|
||||
|
||||
export const statusOf = (row: Row) => Number(row.status || row.httpStatus) || 0;
|
||||
const codeOf = (row: Row) => String(row.errorCode || row.errorType || (row.event === "edge_request" ? `edge_${statusOf(row) || "5xx"}` : row.event) || "unknown");
|
||||
|
||||
export type RecordKind = "issue" | "expected" | "slow" | "interrupted" | "external" | "ignored";
|
||||
export function recordKind(row: Row): RecordKind {
|
||||
if (row.event === "request_slow") return "slow";
|
||||
if (row.event === "request_cancelled" || row.outcome === "interrupted") return "interrupted";
|
||||
if (row.event === "external_request") return "external";
|
||||
if (IGNORED.has(String(row.event))) return "ignored";
|
||||
const status = statusOf(row);
|
||||
if (status >= 500) return "issue";
|
||||
if (status >= 400 && status !== 429) return "expected";
|
||||
if (EXPECTED_CLIENT_ERRORS.has(String(row.errorCode))) return "expected";
|
||||
if (row.severity === "info" || row.severity === "debug") return row.errorCode ? "expected" : "ignored";
|
||||
return "issue";
|
||||
}
|
||||
|
||||
export function issueTitle(row: Row) {
|
||||
const code = codeOf(row);
|
||||
if (TITLES[code]) return TITLES[code];
|
||||
if (row.event === "edge_request") return `Edge proxy returned ${statusOf(row) || "5xx"}`;
|
||||
if (!row.errorCode && row.errorType) return `Code crashed: ${row.errorType}`;
|
||||
if (row.event === "job_failed" && !row.errorCode) return "Background job failed";
|
||||
return code.replace(/_/g, " ").replace(/^./, c => c.toUpperCase());
|
||||
}
|
||||
|
||||
export function issueId(row: Row) {
|
||||
return createHash("sha256").update(JSON.stringify([codeOf(row), String(row.service || ""), String(row.route || row.queue || "")])).digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
const time = (row: Row) => Date.parse(String(row.timestamp));
|
||||
const median = (values: number[]) => { const s = values.slice().sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
|
||||
const seconds = (ms: number) => ms >= 1000 ? `${(ms / 1000).toFixed(1).replace(/\.0$/, "")} s` : `${Math.round(ms)} ms`;
|
||||
const plural = (n: number, word: string) => `${n.toLocaleString("en-US")} ${word}${n === 1 ? "" : "s"}`;
|
||||
const hostLabel = (host: string) => host === "storage" ? "Storage" : /github/.test(host) ? "GitHub" : host === "other" ? "An external service" : host;
|
||||
function firstFrame(stack: unknown) {
|
||||
const line = String(stack || "").split("\n").find(value => /\(?[\w./-]+\.[jt]s:\d+/.test(value));
|
||||
const match = line?.match(/([\w-]+\.[jt]s):(\d+)/);
|
||||
return match ? `${match[1]}:${match[2]}` : "";
|
||||
}
|
||||
|
||||
/** Derives a likely cause from the error code, status, timings and the request's external calls. */
|
||||
export function deriveCause(rows: Row[], external: Row[] = []): Cause {
|
||||
const sample = rows[0] || {};
|
||||
const code = String(sample.errorCode || "");
|
||||
const status = statusOf(sample);
|
||||
const requests = new Set(rows.map(row => row.requestId).filter(validTraceId));
|
||||
const failedCalls = external.filter(row => validTraceId(row.requestId) && requests.has(row.requestId as string) && (Number(row.upstreamStatus) >= 400 || row.errorCode));
|
||||
const durations = rows.map(row => Number(row.ms)).filter(Number.isFinite);
|
||||
const evidence: string[] = [];
|
||||
if (durations.length > 1) evidence.push(`Durations ${seconds(Math.min(...durations))} – ${seconds(Math.max(...durations))}, median ${seconds(median(durations))}.`);
|
||||
if (failedCalls.length) {
|
||||
const groups = new Map<string, { host: string; status: number; method: string; endpoint: string; code: string; requests: Set<string>; calls: number }>();
|
||||
for (const call of failedCalls) {
|
||||
const key = [call.upstreamHost, call.upstreamStatus, call.upstreamMethod, call.upstreamEndpoint, call.errorCode].join(" ");
|
||||
const group = groups.get(key) || { host: String(call.upstreamHost || "other"), status: Number(call.upstreamStatus) || 0, method: String(call.upstreamMethod || ""),
|
||||
endpoint: String(call.upstreamEndpoint || ""), code: String(call.errorCode || ""), requests: new Set(), calls: 0 };
|
||||
group.requests.add(call.requestId as string); group.calls++; groups.set(key, group);
|
||||
}
|
||||
const top = [...groups.values()].sort((a, b) => b.requests.size - a.requests.size || b.calls - a.calls)[0];
|
||||
const who = hostLabel(top.host);
|
||||
const what = top.status ? `answered ${top.status}` : `failed with ${top.code || "a connection error"}`;
|
||||
const where = top.endpoint ? ` on ${top.method ? top.method + " " : ""}${top.endpoint}` : "";
|
||||
const retries = top.calls > top.requests.size ? ` Retries (${Math.round(top.calls / top.requests.size)} calls per request) also failed.` : "";
|
||||
const source: CauseSource = top.host === "storage" ? "storage" : /github/.test(top.host) ? (top.status === 429 || top.status === 403 ? "limit" : "github") : "network";
|
||||
evidence.unshift(`${plural(failedCalls.length, "failed external call")} recorded for these requests.`);
|
||||
return { source, label: source === "storage" ? "Storage" : source === "limit" ? "GitHub limit" : source === "github" ? "GitHub" : "Network",
|
||||
summary: `${who} ${what}${where} in ${top.requests.size} of ${requests.size} failures.`,
|
||||
detail: `${retries.trim()}${retries ? " " : ""}${source === "github" ? "This points at GitHub, not at the app." : source === "storage" ? "This points at the storage backend." : ""}`.trim(), evidence };
|
||||
}
|
||||
if (LIMIT_CODES.has(code) || status === 429) {
|
||||
const fast = durations.filter(ms => ms < 20).length;
|
||||
if (durations.length && fast * 2 >= durations.length) {
|
||||
return { source: "limit", label: "GitHub limit", summary: `${fast} of ${rows.length} requests returned 429 in under 20 ms.`,
|
||||
detail: "That is too fast for a GitHub call: the app answered from its remembered limit state without calling GitHub.", evidence };
|
||||
}
|
||||
return { source: "limit", label: "GitHub limit", summary: "GitHub's rate limit for the token or installation was exhausted.",
|
||||
detail: "The records do not say which token or installation ran out.", evidence };
|
||||
}
|
||||
if (CONFIG_CODES.has(code)) return { source: "configuration", label: "Configuration", summary: `The app recorded ${code}: a credential or app setting needs attention.`, detail: "", evidence };
|
||||
if (/^storage_/.test(code) || sample.module === "s3" || sample.upstreamHost === "storage") {
|
||||
return { source: "storage", label: "Storage", summary: `The storage backend failed (${code || sample.errorType || "no code"}).`, detail: "", evidence };
|
||||
}
|
||||
if (GITHUB_CODES.has(code)) {
|
||||
const subject = rows.some(row => row.jobId) && !rows.some(row => row.requestId) ? "Jobs" : "Requests";
|
||||
const low = Math.min(...durations), high = Math.max(...durations);
|
||||
const waited = durations.length ? ` ${subject} waited ${low === high ? seconds(low) : `${seconds(low)} – ${seconds(high)}`}, then gave up.` : "";
|
||||
return { source: "github", label: "GitHub", summary: `The app recorded ${code} for ${plural(rows.length, "record")}.${waited}`,
|
||||
detail: "No external call records were found for these requests, so GitHub's own answer is not known.", evidence };
|
||||
}
|
||||
if (NETWORK_CODES.has(code)) return { source: "network", label: "Network", summary: `A connection to another service failed (${code}).`, detail: "", evidence };
|
||||
const frame = firstFrame(sample.errorStack);
|
||||
if (sample.errorType && (frame || sample.errorStack)) {
|
||||
return { source: "code", label: "Our code", summary: `${sample.errorType}${frame ? ` thrown at ${frame}` : " thrown"}.`,
|
||||
detail: sample.causeType ? `Caused by ${sample.causeType}.` : "", evidence };
|
||||
}
|
||||
return { source: "unknown", label: "Unknown", summary: "No cause recorded: the records have no exception, stack or external call.", detail: "", evidence };
|
||||
}
|
||||
|
||||
export interface IssueOptions { start: string; end: string; external?: Row[]; buckets?: number; occurrences?: number }
|
||||
type Bucket = { rows: Row[]; first: number; last: number };
|
||||
|
||||
const occurrence = (row: Row) => Object.fromEntries(["timestamp", "requestId", "jobId", "repoId", "userId", "viewer", "requestPath", "method", "route", "status", "httpStatus", "ms", "release", "service", "errorCode", "errorType"]
|
||||
.filter(key => row[key] !== undefined && row[key] !== "").map(key => [key, row[key]]));
|
||||
|
||||
function countBy(rows: Row[], key: "repoId" | "userId", valid: (value: unknown) => boolean) {
|
||||
const map = new Map<string, { id: string; count: number; last: string }>();
|
||||
for (const row of rows) {
|
||||
const id = row[key];
|
||||
if (!valid(id)) continue;
|
||||
const entry = map.get(id as string) || { id: id as string, count: 0, last: String(row.timestamp) };
|
||||
entry.count++; if (time(row) > Date.parse(entry.last)) entry.last = String(row.timestamp);
|
||||
map.set(id as string, entry);
|
||||
}
|
||||
return [...map.values()].sort((a, b) => b.count - a.count || Date.parse(b.last) - Date.parse(a.last));
|
||||
}
|
||||
|
||||
/** Splits rows into issues, expected responses and excluded noise. */
|
||||
export function buildIssues(rows: Row[], options: IssueOptions) {
|
||||
const start = Date.parse(options.start), end = Date.parse(options.end);
|
||||
const size = options.buckets || 24, step = Math.max(1, (end - start) / size);
|
||||
const inWindow = rows.filter(row => { const t = time(row); return Number.isFinite(t) && t >= start && t <= end; });
|
||||
const excluded = { slow: 0, interrupted: 0 };
|
||||
const expected = new Map<string, { code: string; status: number; count: number; last: string }>();
|
||||
const external = [...(options.external || [])];
|
||||
const candidates: Row[] = [];
|
||||
for (const row of inWindow) {
|
||||
const kind = recordKind(row);
|
||||
if (kind === "slow" || kind === "interrupted") excluded[kind]++;
|
||||
else if (kind === "external") external.push(row);
|
||||
else if (kind === "expected") {
|
||||
const key = `${codeOf(row)}:${statusOf(row)}`;
|
||||
const entry = expected.get(key) || { code: codeOf(row), status: statusOf(row), count: 0, last: String(row.timestamp) };
|
||||
entry.count++; if (time(row) > Date.parse(entry.last)) entry.last = String(row.timestamp);
|
||||
expected.set(key, entry);
|
||||
} else if (kind === "issue") candidates.push(row);
|
||||
}
|
||||
const specific = new Set(candidates.filter(row => !ENVELOPES.has(String(row.event))).map(row => row.requestId).filter(validTraceId));
|
||||
const issueRows = candidates.filter(row => !(ENVELOPES.has(String(row.event)) && specific.has(row.requestId as string)));
|
||||
const releases = issueRows.filter(row => row.release && row.release !== "unknown").sort((a, b) => time(b) - time(a)).map(row => String(row.release));
|
||||
const newest = releases[0];
|
||||
const mixedReleases = new Set(releases).size > 1;
|
||||
const groups = new Map<string, Bucket>();
|
||||
for (const row of issueRows) {
|
||||
const id = issueId(row);
|
||||
const group = groups.get(id) || { rows: [], first: Infinity, last: -Infinity };
|
||||
group.rows.push(row); group.first = Math.min(group.first, time(row)); group.last = Math.max(group.last, time(row));
|
||||
groups.set(id, group);
|
||||
}
|
||||
const issues = [...groups.entries()].map(([id, group]) => {
|
||||
const sorted = group.rows.sort((a, b) => time(b) - time(a));
|
||||
const sample = sorted[0];
|
||||
const firstRow = sorted[sorted.length - 1];
|
||||
const trend = Array.from({ length: size }, () => 0);
|
||||
for (const row of sorted) trend[Math.min(size - 1, Math.max(0, Math.floor((time(row) - start) / step)))]++;
|
||||
const requests = new Set(sorted.map(row => row.requestId).filter(validTraceId));
|
||||
const jobs = new Set(sorted.map(row => row.jobId).filter(validTraceId));
|
||||
const repos = countBy(sorted, "repoId", validProjectId);
|
||||
const users = countBy(sorted, "userId", validUserId);
|
||||
const viewers = { signedIn: 0, visitors: 0, notRecorded: 0 };
|
||||
for (const row of sorted) viewers[SIGNED_IN.has(String(row.viewer)) ? "signedIn" : row.viewer ? "visitors" : "notRecorded"]++;
|
||||
const routes = new Set(sorted.map(row => row.route).filter(Boolean));
|
||||
return {
|
||||
id, title: issueTitle(sample), code: codeOf(sample), errorCode: sample.errorCode || null, errorType: sample.errorType || null,
|
||||
status: statusOf(sample) || null, service: sample.service || null, route: sample.route || null, method: sample.method || null,
|
||||
queue: sample.queue || null, event: sample.event, severity: sample.severity,
|
||||
count: sorted.length, requests: requests.size, jobs: jobs.size, routeKnown: sorted.filter(row => row.route).length, routes: routes.size,
|
||||
repoCount: repos.length, repos: repos.slice(0, 50), userCount: users.length, users: users.slice(0, 50), viewers,
|
||||
first: new Date(group.first).toISOString(), last: new Date(group.last).toISOString(),
|
||||
firstRelease: firstRow.release && firstRow.release !== "unknown" ? firstRow.release : null,
|
||||
newInRelease: mixedReleases && newest && firstRow.release === newest ? newest : null,
|
||||
failingNow: end - group.last <= 15 * 60000,
|
||||
trend, cause: deriveCause(sorted, external),
|
||||
occurrences: sorted.slice(0, options.occurrences || 50).map(occurrence), sample,
|
||||
};
|
||||
}).sort((a, b) => Number(b.failingNow) - Number(a.failingNow) || Date.parse(b.last) - Date.parse(a.last));
|
||||
const repoIds = new Set(issues.flatMap(issue => issue.repos.map(repo => repo.id)));
|
||||
const userIds = new Set(issues.flatMap(issue => issue.users.map(user => user.id)));
|
||||
const failed = issues.reduce((sum, issue) => sum + issue.count, 0);
|
||||
const upstream = issues.filter(issue => ["github", "limit", "storage"].includes(issue.cause.source)).reduce((sum, issue) => sum + issue.count, 0);
|
||||
const expectedList = [...expected.values()].sort((a, b) => b.count - a.count);
|
||||
return {
|
||||
issues,
|
||||
expected: { count: expectedList.reduce((sum, entry) => sum + entry.count, 0), groups: expectedList.slice(0, 20) },
|
||||
excluded,
|
||||
summary: { issues: issues.length, failingNow: issues.filter(issue => issue.failingNow).length, failedRecords: failed,
|
||||
repositories: repoIds.size, users: userIds.size, upstreamShare: failed ? Math.round(upstream / failed * 100) : 0 },
|
||||
};
|
||||
}
|
||||
|
||||
export class InvalidIssueQuery extends Error {}
|
||||
const ISSUE_WINDOWS: Record<string, number> = { "15m": 15, "1h": 60, "6h": 360, "24h": 1440 };
|
||||
const ISSUE_SERVICES = ["api", "streamer", "worker", "nginx", "mongodb", "redis", "backup"];
|
||||
/** Validated options for GET /api/admin/errors/issues. Unknown keys are rejected. */
|
||||
export function issueOptions(query: Record<string, unknown>, now = Date.now()) {
|
||||
const permitted = ["window", "service", "repoId", "userId", "source"];
|
||||
if (Object.keys(query).some(key => !permitted.includes(key)) || Object.values(query).some(value => typeof value !== "string")) throw new InvalidIssueQuery();
|
||||
const window = (query.window as string) || "24h";
|
||||
if (!Object.hasOwn(ISSUE_WINDOWS, window)) throw new InvalidIssueQuery();
|
||||
const service = (query.service as string) || "";
|
||||
if (service && !ISSUE_SERVICES.includes(service)) throw new InvalidIssueQuery();
|
||||
const repoId = (query.repoId as string) || "";
|
||||
if (repoId && !validProjectId(repoId)) throw new InvalidIssueQuery();
|
||||
const userId = (query.userId as string) || "";
|
||||
if (userId && !validUserId(userId)) throw new InvalidIssueQuery();
|
||||
const source = (query.source as string) || "auto";
|
||||
if (!["auto", "history"].includes(source)) throw new InvalidIssueQuery();
|
||||
return { window, service, repoId, userId, source, start: new Date(now - ISSUE_WINDOWS[window] * 60000).toISOString(), end: new Date(now).toISOString() };
|
||||
}
|
||||
export type IssueQuery = ReturnType<typeof issueOptions>;
|
||||
|
||||
/** Keeps only rows that match the validated service, repository and user filters. */
|
||||
export function filterRows(rows: Row[], query: Pick<IssueQuery, "service" | "repoId" | "userId">) {
|
||||
return rows.filter(row => (!query.service || row.service === query.service) && (!query.repoId || row.repoId === query.repoId) && (!query.userId || row.userId === query.userId));
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import { createHash } from "crypto";
|
||||
import { logRecord, LOG_NUMBERS, LOG_STAGES } from "../core/log-record";
|
||||
import { LogContext, logContext, validTraceId } from "../core/log-context";
|
||||
import { LogContext, logContext, validProjectId, validTraceId, validUserId } from "../core/log-context";
|
||||
import { LOG_EVENTS } from "../core/log-schema";
|
||||
import { LOG_ROUTES } from "../core/log-diagnostic-schema";
|
||||
|
||||
const services = ["api", "streamer", "worker", "nginx", "mongodb", "redis", "backup"];
|
||||
const events = new Set([...Object.values(LOG_EVENTS), "deployment", "application_log", "webhook_log", "request_completed", "request_slow", "request_cancelled", "process_fatal_error", "process_started", "process_heartbeat", "job_started", "job_completed", "job_failed", "job_stalled", "queue_heartbeat", "edge_request", "infrastructure_log"]);
|
||||
const events = new Set([...Object.values(LOG_EVENTS), "deployment", "application_log", "webhook_log", "request_completed", "request_slow", "request_cancelled", "process_fatal_error", "process_started", "process_heartbeat", "job_started", "job_completed", "job_failed", "job_stalled", "queue_heartbeat", "edge_request", "infrastructure_log", "external_request"]);
|
||||
const windows: Record<string, number> = { "15m": 15, "1h": 60, "6h": 360, "24h": 1440 };
|
||||
let active = 0;
|
||||
export class InvalidLogQuery extends Error {}
|
||||
export function logOptions(query: Record<string, unknown>, correlation = false) {
|
||||
const permitted = correlation ? ["window", "kind", "id"] : ["window", "service", "release"];
|
||||
const permitted = correlation ? ["window", "kind", "id"] : ["window", "service", "release", "repoId", "userId"];
|
||||
if (Object.keys(query).some(key => !permitted.includes(key)) || Object.values(query).some(value => typeof value !== "string")) throw new InvalidLogQuery();
|
||||
const window = (query.window as string) || "1h";
|
||||
if (!Object.hasOwn(windows, window)) throw new InvalidLogQuery();
|
||||
@@ -19,9 +19,11 @@ export function logOptions(query: Record<string, unknown>, correlation = false)
|
||||
if (service && !services.includes(service)) throw new InvalidLogQuery();
|
||||
if (release && !/^(?:[a-f0-9]{7,40}|unknown)$/.test(release)) throw new InvalidLogQuery();
|
||||
if (correlation && (!validTraceId(query.id) || !["requestId", "jobId"].includes(String(query.kind)))) throw new InvalidLogQuery();
|
||||
const repoId = (query.repoId as string) || "", userId = (query.userId as string) || "";
|
||||
if ((repoId && !validProjectId(repoId)) || (userId && !validUserId(userId))) throw new InvalidLogQuery();
|
||||
const end = new Date().toISOString();
|
||||
const start = new Date(Date.now() - windows[window] * 60000).toISOString();
|
||||
return { window, start, end, service, release, id: query.id as string, kind: query.kind as "requestId" | "jobId" };
|
||||
return { window, start, end, service, release, repoId, userId, id: query.id as string, kind: query.kind as "requestId" | "jobId" };
|
||||
}
|
||||
type Options = ReturnType<typeof logOptions>;
|
||||
type Row = Record<string, string | number>;
|
||||
@@ -52,7 +54,8 @@ function safeRow(input: Record<string, unknown>): Row | null {
|
||||
if (typeof time !== "string" || !Number.isFinite(Date.parse(time))) return null;
|
||||
// Reuse the application's reviewed projection. Never return raw backend data.
|
||||
const numeric = [...LOG_NUMBERS, ...LOG_STAGES.flatMap(stage => [`stage_${stage}_ms`, `stage_${stage}_count`, `stage_${stage}_open`])];
|
||||
const data: Record<string, unknown> = { ...input, code: input.errorCode };
|
||||
// #990 stores the external host as upstreamHost; logRecord revalidates it from hostname.
|
||||
const data: Record<string, unknown> = { ...input, code: input.errorCode, hostname: input.upstreamHost };
|
||||
for (const key of numeric) if (typeof input[key] === "string" && /^-?\d+(?:\.\d+)?$/.test(input[key] as string)) data[key] = Number(input[key]);
|
||||
for (const [field, suffix] of [["stages", "ms"], ["stageCounts", "count"], ["stageOpen", "open"]]) {
|
||||
data[field] = Object.fromEntries(LOG_STAGES.map(stage => [stage, data[`stage_${stage}_${suffix}`]]));
|
||||
@@ -65,7 +68,7 @@ function safeRow(input: Record<string, unknown>): Row | null {
|
||||
for (const key of keys) if (typeof input[key] === "string") (identity as Record<string, unknown>)[key] = input[key];
|
||||
const projected = logContext.run(identity, () => logRecord(["error", "warn", "info", "debug"].includes(String(input.severity)) ? String(input.severity) : "info", String(input.module || "application"), ["", data]));
|
||||
const result: Row = { timestamp: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/.test(time) ? time : new Date(time).toISOString(), severity: String(projected.severity), service: services.includes(String(input.service)) ? String(input.service) : "unknown", event: events.has(String(input.event)) ? String(input.event) : "application_log", module: String(projected.module), release: /^(?:[a-f0-9]{7,40}|unknown)$/.test(String(input.release)) ? String(input.release) : "unknown" };
|
||||
for (const key of [...numeric, "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "outcome", "endpointKind", "cancellationOrigin", "cancellationEvidence", "hopId", "parentHopId", "errorCode", "requestId", "jobId", "queue", "route", "method", "errorType", "errorStack", "causeType", "causeStack", "repoId", "pullRequestId", "gistId", "userId", "viewer", "requestPath"]) if (typeof projected[key] === "string" || typeof projected[key] === "number") result[key] = projected[key] as string | number;
|
||||
for (const key of [...numeric, "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "outcome", "endpointKind", "cancellationOrigin", "cancellationEvidence", "hopId", "parentHopId", "errorCode", "requestId", "jobId", "queue", "route", "method", "errorType", "errorStack", "causeType", "causeStack", "repoId", "pullRequestId", "gistId", "userId", "viewer", "requestPath", "upstreamHost", "upstreamMethod", "upstreamEndpoint"]) if (typeof projected[key] === "string" || typeof projected[key] === "number") result[key] = projected[key] as string | number;
|
||||
if (validTraceId(input.instance)) result.instance = input.instance;
|
||||
return result;
|
||||
}
|
||||
@@ -86,6 +89,8 @@ async function rows(base: string, query: string, limit: number, signal: AbortSig
|
||||
return { records, partial: lines.length >= limit || rejected > 0 };
|
||||
}
|
||||
const range = (o: Options) => `_time:[${o.start}, ${o.end}]`;
|
||||
// Values are validated (validProjectId / validUserId) before they reach a query.
|
||||
const identity = (o: { repoId?: string; userId?: string }) => `${o.repoId ? ` repoId:"${o.repoId}"` : ""}${o.userId ? ` userId:"${o.userId}"` : ""}`;
|
||||
function grafana(o: Options) {
|
||||
try {
|
||||
const value = process.env.ADMIN_LOG_GRAFANA_URL;
|
||||
@@ -171,7 +176,7 @@ export async function investigateLogs(options: Options, correlation = false) {
|
||||
}
|
||||
// Historical collector output omits unknown releases and keeps edge 5xx at info.
|
||||
const release = options.release === "unknown" ? ' (release:unknown OR release:"")' : options.release ? ` release:${options.release}` : "";
|
||||
const filter = `${range(options)} (severity:error OR severity:warn OR (service:nginx event:edge_request status:>=500 status:<600))${options.service ? ` service:${options.service}` : ""}${release}`;
|
||||
const filter = `${range(options)} (severity:error OR severity:warn OR (service:nginx event:edge_request status:>=500 status:<600))${options.service ? ` service:${options.service}` : ""}${release}${identity(options)}`;
|
||||
const baselineStart = new Date(Date.parse(options.start) - 24 * 60 * 60 * 1000).toISOString();
|
||||
const compareRelease = options.release && options.release !== "unknown";
|
||||
const [errors, heartbeat, drops, baseline] = await Promise.all([
|
||||
@@ -195,3 +200,47 @@ export async function investigateLogs(options: Options, correlation = false) {
|
||||
} catch { return { ...common, state: "unreachable", groups: [], events: [] }; }
|
||||
finally { controller.abort(); clearTimeout(timer); active--; }
|
||||
}
|
||||
|
||||
type IssueSource = { window: string; start: string; end: string; service: string; repoId: string; userId: string };
|
||||
const FAULTS = "(severity:error OR severity:warn OR (service:nginx event:edge_request status:>=500 status:<600))";
|
||||
async function noiseCounts(base: string, query: string, signal: AbortSignal) {
|
||||
const text = await read(base + "/select/logsql/query", signal, new URLSearchParams({ query }));
|
||||
const counts = { slow: 0, interrupted: 0 };
|
||||
for (const line of text.split("\n").filter(Boolean).slice(0, 10)) {
|
||||
try {
|
||||
const row = JSON.parse(line); const n = Number(row.n);
|
||||
if (Number.isSafeInteger(n) && n >= 0) { if (row.event === "request_slow") counts.slow = n; if (row.event === "request_cancelled") counts.interrupted = n; }
|
||||
} catch { /* A malformed stats line only loses the count. */ }
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
/**
|
||||
* Records for the admin issue list: faults (slow and interrupted requests excluded
|
||||
* and only counted), expected responses logged at info, and failed external calls
|
||||
* that explain them. Same bounds and projection as investigateLogs.
|
||||
*/
|
||||
export async function issueRecords(options: IssueSource) {
|
||||
const o = { ...options, release: "", id: "", kind: "requestId" as const };
|
||||
const common = { source: "central", window: o.window, start: o.start, end: o.end, grafanaUrl: grafana(o) };
|
||||
let base: string | null;
|
||||
try { base = endpoint(process.env.ADMIN_LOG_URL); } catch { return { ...common, state: "misconfigured", records: [], external: [], noise: null }; }
|
||||
if (!base) return { ...common, state: "disabled", records: [], external: [], noise: null };
|
||||
if (active >= 2) return { ...common, state: "busy", records: [], external: [], noise: null };
|
||||
active++;
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), 4000); timer.unref();
|
||||
try {
|
||||
const scope = `${range(o)}${o.service ? ` service:${o.service}` : ""}${identity(o)}`;
|
||||
const noise = "(event:request_slow OR event:request_cancelled)";
|
||||
const [faults, expected, external, counts] = await Promise.all([
|
||||
rows(base, `${scope} ${FAULTS} NOT ${noise} NOT event:external_request | sort by (_time) desc`, 2001, controller.signal),
|
||||
rows(base, `${scope} severity:info errorCode:* NOT event:external_request | sort by (_time) desc`, 501, controller.signal),
|
||||
rows(base, `${range(o)} event:external_request (upstreamStatus:>=400 OR errorCode:*) | sort by (_time) desc`, 2001, controller.signal).catch(() => ({ records: [], partial: true })),
|
||||
noiseCounts(base, `${scope} ${noise} | stats by (event) count() n`, controller.signal).catch(() => null),
|
||||
]);
|
||||
const records = [...faults.records.slice(0, 2000), ...expected.records.slice(0, 500)];
|
||||
return { ...common, state: faults.partial || expected.partial ? "partial" : records.length ? "ready" : "empty", records, external: external.records.slice(0, 2000),
|
||||
externalPartial: external.partial, noise: counts, captured: records.length, limit: 2500 };
|
||||
} catch { return { ...common, state: "unreachable", records: [], external: [], noise: null }; }
|
||||
finally { controller.abort(); clearTimeout(timer); active--; }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { investigateLogs, logOptions, safeRedisLog } from "../admin-log-investigation";
|
||||
import { investigateLogs, issueRecords, logOptions, safeRedisLog } from "../admin-log-investigation";
|
||||
import { buildIssues, filterRows, issueOptions, IssueQuery, Row } from "../admin-error-issues";
|
||||
import { jobTrace } from "../../core/log-context";
|
||||
import { cacheMetricsReport } from "../../core/cache-observability";
|
||||
import { sharedBlobCache, resultBlobCache } from "../../core/blob-cache";
|
||||
@@ -113,6 +114,57 @@ for (const [path, correlation] of [["/errors/investigation", false], ["/errors/c
|
||||
});
|
||||
}
|
||||
|
||||
// Repository owners and user names for the issue pages. Bounded, and skipped
|
||||
// when the database is not connected so the error page never waits on it.
|
||||
async function issueNames(repoIds: string[], userIds: string[]) {
|
||||
const repos: Record<string, { ownerId?: string; owner?: string; source?: string; status?: string }> = {};
|
||||
const users: Record<string, string> = {};
|
||||
if (AnonymizedRepositoryModel.db.readyState !== 1 || (!repoIds.length && !userIds.length)) return { repos, users };
|
||||
try {
|
||||
const found = repoIds.length ? await AnonymizedRepositoryModel.find({ repoId: { $in: repoIds.slice(0, 100) } }, { repoId: 1, owner: 1, status: 1, "source.repositoryName": 1 }).lean().maxTimeMS(2000) : [];
|
||||
const owners = [...new Set([...found.map(repo => String(repo.owner || "")).filter(id => /^[a-f0-9]{24}$/.test(id)), ...userIds.slice(0, 100)])];
|
||||
const named = owners.length ? await UserModel.find({ _id: { $in: owners } }, { username: 1 }).lean().maxTimeMS(2000) : [];
|
||||
for (const user of named) users[String(user._id)] = String(user.username);
|
||||
for (const repo of found) {
|
||||
const ownerId = repo.owner ? String(repo.owner) : undefined;
|
||||
repos[repo.repoId] = { ownerId, owner: ownerId ? users[ownerId] : undefined, source: (repo.source as { repositoryName?: string } | undefined)?.repositoryName, status: repo.status };
|
||||
}
|
||||
} catch { /* Names are a convenience; IDs stay usable without them. */ }
|
||||
return { repos, users };
|
||||
}
|
||||
async function historyRows(query: IssueQuery) {
|
||||
if (errorLogActive >= ERROR_LOG_CONCURRENCY) return { state: "busy", rows: [] as Row[] };
|
||||
errorLogActive++;
|
||||
try {
|
||||
const client = await getErrorLogClient();
|
||||
if (!client) return { state: "unavailable", rows: [] as Row[] };
|
||||
const raw = await client.lRange(ERROR_LOG_KEY, 0, ERROR_LOG_MAX - 1);
|
||||
const rows = raw.flatMap(text => { try { const row = safeRedisLog(JSON.parse(text))?.raw?.[0]; return row ? [row as Row] : []; } catch { return []; } });
|
||||
return { state: "ready", rows: filterRows(rows, query) };
|
||||
} catch { return { state: "unavailable", rows: [] as Row[] }; }
|
||||
finally { errorLogActive--; }
|
||||
}
|
||||
// One list of issues: central logs when they answer, the Redis history otherwise.
|
||||
router.get("/errors/issues", async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
let query: IssueQuery;
|
||||
try { query = issueOptions(req.query as Record<string, unknown>); }
|
||||
catch { return res.status(400).json({ error: "invalid_request" }); }
|
||||
const central = query.source === "history" ? null : await issueRecords(query);
|
||||
const useCentral = central && ["ready", "partial", "empty"].includes(central.state);
|
||||
const history = useCentral ? null : await historyRows(query);
|
||||
const rows = useCentral ? central.records as Row[] : history!.rows;
|
||||
const built = buildIssues(rows, { start: query.start, end: query.end, external: useCentral ? central.external as Row[] : [] });
|
||||
if (useCentral && central.noise) built.excluded = central.noise;
|
||||
const names = await issueNames([...new Set(built.issues.flatMap(issue => issue.repos.map(repo => repo.id)))], [...new Set(built.issues.flatMap(issue => issue.users.map(user => user.id)))]);
|
||||
res.json({
|
||||
source: useCentral ? "central" : "history", state: useCentral ? central.state : history!.state,
|
||||
centralState: central?.state || "skipped", grafanaUrl: central?.grafanaUrl || null,
|
||||
window: query.window, start: query.start, end: query.end, filters: { service: query.service, repoId: query.repoId, userId: query.userId },
|
||||
captured: rows.length, redisCollecting: process.env.LOG_REDIS_MIRROR !== "off", ...built, names,
|
||||
});
|
||||
});
|
||||
|
||||
router.use("/tokens", adminTokensRouter);
|
||||
router.use("/billing", adminBillingRouter);
|
||||
router.use("/emails", adminEmailsRouter);
|
||||
|
||||
Reference in new issue
Block a user