Files
anonymous_github/src/server/admin-error-issues.ts
T
Thomas DurieuxandClaude Opus 5.5 fdd8f58944 fix(admin): split uncoded errors by crash site, label signed-in visitors, scope external calls
- Errors without a code are grouped by their first app stack frame (or the
  logging module), so unrelated TypeErrors no longer share one issue.
- "visitor" is a signed-in user with no role on the repository; it is no
  longer shown as "not signed in". Anonymous viewers are counted apart.
- The issue page no longer offers "Open user" next to "Open repository":
  users and repositories are counted from different records.
- With a service, repository or user filter, failed external calls are looked
  up by the faults' request IDs instead of the newest 2000 calls overall.
- The page says when the 2000-failure cap was reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:35:34 +00:00

289 lines
20 KiB
TypeScript
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 { 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 ACCOUNT_ROLES = 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";
}
/**
* Without an error code, the code or type alone says little: every TypeError in
* the API would share one issue. The first app stack frame (or the module that
* logged it) tells those crash sites apart.
*/
function uncodedSite(row: Row) {
if (row.errorCode || row.event === "edge_request") return "";
return firstFrame(row.errorStack) || String(row.module || "");
}
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"}`;
const site = uncodedSite(row);
const at = site ? ` in ${site}` : "";
if (!row.errorCode && row.errorType) return `Code crashed: ${row.errorType}${at}`;
if (row.event === "job_failed" && !row.errorCode) return `Background job failed${at}`;
return code.replace(/_/g, " ").replace(/^./, c => c.toUpperCase()) + at;
}
export function issueId(row: Row) {
// One cause (a GitHub limit, an outage) hits many routes: routes are listed inside the issue.
return createHash("sha256").update(JSON.stringify([codeOf(row), String(row.service || ""), uncodedSite(row)])).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) {
// The first frame in our code: dependencies and Node internals say little about the crash site.
const line = String(stack || "").split("\n").find(value => /\(?[\w./-]+\.[jt]s:\d+/.test(value) && !/node_modules|node:/.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);
// "visitor" is signed in without a role on the repository; "anonymous" has no session.
const viewers = { signedIn: 0, visitors: 0, anonymous: 0, notRecorded: 0 };
for (const row of sorted) viewers[ACCOUNT_ROLES.has(String(row.viewer)) ? "signedIn" : row.viewer === "visitor" ? "visitors" : row.viewer === "anonymous" ? "anonymous" : "notRecorded"]++;
const routeCounts = new Map<string, { route: string; method: string; count: number; last: string }>();
for (const row of sorted) {
const route = String(row.route || (row.queue ? `job ${row.queue}` : ""));
if (!route) continue;
const key = `${row.method || ""} ${route}`;
const entry = routeCounts.get(key) || { route, method: String(row.method || ""), count: 0, last: String(row.timestamp) };
entry.count++; routeCounts.set(key, entry);
}
const routes = [...routeCounts.values()].sort((a, b) => b.count - a.count || Date.parse(b.last) - Date.parse(a.last));
const top = routes[0];
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: top && !top.route.startsWith("job ") ? top.route : null, method: top?.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, routeCount: routes.length, routes: routes.slice(0, 20),
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));
}