chore(api): add admin stats routes source (required by index register)

This commit is contained in:
1sonhador committed 2026-03-29 21:17:55 +01:00
1 parent 988f9b8987
commit 0a8918ed00
1 file changed
+249
+249
View File
@@ -0,0 +1,249 @@
/**
* Admin statistics for dashboard charts.
* GET /v1/stats/trend — occurrences per day × severity
* GET /v1/stats/summary — incidents by project/state, severity totals, 24h activity
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
type Severity = (typeof SEVERITIES)[number];
function isSeverity(s: string): s is Severity {
return (SEVERITIES as readonly string[]).includes(s);
}
function parseDays(raw: string | undefined): number {
if (raw === undefined || raw === '') {
return 30;
}
const n = parseInt(raw, 10);
if (!Number.isFinite(n) || n < 1) {
return 30;
}
if (n > 366) {
return 366;
}
return n;
}
/** UTC calendar date string YYYY-MM-DD for each day in [startDay, endDay] inclusive. */
function enumerateUtcDatesInclusive(startDay: string, endDay: string): string[] {
const out: string[] = [];
let cur = startDay;
while (cur <= endDay) {
out.push(cur);
const d = new Date(`${cur}T00:00:00.000Z`);
d.setUTCDate(d.getUTCDate() + 1);
cur = d.toISOString().slice(0, 10);
}
return out;
}
function utcTodayString(): string {
const now = new Date();
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()))
.toISOString()
.slice(0, 10);
}
export default async function adminStatsRoutes(app: FastifyInstance): Promise<void> {
const db = app.db;
const pre = [app.authenticate, app.requirePermission('errors:read')] as const;
app.get(
'/v1/stats/trend',
{
preHandler: [...pre],
schema: {
querystring: {
type: 'object',
properties: {
days: { type: 'string' },
project: { type: 'string', maxLength: 64 },
},
additionalProperties: false,
},
},
},
async (request: FastifyRequest, reply: FastifyReply) => {
const q = request.query as { days?: string; project?: string };
const days = parseDays(q.days);
const projectSlug = q.project?.trim() || null;
const endDay = utcTodayString();
const startDate = new Date(`${endDay}T00:00:00.000Z`);
startDate.setUTCDate(startDate.getUTCDate() - (days - 1));
const startDay = startDate.toISOString().slice(0, 10);
const dates = enumerateUtcDatesInclusive(startDay, endDay);
if (dates.length !== days) {
request.log.warn({ daysRequested: days, datesLen: dates.length }, 'stats.trend date range mismatch');
}
const rangeStart = `${startDay} 00:00:00.000000`;
const rangeEndExclusiveDate = new Date(`${endDay}T00:00:00.000Z`);
rangeEndExclusiveDate.setUTCDate(rangeEndExclusiveDate.getUTCDate() + 1);
const rangeEndExclusive = rangeEndExclusiveDate.toISOString().slice(0, 10) + ' 00:00:00.000000';
let projectId: string | null = null;
if (projectSlug) {
const [prows] = await db.execute<RowDataPacket[]>(
`SELECT CAST(id AS CHAR) AS id FROM er_projects WHERE slug = ? LIMIT 1`,
[projectSlug],
);
const row = prows[0] as { id: string } | undefined;
if (!row) {
return reply.code(404).send({ error: 'Not found', message: 'Unknown project slug' });
}
projectId = row.id;
}
const [aggRows] = await db.execute<RowDataPacket[]>(
`SELECT DATE(o.occurred_at) AS d, o.severity, COUNT(*) AS c
FROM er_incident_occurrences o
WHERE o.occurred_at >= ? AND o.occurred_at < ?
AND (${projectId ? 'o.project_id = ?' : '1=1'})
GROUP BY DATE(o.occurred_at), o.severity`,
projectId ? [rangeStart, rangeEndExclusive, projectId] : [rangeStart, rangeEndExclusive],
);
const byDateSeverity = new Map<string, Map<Severity, number>>();
for (const row of aggRows) {
const d = String(row.d);
const sev = String(row.severity);
const c = Number(row.c);
if (!isSeverity(sev)) {
continue;
}
if (!byDateSeverity.has(d)) {
byDateSeverity.set(d, new Map());
}
byDateSeverity.get(d)!.set(sev, c);
}
const series: Record<Severity, number[]> = {
critical: [],
high: [],
medium: [],
low: [],
info: [],
};
for (const d of dates) {
const m = byDateSeverity.get(d) ?? new Map();
for (const sev of SEVERITIES) {
series[sev].push(m.get(sev) ?? 0);
}
}
return reply.send({ dates, series });
},
);
app.get(
'/v1/stats/summary',
{
preHandler: [...pre],
schema: {
querystring: {
type: 'object',
properties: {
project: { type: 'string', maxLength: 64 },
},
additionalProperties: false,
},
},
},
async (request: FastifyRequest, reply: FastifyReply) => {
const q = request.query as { project?: string };
const projectSlug = q.project?.trim() || null;
if (projectSlug) {
const [chk] = await db.execute<RowDataPacket[]>(
`SELECT 1 AS ok FROM er_projects WHERE slug = ? LIMIT 1`,
[projectSlug],
);
if (chk.length === 0) {
return reply.code(404).send({ error: 'Not found', message: 'Unknown project slug' });
}
}
const [byProjectRows] = await db.execute<RowDataPacket[]>(
`SELECT
p.slug AS slug,
SUM(CASE WHEN i.id IS NOT NULL AND i.current_state = 'open' THEN 1 ELSE 0 END) AS open_cnt,
SUM(CASE WHEN i.id IS NOT NULL AND i.current_state = 'investigating' THEN 1 ELSE 0 END) AS investigating_cnt,
SUM(CASE WHEN i.id IS NOT NULL AND i.current_state = 'resolved' THEN 1 ELSE 0 END) AS resolved_cnt,
SUM(CASE WHEN i.id IS NOT NULL AND i.current_state = 'ignored' THEN 1 ELSE 0 END) AS ignored_cnt
FROM er_projects p
LEFT JOIN er_incidents i ON i.project_id = p.id
WHERE (? IS NULL OR p.slug = ?)
GROUP BY p.id, p.slug
ORDER BY p.slug ASC`,
[projectSlug, projectSlug],
);
const byProject = byProjectRows.map((row) => ({
slug: String(row.slug),
open: Number(row.open_cnt) || 0,
investigating: Number(row.investigating_cnt) || 0,
resolved: Number(row.resolved_cnt) || 0,
ignored: Number(row.ignored_cnt) || 0,
}));
const [sevRows] = await db.execute<RowDataPacket[]>(
`SELECT i.severity, COUNT(*) AS c
FROM er_incidents i
INNER JOIN er_projects p ON p.id = i.project_id
WHERE (? IS NULL OR p.slug = ?)
GROUP BY i.severity`,
[projectSlug, projectSlug],
);
const bySeverity: Record<Severity, number> = {
critical: 0,
high: 0,
medium: 0,
low: 0,
info: 0,
};
for (const row of sevRows) {
const sev = String(row.severity);
if (isSeverity(sev)) {
bySeverity[sev] = Number(row.c) || 0;
}
}
const [resolvedRows] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(DISTINCT h.incident_id) AS c
FROM er_incident_state_history h
INNER JOIN er_projects p ON p.id = h.project_id
WHERE h.to_state = 'resolved'
AND h.created_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)
AND (? IS NULL OR p.slug = ?)`,
[projectSlug, projectSlug],
);
const resolvedLast24h = Number((resolvedRows[0] as { c: unknown })?.c) || 0;
const [totalRows] = await db.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c
FROM er_incident_occurrences o
INNER JOIN er_projects p ON p.id = o.project_id
WHERE o.occurred_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)
AND (? IS NULL OR p.slug = ?)`,
[projectSlug, projectSlug],
);
const totalLast24h = Number((totalRows[0] as { c: unknown })?.c) || 0;
return reply.send({
byProject,
bySeverity,
resolvedLast24h,
totalLast24h,
});
},
);
}