feat(api): register GET /v1/incidents and detail; wire stats routes

Admin UI SSR calls /v1/incidents; routes were missing (404). Add incidents list/detail with errors:read and register admin stats routes in index.
This commit is contained in:
1sonhador committed 2026-03-29 21:17:48 +01:00
1 parent a3b65b4b3f
commit 988f9b8987
2 files changed
+215

No files matched your search

+4
View File
@@ -15,6 +15,8 @@ import rateLimitPlugin from './plugins/rate-limit.js';
import { INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES } from './plugins/rate-limit.js';
import adminAuthRoutes from './routes/admin/auth.js';
import adminStatsRoutes from './routes/admin/stats.js';
import adminIncidentsRoutes from './routes/admin/incidents.js';
const IS_PROD = process.env.NODE_ENV === 'production';
@@ -62,6 +64,8 @@ await app.register(rateLimitPlugin);
// Routes
await app.register(adminAuthRoutes);
await app.register(adminStatsRoutes);
await app.register(adminIncidentsRoutes);
// Health check
app.get('/health', async () => ({ ok: true, ts: new Date().toISOString() }));
+211
View File
@@ -0,0 +1,211 @@
/**
* Admin incident list and detail (read-only).
* GET /v1/incidents — query: state, severity, project (slug), q
* GET /v1/incidents/:id — detail + recent occurrences
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
const 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 rowDateToIso(v: unknown): string {
if (v instanceof Date) {
return v.toISOString();
}
if (typeof v === 'string') {
return new Date(v).toISOString();
}
return String(v);
}
export default async function adminIncidentsRoutes(app: FastifyInstance): Promise<void> {
const db = app.db;
const pre = [app.authenticate, app.requirePermission('errors:read')] as const;
app.get(
'/v1/incidents',
{
preHandler: [...pre],
schema: {
querystring: {
type: 'object',
properties: {
state: { type: 'string', enum: [...STATES] },
severity: { type: 'string', enum: [...SEVERITIES] },
project: { type: 'string', maxLength: 64 },
q: { type: 'string', maxLength: 200 },
},
additionalProperties: false,
},
},
},
async (request: FastifyRequest) => {
const q = request.query as {
state?: string;
severity?: string;
project?: string;
q?: string;
};
const conditions: string[] = ['1=1'];
const params: Array<string | number> = [];
if (q.state && (STATES as readonly string[]).includes(q.state)) {
conditions.push('i.current_state = ?');
params.push(q.state);
}
if (q.severity && (SEVERITIES as readonly string[]).includes(q.severity)) {
conditions.push('i.severity = ?');
params.push(q.severity);
}
if (q.project?.trim()) {
conditions.push('p.slug = ?');
params.push(q.project.trim().toLowerCase());
}
if (q.q?.trim()) {
const term = `%${q.q.trim()}%`;
conditions.push('(i.title LIKE ? OR i.fingerprint LIKE ? OR p.slug LIKE ?)');
params.push(term, term, term);
}
const sql = `
SELECT CAST(i.id AS CHAR) AS id,
p.slug AS projectSlug,
i.fingerprint,
i.title,
i.severity,
i.current_state AS currentState,
i.first_seen_at AS firstSeenAt,
i.last_seen_at AS lastSeenAt,
i.occurrences_count AS occurrencesCount
FROM er_incidents i
INNER JOIN er_projects p ON p.id = i.project_id
WHERE ${conditions.join(' AND ')}
ORDER BY i.last_seen_at DESC
LIMIT 500
`;
const [rows] = await db.execute<RowDataPacket[]>(sql, params);
const incidents = (rows as Record<string, unknown>[]).map((r) => ({
id: String(r.id),
projectSlug: String(r.projectSlug),
fingerprint: String(r.fingerprint),
title: String(r.title),
severity: String(r.severity),
currentState: String(r.currentState),
firstSeenAt: rowDateToIso(r.firstSeenAt),
lastSeenAt: rowDateToIso(r.lastSeenAt),
occurrencesCount: Number(r.occurrencesCount),
}));
return { incidents };
},
);
app.get<{ Params: { id: string } }>(
'/v1/incidents/:id',
{
preHandler: [...pre],
schema: {
params: {
type: 'object',
required: ['id'],
properties: {
id: { type: 'string', minLength: 1, maxLength: 32 },
},
},
},
},
async (request, reply) => {
const { id } = request.params;
if (!/^\d+$/.test(id)) {
return reply.code(404).send({ error: 'Not found', message: 'Invalid incident id' });
}
const [irows] = await db.execute<RowDataPacket[]>(
`SELECT CAST(i.id AS CHAR) AS id,
p.slug AS projectSlug,
i.fingerprint,
i.title,
i.severity,
i.current_state AS currentState,
i.first_seen_at AS firstSeenAt,
i.last_seen_at AS lastSeenAt,
i.occurrences_count AS occurrencesCount,
i.metadata_json AS metadataJson,
k.label AS ingestKeyLabel
FROM er_incidents i
INNER JOIN er_projects p ON p.id = i.project_id
LEFT JOIN er_ingest_keys k ON k.id = i.last_ingest_key_id
WHERE i.id = ?
LIMIT 1`,
[id],
);
const ir = irows[0] as Record<string, unknown> | undefined;
if (!ir) {
return reply.code(404).send({ error: 'Not found', message: 'Incidente não encontrado.' });
}
const [orows] = await db.execute<RowDataPacket[]>(
`SELECT CAST(o.id AS CHAR) AS id,
o.occurred_at AS occurredAt,
o.level_raw AS levelRaw,
o.severity,
o.message,
o.stack_trace AS stacktrace,
o.context_json AS contextJson
FROM er_incident_occurrences o
WHERE o.incident_id = ?
ORDER BY o.occurred_at DESC
LIMIT 200`,
[id],
);
const occurrences = (orows as Record<string, unknown>[]).map((o) => ({
id: String(o.id),
occurredAt: rowDateToIso(o.occurredAt),
levelRaw: String(o.levelRaw),
severity: String(o.severity),
message: String(o.message),
stacktrace: o.stacktrace != null ? String(o.stacktrace) : null,
contextJson: parseJsonObject(o.contextJson != null ? String(o.contextJson) : null),
}));
const incident = {
id: String(ir.id),
projectSlug: String(ir.projectSlug),
fingerprint: String(ir.fingerprint),
title: String(ir.title),
severity: String(ir.severity),
currentState: String(ir.currentState),
firstSeenAt: rowDateToIso(ir.firstSeenAt),
lastSeenAt: rowDateToIso(ir.lastSeenAt),
occurrencesCount: Number(ir.occurrencesCount),
metadataJson: parseJsonObject(ir.metadataJson != null ? String(ir.metadataJson) : null),
ingestKeyLabel: ir.ingestKeyLabel != null ? String(ir.ingestKeyLabel) : null,
occurrences,
};
return reply.send({ incident });
},
);
}