Files
errors.bitreport.pt/api/src/routes/public/recentErrors.ts
T

363 lines
13 KiB
TypeScript

/**
* Paperclip / CRM-compatible listing for incidents (open by default; filters optional).
* Paths (same handler):
* GET /api/error-monitoring/recent-errors?limit=&offset=&api_key=|view_errors=
* GET /v1/paperclip/recent-errors?...
*
* Optional query filters (hub extension, backward compatible when omitted):
* status — comma-separated: open,investigating,resolved,ignored (default: open,investigating)
* severity — critical|high|medium|low|info
* project_slug — project slug (lowercase)
* q — search title, message, fingerprint (LIKE)
* order — occurred_at_desc (default) | occurred_at_asc
*
* Auth: query param must match ERROR_RESOLVE_API_KEY or ERROR_REPORTING_API_KEY (api_key),
* or DEBUG_VIEW_ERRORS_KEY (view_errors). At least one server secret must be configured.
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import { authorizeReadQuery } from '../../lib/errorMonitoringAuth.js';
import { synthesizeStackTraceForDisplay } from '../../lib/synthesizeStackTraceForDisplay.js';
const INCIDENT_STATES = ['open', 'investigating', 'resolved', 'ignored'] as const;
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
function parseJsonObject(raw: string | null): Record<string, unknown> | null {
if (raw == null || raw === '') {
return null;
}
try {
const v = JSON.parse(raw) as unknown;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
return v as Record<string, unknown>;
}
return null;
} catch {
return null;
}
}
function toIsoOccurredAt(value: unknown): string {
if (value == null) {
return '';
}
if (value instanceof Date) {
return value.toISOString();
}
const s = String(value).trim();
if (s === '') {
return '';
}
const t = Date.parse(s);
if (Number.isNaN(t)) {
return s;
}
return new Date(t).toISOString();
}
function extractFileLine(ctx: Record<string, unknown> | null): { file_path: string; line_number: string } {
if (!ctx) {
return { file_path: '', line_number: '' };
}
const file_path = String(ctx.file_path ?? ctx.filename ?? ctx.path ?? ctx.file ?? '').trim();
const line_number = String(ctx.line_number ?? ctx.lineno ?? ctx.line ?? '').trim();
return { file_path, line_number };
}
function ctxStr(ctx: Record<string, unknown> | null, keys: string[]): string {
if (!ctx) return '';
for (const k of keys) {
const v = ctx[k];
if (typeof v === 'string' && v.trim() !== '') return v.trim();
}
return '';
}
/** Paperclip error loop reads top-level `gitea_repo` on each recent-error row. */
function extractGiteaRepo(ctx: Record<string, unknown> | null): string {
if (!ctx) {
return '';
}
const raw = ctx.gitea_repo ?? ctx.giteaRepo ?? ctx.repo_full_name ?? ctx.repository;
return typeof raw === 'string' ? raw.trim() : '';
}
/** Paperclip error loop reads top-level `paperclip_project_id` to route issues to the correct project. */
function extractPaperclipProjectId(ctx: Record<string, unknown> | null): string {
if (!ctx) {
return '';
}
const raw = ctx.paperclip_project_id ?? ctx.paperclipProjectId;
return typeof raw === 'string' ? raw.trim() : '';
}
function parseStatusList(raw: string | undefined): string[] | null {
if (raw == null || raw.trim() === '') {
return ['open', 'investigating'];
}
const parts = raw
.split(',')
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
const allowed = new Set(INCIDENT_STATES as readonly string[]);
for (const p of parts) {
if (!allowed.has(p)) {
return null;
}
}
return parts.length > 0 ? parts : ['open', 'investigating'];
}
function slimContext(ctx: Record<string, unknown> | null): Record<string, unknown> | null {
if (!ctx) return null;
const out: Record<string, unknown> = {};
for (const key of Object.keys(ctx).slice(0, 40)) out[key] = slimContextValue(ctx[key], 0);
return out;
}
function slimContextValue(value: unknown, depth: number): unknown {
if (depth > 3) return '[nested]';
if (typeof value === 'string') return value.length > 1500 ? `${value.slice(0, 1500)}…` : value;
if (value == null || typeof value === 'number' || typeof value === 'boolean') return value;
if (Array.isArray(value)) return value.slice(0, 20).map((item) => slimContextValue(item, depth + 1));
if (typeof value === 'object') {
const nested: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>).slice(0, 30)) {
nested[key] = slimContextValue(item, depth + 1);
}
return nested;
}
return String(value).slice(0, 500);
}
async function handleRecentErrors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const db = request.server.db;
if (!authorizeReadQuery(request, reply)) {
return;
}
const q = request.query as {
limit?: string;
offset?: string;
status?: string;
severity?: string;
project_slug?: string;
q?: string;
order?: string;
};
let limit = 999999;
if (q.limit != null && q.limit !== '') {
const n = parseInt(String(q.limit), 10);
if (!Number.isFinite(n) || n < 1) {
return void reply.code(400).send({ success: false, message: 'Invalid limit' });
}
limit = Math.min(n, 999999);
}
let offset = 0;
if (q.offset != null && q.offset !== '') {
const o = parseInt(String(q.offset), 10);
if (!Number.isFinite(o) || o < 0) {
return void reply.code(400).send({ success: false, message: 'Invalid offset' });
}
offset = Math.min(o, 10_000_000);
}
const states = parseStatusList(q.status);
if (!states) {
return void reply.code(400).send({
success: false,
message: `Invalid status (use comma-separated: ${INCIDENT_STATES.join(',')})`,
});
}
if (q.severity != null && q.severity !== '') {
const sev = q.severity.trim().toLowerCase();
if (!(SEVERITIES as readonly string[]).includes(sev)) {
return void reply.code(400).send({
success: false,
message: `Invalid severity (allowed: ${SEVERITIES.join(',')})`,
});
}
}
const orderRaw = (q.order ?? 'occurred_at_desc').trim().toLowerCase();
const orderSql =
orderRaw === 'occurred_at_asc' ? 'r.occurred_at ASC, r.id ASC' : 'r.occurred_at DESC, r.id DESC';
const statePlaceholders = states.map(() => '?').join(', ');
const incidentConditions: string[] = [`i.current_state IN (${statePlaceholders})`];
const incidentParams: Array<string | number> = [...states];
if (q.severity != null && q.severity !== '') {
incidentConditions.push('i.severity = ?');
incidentParams.push(q.severity.trim().toLowerCase());
}
if (q.project_slug != null && q.project_slug.trim() !== '') {
incidentConditions.push('p.slug = ?');
incidentParams.push(q.project_slug.trim().toLowerCase());
}
const incidentWhereClause = incidentConditions.join(' AND ');
const hasSearch = q.q != null && q.q.trim() !== '';
let sql: string;
let params: Array<string | number>;
if (!hasSearch) {
// Fast path (BIT-29730, tightened in BIT-30040): page through er_incidents
// first (small, indexed by current_state) and fetch only the single latest
// occurrence per selected incident via a correlated subquery. Earlier this
// still used ROW_NUMBER() over ALL occurrences of the selected incidents —
// MariaDB can't turn PARTITION BY into a loose index scan, so it
// materialized and sorted the entire occurrence history of every matching
// incident before filtering rn = 1. Fleet-audit-scale "mega-incidents"
// (100k+ occurrences each) blew that up to minutes even after the
// incident-first paging fix. A `LIMIT 1` correlated subquery per incident
// instead walks er_incident_occurrences_incident_time_idx
// (incident_id, occurred_at DESC) and stops at the first row — no
// materialization of the rest of that incident's history.
const incidentOrderDir = orderRaw === 'occurred_at_asc' ? 'ASC' : 'DESC';
sql = `
WITH selected_incidents AS (
SELECT i.id AS incident_id
FROM er_incidents i
INNER JOIN er_projects p ON p.id = i.project_id
WHERE ${incidentWhereClause}
ORDER BY i.last_seen_at ${incidentOrderDir}, i.id ${incidentOrderDir}
LIMIT ? OFFSET ?
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
p.slug AS project_slug,
i.severity AS incident_severity,
i.current_state AS incident_state,
r.message,
r.stack_trace,
r.context_json,
r.environment,
r.occurred_at
FROM selected_incidents si
INNER JOIN er_incidents i ON i.id = si.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
INNER JOIN er_incident_occurrences r ON r.id = (
SELECT o.id
FROM er_incident_occurrences o
WHERE o.incident_id = si.incident_id
ORDER BY o.occurred_at DESC, o.id DESC
LIMIT 1
)
ORDER BY ${orderSql}
`;
params = [...incidentParams, limit, offset];
} else {
// Search path: `q` matches against occurrence message too, so an incident's
// latest occurrence isn't necessarily the one that matched. Keep the
// original occurrence-first scan for correctness; status=resolved + q can
// still be slow (not the case reported in BIT-29730, tracked separately).
const term = `%${q.q!.trim()}%`;
const conditions = [...incidentConditions, '(i.title LIKE ? OR o.message LIKE ? OR i.fingerprint LIKE ?)'];
const whereClause = conditions.join(' AND ');
sql = `
WITH ranked AS (
SELECT o.id,
o.incident_id,
o.message,
o.stack_trace AS stack_trace,
o.context_json AS context_json,
o.environment,
o.occurred_at AS occurred_at,
ROW_NUMBER() OVER (PARTITION BY o.incident_id ORDER BY o.occurred_at DESC, o.id DESC) AS rn
FROM er_incident_occurrences o
INNER JOIN er_incidents i ON i.id = o.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE ${whereClause}
)
SELECT CAST(i.id AS CHAR) AS incident_id,
CAST(r.id AS CHAR) AS occurrence_id,
p.slug AS project_slug,
i.severity AS incident_severity,
i.current_state AS incident_state,
r.message,
r.stack_trace,
r.context_json,
r.environment,
r.occurred_at
FROM ranked r
INNER JOIN er_incidents i ON i.id = r.incident_id
INNER JOIN er_projects p ON p.id = i.project_id
WHERE r.rn = 1
ORDER BY ${orderSql}
LIMIT ? OFFSET ?
`;
params = [...incidentParams, term, term, term, limit, offset];
}
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
const data = (rows as Record<string, unknown>[]).map((row) => {
const ctx = parseJsonObject(row.context_json != null ? String(row.context_json) : null);
const { file_path, line_number } = extractFileLine(ctx);
const gitea_repo = extractGiteaRepo(ctx);
const paperclip_project_id = extractPaperclipProjectId(ctx);
const incSev = String(row.incident_severity ?? 'medium').toLowerCase();
const sev = ['critical', 'high', 'medium', 'low'].includes(incSev) ? incSev : 'medium';
const st = String(row.incident_state ?? 'open').toLowerCase();
const message = String(row.message ?? '');
const rawStack =
row.stack_trace != null && String(row.stack_trace).trim() !== ''
? String(row.stack_trace).trim()
: '';
const stack_trace =
rawStack !== '' ? rawStack : synthesizeStackTraceForDisplay(message, ctx);
const rowOut: Record<string, unknown> = {
status: st === 'resolved' ? 'resolved' : st === 'ignored' ? 'ignored' : 'open',
message,
error_message: message,
stack_trace,
file_path,
line_number,
severity: sev,
unique_id: String(row.occurrence_id ?? row.incident_id ?? ''),
project_slug: String(row.project_slug ?? '').toLowerCase(),
environment: String(row.environment ?? 'production'),
occurred_at: toIsoOccurredAt(row.occurred_at),
};
if (gitea_repo !== '') {
rowOut.gitea_repo = gitea_repo;
}
const extra: Record<string, string> = {
component: ctxStr(ctx, ['component']),
release_version: ctxStr(ctx, ['release_version', 'release', 'app_version']),
runtime_name: ctxStr(ctx, ['runtime_name', 'runtime']),
host_name: ctxStr(ctx, ['host_name', 'hostname', 'host']),
};
for (const [k, v] of Object.entries(extra)) {
if (v !== '') rowOut[k] = v;
}
if (paperclip_project_id !== '') {
rowOut.paperclip_project_id = paperclip_project_id;
}
const contextData = slimContext(ctx);
if (contextData) rowOut.context_data = contextData;
return rowOut;
});
return void reply.send({
success: true,
message: 'ok',
data,
});
}
export default async function recentErrorsPublicRoutes(app: FastifyInstance): Promise<void> {
app.get('/api/error-monitoring/recent-errors', handleRecentErrors);
app.get('/v1/paperclip/recent-errors', handleRecentErrors);
}