mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
feat: add operational incident evidence and recovering alerts
This commit is contained in:
1 parent
a4f441f097
commit
0f9d8c657a
18 files changed
+558
-123
No files matched your search
@@ -1079,6 +1079,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getRedis",
|
||||
"hourKey",
|
||||
"persistError",
|
||||
"reportOutputDrops",
|
||||
"resolveThreshold",
|
||||
"serializeError",
|
||||
"trimErrorLike",
|
||||
@@ -1096,6 +1097,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"getRedis",
|
||||
"hourKey",
|
||||
"persistError",
|
||||
"reportOutputDrops",
|
||||
"resolveThreshold",
|
||||
"serializeError",
|
||||
"trimErrorLike",
|
||||
@@ -2205,7 +2207,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"collector",
|
||||
"endpoint",
|
||||
"grafana",
|
||||
"group",
|
||||
"incidentGroups",
|
||||
"investigateLogs",
|
||||
"logOptions",
|
||||
"range",
|
||||
@@ -2213,6 +2215,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"rows",
|
||||
"safeRedisLog",
|
||||
"safeRow",
|
||||
"signature",
|
||||
"timestampKey"
|
||||
],
|
||||
"build/server/admin-log-investigation.js": [
|
||||
@@ -2220,7 +2223,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"collector",
|
||||
"endpoint",
|
||||
"grafana",
|
||||
"group",
|
||||
"incidentGroups",
|
||||
"investigateLogs",
|
||||
"logOptions",
|
||||
"range",
|
||||
@@ -2228,6 +2231,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"rows",
|
||||
"safeRedisLog",
|
||||
"safeRow",
|
||||
"signature",
|
||||
"timestampKey"
|
||||
],
|
||||
"src/server/dailyStatsSnapshot.ts": [
|
||||
|
||||
@@ -10,7 +10,7 @@ import { logContext, validTraceId } from "./log-context";
|
||||
const instance = randomUUID();
|
||||
const allowed = (values: readonly string[], value: unknown): value is string => typeof value === "string" && values.includes(value);
|
||||
const events: Record<string, string> = {
|
||||
...LOG_EVENTS,
|
||||
...LOG_EVENTS, deployment: "deployment",
|
||||
request: "request_completed", "slow request": "request_slow", "request interrupted": "request_cancelled",
|
||||
"process fatal error": "process_fatal_error", "process started": "process_started",
|
||||
"process heartbeat": "process_heartbeat", "job started": "job_started", "job completed": "job_completed",
|
||||
@@ -18,19 +18,19 @@ const events: Record<string, string> = {
|
||||
};
|
||||
const errorCodes = new Set([
|
||||
...ERROR_CODES,
|
||||
"token_refresh_failed", "quota_exceeded", "github_rate_limit_exceeded", "github_app_reconnect_required", "github_token_invalid",
|
||||
"repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "token_refresh_failed", "quota_exceeded", "github_rate_limit_exceeded", "github_app_reconnect_required", "github_token_invalid",
|
||||
"repository_expired", "repository_not_ready", "repository_not_found", "repository_job_cancelled",
|
||||
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE", "ABORT_ERR",
|
||||
"upstream_error", "upstream_timeout", "invalid_signature", "webhook_processing_failed",
|
||||
]);
|
||||
export const LOG_NUMBERS = ["expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
|
||||
export const LOG_NUMBERS = ["restartMs", "exitCode","droppedLogsInterval","expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
|
||||
"attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed",
|
||||
"oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus"];
|
||||
export const LOG_STAGES = ["transfer", "database","repository", "credential_resolution", "upstream", "cache_lookup", "cache_fill", "worker_wait", "anonymize", "streamer_headers"];
|
||||
export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
const context = logContext.getStore() || {};
|
||||
const details: Record<string, unknown> = {};
|
||||
const keys = [...LOG_NUMBERS, "requestId", "jobId", "hopId", "parentHopId", "cancellationOrigin", "cancellationEvidence", "endpointKind", "stageCounts", "stageOpen", "code", "message", "outcome", "method", "route", "queue",
|
||||
const keys = [...LOG_NUMBERS, "requestId", "jobId", "hopId", "parentHopId", "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "cancellationOrigin", "cancellationEvidence", "endpointKind", "stageCounts", "stageOpen", "code", "message", "outcome", "method", "route", "queue",
|
||||
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service"];
|
||||
// Do not traverse arbitrary objects or invoke error getters while logging.
|
||||
for (const arg of args.slice(0, 8)) if (arg && typeof arg === "object") {
|
||||
@@ -50,8 +50,8 @@ export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
service: context.service || (allowed(["api", "streamer", "worker"], details.service) ? details.service : undefined) || (process.env.SERVICE_NAME?.toLowerCase() === "streamer" ? "streamer" : "api"),
|
||||
instance, release: /^[a-f0-9]{7,40}$/.test(process.env.APP_RELEASE || "") ? process.env.APP_RELEASE : "unknown",
|
||||
event, message: event, module: LOG_MODULES.includes(module) ? module : "application" };
|
||||
for (const key of ["requestId", "jobId", "hopId", "parentHopId"] as const) {
|
||||
const value = details[key] || context[key];
|
||||
for (const key of ["requestId", "jobId", "hopId", "parentHopId", "deploymentId"] as const) {
|
||||
const value = details[key] || (key === "deploymentId" ? undefined : context[key]);
|
||||
if (validTraceId(value)) record[key] = value;
|
||||
}
|
||||
if (Number.isSafeInteger(context.attempt)) record.attempt = context.attempt;
|
||||
@@ -64,7 +64,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
|
||||
if (validTraceId(details.deliveryId)) record.deliveryId = details.deliveryId;
|
||||
if (allowed(["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com"], details.hostname)) record.upstreamHost = details.hostname;
|
||||
else if (details.hostname) record.upstreamHost = "other";
|
||||
for (const [key, values] of Object.entries({ cancellationOrigin: ["unknown", "api", "streamer", "timeout", "upstream"],
|
||||
for (const [key, values] of Object.entries({ deploymentOperation: ["deploy", "rollback"], deploymentPhase: ["start", "restart", "finish"], deploymentOutcome: ["started", "completed", "failed", "unchanged"], cancellationOrigin: ["unknown", "api", "streamer", "timeout", "upstream"],
|
||||
cancellationEvidence: ["response_close", "request_aborted", "upstream_error", "timeout", "local_abort"], endpointKind: ["public", "internal"] })) {
|
||||
if (allowed(values, details[key])) record[key] = details[key];
|
||||
}
|
||||
|
||||
@@ -93,6 +93,13 @@ let errorOutputBroken = false;
|
||||
process.stdout.on("error", () => { outputBroken = true; droppedOutput++; });
|
||||
process.stderr.on("error", () => { errorOutputBroken = true; droppedOutput++; });
|
||||
export function getDroppedOutput() { return droppedOutput; }
|
||||
let reportedDrops = 0;
|
||||
/** Advance the interval only when emitting the report did not itself drop a record. */
|
||||
export function reportOutputDrops(report: (fields: { droppedLogs: number; droppedLogsInterval: number }) => void) {
|
||||
const before = droppedOutput;
|
||||
report({ droppedLogs: before, droppedLogsInterval: Math.max(0, before - reportedDrops) });
|
||||
if (droppedOutput === before) reportedDrops = before;
|
||||
}
|
||||
export function getInProcessDropped(): number {
|
||||
return droppedInProcess;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { logMemory } from "./log-memory";
|
||||
import { createLogger, serializeError, getDroppedOutput } from "./logger";
|
||||
import { createLogger, serializeError, reportOutputDrops } from "./logger";
|
||||
|
||||
/** Observe fatal errors without overriding Node's default exit behavior. */
|
||||
export function installFatalErrorLogging(service: "api" | "streamer") {
|
||||
@@ -9,8 +9,8 @@ export function installFatalErrorLogging(service: "api" | "streamer") {
|
||||
});
|
||||
logger.info("process started", { service });
|
||||
const heartbeat = setInterval(() => {
|
||||
void logMemory().then(memory => logger.info("process heartbeat", {
|
||||
service, uptime: process.uptime(), ...memory, droppedLogs: getDroppedOutput() }));
|
||||
void logMemory().then(memory => reportOutputDrops(drops => logger.info("process heartbeat", {
|
||||
service, uptime: process.uptime(), ...memory, ...drops })));
|
||||
}, 30000);
|
||||
heartbeat.unref();
|
||||
process.on("uncaughtExceptionMonitor", report);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { logMemory } from "../core/log-memory";
|
||||
import { randomUUID } from "crypto";
|
||||
import { SandboxedJob } from "bullmq";
|
||||
import { logContext, validTraceId } from "../core/log-context";
|
||||
import { createLogger, getDroppedOutput } from "../core/logger";
|
||||
import { createLogger, reportOutputDrops } from "../core/logger";
|
||||
import type { RepoJobData } from "./index";
|
||||
const logger = createLogger("queue");
|
||||
export function loggedJob(queue: "download" | "remove" | "cache", work: (job: SandboxedJob<RepoJobData, void>) => Promise<void>) {
|
||||
@@ -14,14 +14,14 @@ export function loggedJob(queue: "download" | "remove" | "cache", work: (job: Sa
|
||||
logger.info("job started", { queue });
|
||||
const started = Date.now();
|
||||
const heartbeat = setInterval(() => {
|
||||
void logMemory().then(memory => logger.info("process heartbeat", { queue, ...memory, uptime: process.uptime(), droppedLogs: getDroppedOutput() }));
|
||||
void logMemory().then(memory => reportOutputDrops(drops => logger.info("process heartbeat", { queue, ...memory, uptime: process.uptime(), ...drops })));
|
||||
}, 30000); heartbeat.unref();
|
||||
try {
|
||||
await work(job);
|
||||
logger.info("job completed", { queue, ms: Date.now() - started, droppedLogs: getDroppedOutput() });
|
||||
reportOutputDrops(drops => logger.info("job completed", { queue, ms: Date.now() - started, ...drops }));
|
||||
} catch (error) {
|
||||
const expected = error instanceof Error && ["DelayedError", "RateLimitDelayError"].includes(error.name);
|
||||
logger[expected ? "info" : "error"]("job failed", { queue, ms: Date.now() - started, droppedLogs: getDroppedOutput() });
|
||||
reportOutputDrops(drops => logger[expected ? "info" : "error"]("job failed", { queue, ms: Date.now() - started, ...drops }));
|
||||
throw error;
|
||||
} finally { clearInterval(heartbeat); }
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { logContext, validTraceId } from "../core/log-context";
|
||||
import { LOG_EVENTS } from "../core/log-schema";
|
||||
|
||||
const services = ["api", "streamer", "worker", "nginx", "mongodb", "redis", "backup"];
|
||||
const events = new Set([...Object.values(LOG_EVENTS), "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"]);
|
||||
const windows: Record<string, number> = { "15m": 15, "1h": 60, "6h": 360, "24h": 1440 };
|
||||
let active = 0;
|
||||
export class InvalidLogQuery extends Error {}
|
||||
@@ -59,7 +59,7 @@ function safeRow(input: Record<string, unknown>): Row | null {
|
||||
// Revalidate finite route and diagnostic allowlists; never pass raw strings.
|
||||
const projected = logContext.run({}, () => 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, "outcome", "endpointKind", "cancellationOrigin", "cancellationEvidence", "hopId", "parentHopId", "errorCode", "requestId", "jobId", "queue", "route", "method", "errorType", "errorStack", "causeType", "causeStack", "repoId", "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", "requestPath"]) 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;
|
||||
}
|
||||
@@ -88,6 +88,8 @@ function grafana(o: Options) {
|
||||
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
|
||||
url.search = ""; url.hash = "";
|
||||
url.searchParams.set("from", String(Date.parse(o.start))); url.searchParams.set("to", String(Date.parse(o.end)));
|
||||
if (o.service) url.searchParams.set("var-service", `^${o.service}$`);
|
||||
if (o.release) url.searchParams.set("var-release", `^${o.release}$`);
|
||||
if (o.id) url.searchParams.set(o.kind === "jobId" ? "var-job_id" : "var-request_id", o.id);
|
||||
return url.toString();
|
||||
} catch { return null; }
|
||||
@@ -97,16 +99,28 @@ function grafana(o: Options) {
|
||||
function timestampKey(value: string | number) {
|
||||
return String(value).replace(/(?:\.(\d+))?Z$/, (_match, fraction = "") => `.${fraction.padEnd(9, "0")}Z`);
|
||||
}
|
||||
function group(records: Row[]) {
|
||||
const groups = new Map<string, { fingerprint: string; count: number; first: string; last: string; sample: Row }>();
|
||||
export function incidentGroups(records: Row[], baseline?: { records: Row[]; partial: boolean }) {
|
||||
const signature = (row: Row) => JSON.stringify([row.service, row.module, row.event, row.errorCode || "", row.severity,
|
||||
row.status || row.httpStatus || "", row.errorType || "", String(row.errorStack || "").split("\n")[0].replace(/:\d+:\d+\)$/, ")")]);
|
||||
const known = new Set((baseline?.records || []).map(signature));
|
||||
const groups = new Map<string, { fingerprint: string; count: number; first: string; last: string; sample: Row;
|
||||
requests: Set<string>; uncorrelatedRecords: number; releases: Set<string>; regression: string }>();
|
||||
for (const row of records) {
|
||||
const key = JSON.stringify([row.service, row.module, row.event, row.errorCode || "", row.severity, row.status || row.httpStatus || "", row.errorType || "", String(row.errorStack || "").split("\n")[0]]);
|
||||
const key = signature(row);
|
||||
const fingerprint = createHash("sha256").update(key).digest("hex").slice(0, 24);
|
||||
const existing = groups.get(fingerprint);
|
||||
let existing = groups.get(fingerprint);
|
||||
if (existing) { existing.count++; existing.first = timestampKey(existing.first) < timestampKey(row.timestamp) ? existing.first : String(row.timestamp); existing.last = timestampKey(existing.last) > timestampKey(row.timestamp) ? existing.last : String(row.timestamp); }
|
||||
else groups.set(fingerprint, { fingerprint, count: 1, first: String(row.timestamp), last: String(row.timestamp), sample: row });
|
||||
else {
|
||||
existing = { fingerprint, count: 1, first: String(row.timestamp), last: String(row.timestamp), sample: row,
|
||||
requests: new Set(), releases: new Set(), uncorrelatedRecords: 0,
|
||||
regression: known.has(key) ? "known" : baseline && !baseline.partial && baseline.records.length ? "not_seen_in_baseline" : "unknown" };
|
||||
groups.set(fingerprint, existing);
|
||||
}
|
||||
if (validTraceId(row.requestId)) existing.requests.add(row.requestId); else existing.uncorrelatedRecords++;
|
||||
if (typeof row.release === "string") existing.releases.add(row.release);
|
||||
}
|
||||
return [...groups.values()].sort((a, b) => timestampKey(b.last).localeCompare(timestampKey(a.last)));
|
||||
return [...groups.values()].map(({ requests, releases, ...value }) => ({ ...value, affectedRequests: requests.size, releases: [...releases] }))
|
||||
.sort((a, b) => timestampKey(b.last).localeCompare(timestampKey(a.last)));
|
||||
}
|
||||
async function collector(signal: AbortSignal) {
|
||||
try {
|
||||
@@ -152,10 +166,13 @@ 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 [errors, heartbeat, drops] = await Promise.all([
|
||||
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([
|
||||
rows(base, `${filter} | sort by (_time) desc`, 1001, controller.signal),
|
||||
rows(base, '_time:5m (event:process_heartbeat OR event:queue_heartbeat OR event:job_completed OR event:job_failed) | sort by (_time) desc', 501, controller.signal),
|
||||
collector(controller.signal),
|
||||
compareRelease ? rows(base, `_time:[${baselineStart}, ${options.start}) (severity:error OR severity:warn OR (service:nginx event:edge_request status:>=500 status:<600))${options.service ? ` service:${options.service}` : ""} NOT release:${options.release} NOT release:unknown NOT release:"" | sort by (_time) desc`, 1001, controller.signal) : Promise.resolve(undefined),
|
||||
]);
|
||||
const latest = new Map<string, Row>();
|
||||
for (const row of heartbeat.records) {
|
||||
@@ -167,7 +184,8 @@ export async function investigateLogs(options: Options, correlation = false) {
|
||||
const queues = new Set(recent.filter(row => row.event === "queue_heartbeat").map(row => row.queue).filter(Boolean)).size;
|
||||
const missing = [...(!recent.some(row => row.service === "api" && row.event === "process_heartbeat") ? ["API"] : []), ...(streamers < 4 ? ["streamers"] : []), ...(queues < 3 ? ["queues"] : [])];
|
||||
const records = errors.records.slice(0, 1000);
|
||||
return { ...common, state: errors.partial || heartbeat.partial ? "partial" : missing.length ? "stale" : records.length ? "ready" : "empty", groups: group(records), captured: records.length, limit: 1000, telemetry: { missing, streamers, queues, partial: heartbeat.partial, instances: [...latest.values()].map(row => ({ service: row.service, instance: row.instance, last: row.timestamp, dropped: row.droppedLogs ?? null })), collector: drops } };
|
||||
return { ...common, state: errors.partial || heartbeat.partial ? "partial" : missing.length ? "stale" : records.length ? "ready" : "empty", groups: incidentGroups(records, baseline), baseline: baseline ? { start: baselineStart, end: options.start, captured: baseline.records.length,
|
||||
partial: baseline.partial, comparison: "other_releases_previous_24h" } : null, captured: records.length, limit: 1000, telemetry: { missing, streamers, queues, partial: heartbeat.partial, instances: [...latest.values()].map(row => ({ service: row.service, instance: row.instance, last: row.timestamp, dropped: row.droppedLogs ?? null })), collector: drops } };
|
||||
} catch { return { ...common, state: "unreachable", groups: [], events: [] }; }
|
||||
finally { controller.abort(); clearTimeout(timer); active--; }
|
||||
}
|
||||
Reference in new issue
Block a user