merge: BIT-734 operational observability (stats, Prometheus, SLO, Grafana)
Paperclip-Issue: BIT-734
This commit is contained in:
commit
acac2ba034
11 files changed
+1098
-2
No files matched your search
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* CRM-parity operational stats endpoint.
|
||||
* GET /api/error-monitoring/stats
|
||||
*
|
||||
* Returns 24h ingestion volume, severity distribution, per-project metrics,
|
||||
* and resolution rates. Also refreshes Prometheus gauges on each call.
|
||||
*
|
||||
* Auth: same read-key scheme as recent-errors (api_key or view_errors query param).
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { RowDataPacket } from 'mysql2';
|
||||
import { authorizeReadQuery } from '../../lib/errorMonitoringAuth.js';
|
||||
import { metricsGauges } from '../../plugins/prometheus.js';
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
interface ProjectRow {
|
||||
slug: string;
|
||||
total: number;
|
||||
open: number;
|
||||
investigating: number;
|
||||
resolved: number;
|
||||
ignored: number;
|
||||
critical: number;
|
||||
}
|
||||
|
||||
interface HourlyRow {
|
||||
hour_bucket: string;
|
||||
severity: string;
|
||||
cnt: number;
|
||||
}
|
||||
|
||||
export default async function errorMonitoringStatsRoutes(app: FastifyInstance): Promise<void> {
|
||||
const db = app.db;
|
||||
|
||||
app.get(
|
||||
'/api/error-monitoring/stats',
|
||||
{
|
||||
schema: {
|
||||
querystring: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
api_key: { type: 'string' },
|
||||
view_errors: { type: 'string' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
if (!authorizeReadQuery(request, reply)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── 1. Severity distribution (all incidents) ──────────────────────
|
||||
const [sevRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT i.severity, COUNT(*) AS c
|
||||
FROM er_incidents i
|
||||
GROUP BY i.severity`,
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Incidents by state ─────────────────────────────────────────
|
||||
const [stateRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT i.current_state AS state, COUNT(*) AS c
|
||||
FROM er_incidents i
|
||||
GROUP BY i.current_state`,
|
||||
);
|
||||
const byState: Record<string, number> = {};
|
||||
for (const row of stateRows) {
|
||||
byState[String(row.state)] = Number(row.c) || 0;
|
||||
}
|
||||
|
||||
// ── 3. 24h ingestion volume ───────────────────────────────────────
|
||||
const [vol24h] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(*) AS c
|
||||
FROM er_incident_occurrences o
|
||||
WHERE o.occurred_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)`,
|
||||
);
|
||||
const totalLast24h = Number((vol24h[0] as { c: unknown })?.c) || 0;
|
||||
|
||||
// ── 4. Resolved in last 24h ───────────────────────────────────────
|
||||
const [res24h] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT COUNT(DISTINCT h.incident_id) AS c
|
||||
FROM er_incident_state_history h
|
||||
WHERE h.to_state = 'resolved'
|
||||
AND h.created_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)`,
|
||||
);
|
||||
const resolvedLast24h = Number((res24h[0] as { c: unknown })?.c) || 0;
|
||||
|
||||
// ── 5. Hourly trend (last 24h by severity) ────────────────────────
|
||||
const [hourlyRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT DATE_FORMAT(
|
||||
CONVERT_TZ(o.occurred_at, @@session.time_zone, '+00:00'),
|
||||
'%Y-%m-%d %H:00:00'
|
||||
) AS hour_bucket,
|
||||
o.severity,
|
||||
COUNT(*) AS cnt
|
||||
FROM er_incident_occurrences o
|
||||
WHERE o.occurred_at >= DATE_SUB(NOW(6), INTERVAL 1 DAY)
|
||||
GROUP BY hour_bucket, o.severity
|
||||
ORDER BY hour_bucket ASC`,
|
||||
);
|
||||
|
||||
// Build hourly trend as array of {hour, critical, high, medium, low, info}
|
||||
const hourMap = new Map<string, Record<Severity, number>>();
|
||||
for (const raw of hourlyRows as HourlyRow[]) {
|
||||
const h = String(raw.hour_bucket);
|
||||
const sev = String(raw.severity);
|
||||
if (!isSeverity(sev)) continue;
|
||||
if (!hourMap.has(h)) {
|
||||
hourMap.set(h, { critical: 0, high: 0, medium: 0, low: 0, info: 0 });
|
||||
}
|
||||
hourMap.get(h)![sev] = Number(raw.cnt) || 0;
|
||||
}
|
||||
|
||||
// Enumerate all 24 hours to zero-fill gaps
|
||||
const now = new Date();
|
||||
const hourlyTrend: Array<{ hour: string } & Record<Severity, number>> = [];
|
||||
for (let i = 23; i >= 0; i--) {
|
||||
const d = new Date(now.getTime() - i * 3600_000);
|
||||
const y = d.getUTCFullYear();
|
||||
const mo = String(d.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getUTCDate()).padStart(2, '0');
|
||||
const hr = String(d.getUTCHours()).padStart(2, '0');
|
||||
const label = `${y}-${mo}-${day} ${hr}:00:00`;
|
||||
const vals = hourMap.get(label) ?? { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
|
||||
hourlyTrend.push({ hour: label, ...vals });
|
||||
}
|
||||
|
||||
// ── 6. Per-project metrics ────────────────────────────────────────
|
||||
const [projRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT
|
||||
p.slug,
|
||||
COUNT(i.id) AS total,
|
||||
SUM(CASE WHEN i.current_state = 'open' THEN 1 ELSE 0 END) AS open_cnt,
|
||||
SUM(CASE WHEN i.current_state = 'investigating' THEN 1 ELSE 0 END) AS investigating_cnt,
|
||||
SUM(CASE WHEN i.current_state = 'resolved' THEN 1 ELSE 0 END) AS resolved_cnt,
|
||||
SUM(CASE WHEN i.current_state = 'ignored' THEN 1 ELSE 0 END) AS ignored_cnt,
|
||||
SUM(CASE WHEN i.severity = 'critical' THEN 1 ELSE 0 END) AS critical_cnt
|
||||
FROM er_projects p
|
||||
LEFT JOIN er_incidents i ON i.project_id = p.id
|
||||
GROUP BY p.id, p.slug
|
||||
ORDER BY p.slug ASC`,
|
||||
);
|
||||
|
||||
const projects: Array<ProjectRow & { resolutionRate: number }> = (
|
||||
projRows as Record<string, unknown>[]
|
||||
).map((row) => {
|
||||
const total = Number(row.total) || 0;
|
||||
const resolved = Number(row.resolved_cnt) || 0;
|
||||
return {
|
||||
slug: String(row.slug),
|
||||
total,
|
||||
open: Number(row.open_cnt) || 0,
|
||||
investigating: Number(row.investigating_cnt) || 0,
|
||||
resolved,
|
||||
ignored: Number(row.ignored_cnt) || 0,
|
||||
critical: Number(row.critical_cnt) || 0,
|
||||
resolutionRate: total > 0 ? Math.round((resolved / total) * 10000) / 10000 : 0,
|
||||
};
|
||||
});
|
||||
|
||||
// ── 7. Refresh Prometheus gauges ──────────────────────────────────
|
||||
try {
|
||||
metricsGauges.occurrences24hGauge.set(totalLast24h);
|
||||
metricsGauges.resolved24hGauge.set(resolvedLast24h);
|
||||
|
||||
for (const sev of SEVERITIES) {
|
||||
metricsGauges.incidentsBySeverityGauge.labels(sev).set(bySeverity[sev]);
|
||||
}
|
||||
|
||||
for (const [state, count] of Object.entries(byState)) {
|
||||
metricsGauges.incidentsTotalGauge.labels(state).set(count);
|
||||
}
|
||||
|
||||
metricsGauges.projectIncidentsGauge.reset();
|
||||
metricsGauges.projectResolutionRateGauge.reset();
|
||||
for (const proj of projects) {
|
||||
for (const state of ['open', 'investigating', 'resolved', 'ignored'] as const) {
|
||||
metricsGauges.projectIncidentsGauge.labels(proj.slug, state).set(proj[state]);
|
||||
}
|
||||
metricsGauges.projectResolutionRateGauge.labels(proj.slug).set(proj.resolutionRate);
|
||||
}
|
||||
} catch {
|
||||
// Non-blocking: metric refresh failure must not break the endpoint.
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
ingestion: {
|
||||
last24h: totalLast24h,
|
||||
resolvedLast24h,
|
||||
hourlyTrend,
|
||||
},
|
||||
bySeverity,
|
||||
byState,
|
||||
projects,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user