feat(admin): operational stats — hourly trends, recurrence, dashboard
Extend GET /v1/stats/trend with granularity=hour (UTC buckets) and granularity=day response envelope. Enrich GET /v1/stats/summary per-project totals and critical counts. Add GET /v1/stats/recurrence for top incidents by occurrence volume in a sliding window. Add index on er_incident_occurrences(occurred_at) for range queries. Wire admin dashboard to summary, 24h/14d trends, and recurrence table. Document contract in docs/ADMIN_STATS_API.md. Paperclip-Agent: Pedro Alves (urlKey pedro-alves; id d706f4e6-5d05-4cec-b6e8-f8fb1f203aae) Paperclip-Issue: BIT-728 Paperclip-Run: 948904bb-20d7-4d29-9cd7-4c22544f7570 Made-with: Cursor
This commit is contained in:
1 parent
c4e0b03ed8
commit
de68f68103
6 files changed
+643
-23
No files matched your search
+186
-4
@@ -1,14 +1,24 @@
|
||||
import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
|
||||
/** Respect runtime env (e.g. ERROR_REPORTING_UI_DEMO) — avoid stale prerender behind CDN. */
|
||||
export const dynamic = "force-dynamic";
|
||||
import { DataAlert } from "@/components/DataAlert";
|
||||
import { KpiCard } from "@/components/KpiCard";
|
||||
import { computeKpis, fetchIncidentList } from "@/lib/incidents-data";
|
||||
import { fetchOperationalStats } from "@/lib/stats-data";
|
||||
|
||||
/** Respect runtime env (e.g. ERROR_REPORTING_UI_DEMO) — avoid stale prerender behind CDN. */
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function _sumSeriesAt(idx: number, series: Record<string, number[]>): number {
|
||||
let _t = 0;
|
||||
for (const _k of Object.keys(series)) {
|
||||
const _arr = series[_k];
|
||||
_t += _arr[idx] ?? 0;
|
||||
}
|
||||
return _t;
|
||||
}
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const _list = await fetchIncidentList({});
|
||||
const [_list, _stats] = await Promise.all([fetchIncidentList({}), fetchOperationalStats()]);
|
||||
|
||||
if (!_list.ok) {
|
||||
return (
|
||||
@@ -48,6 +58,178 @@ export default async function DashboardPage() {
|
||||
<KpiCard label="Ignorados" value={_kpis.ignored} variant="secondary" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{_stats.ok ? (
|
||||
<>
|
||||
<h2 className="h5 mt-4 mb-3">Métricas operacionais (API)</h2>
|
||||
<div className="row g-3 mb-4">
|
||||
<div className="col-md-4">
|
||||
<KpiCard
|
||||
label="Ocorrências (24h)"
|
||||
value={_stats.summary.totalLast24h}
|
||||
variant="dark"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<KpiCard
|
||||
label="Incidentes resolvidos (24h)"
|
||||
value={_stats.summary.resolvedLast24h}
|
||||
variant="success"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<KpiCard
|
||||
label="Críticos (todos os estados)"
|
||||
value={_stats.summary.bySeverity.critical ?? 0}
|
||||
variant="danger"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card mb-4">
|
||||
<div className="card-header fw-semibold">Por projeto (inventário de incidentes)</div>
|
||||
<div className="card-body p-0">
|
||||
<div className="table-responsive">
|
||||
<table className="table table-sm table-striped mb-0 align-middle">
|
||||
<thead className="table-light">
|
||||
<tr>
|
||||
<th>Projeto</th>
|
||||
<th className="text-end">Total</th>
|
||||
<th className="text-end">Abertos</th>
|
||||
<th className="text-end">Resolvidos</th>
|
||||
<th className="text-end">Críticos</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{_stats.summary.byProject.map((r) => (
|
||||
<tr key={r.slug}>
|
||||
<td>
|
||||
<code className="small">{r.slug}</code>
|
||||
</td>
|
||||
<td className="text-end font-monospace">{r.total}</td>
|
||||
<td className="text-end font-monospace">{r.open}</td>
|
||||
<td className="text-end font-monospace">{r.resolved}</td>
|
||||
<td className="text-end font-monospace">{r.critical}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row g-3 mb-4">
|
||||
<div className="col-lg-6">
|
||||
<div className="card h-100">
|
||||
<div className="card-header fw-semibold">
|
||||
Volume horário (UTC, 24h) — ocorrências
|
||||
</div>
|
||||
<div className="card-body p-0" style={{ maxHeight: 280, overflowY: "auto" }}>
|
||||
<table className="table table-sm mb-0 align-middle">
|
||||
<thead className="table-light sticky-top">
|
||||
<tr>
|
||||
<th>Hora (início UTC)</th>
|
||||
<th className="text-end">Total</th>
|
||||
<th className="text-end">Crítico</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{_stats.trendHour.hours.map((h, i) => (
|
||||
<tr key={h}>
|
||||
<td className="text-nowrap small">{h}</td>
|
||||
<td className="text-end font-monospace">{_sumSeriesAt(i, _stats.trendHour.series)}</td>
|
||||
<td className="text-end font-monospace">
|
||||
{_stats.trendHour.series.critical[i] ?? 0}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-lg-6">
|
||||
<div className="card h-100">
|
||||
<div className="card-header fw-semibold">Tendência diária (14 dias)</div>
|
||||
<div className="card-body p-0" style={{ maxHeight: 280, overflowY: "auto" }}>
|
||||
<table className="table table-sm mb-0 align-middle">
|
||||
<thead className="table-light sticky-top">
|
||||
<tr>
|
||||
<th>Dia</th>
|
||||
<th className="text-end">Total ocorr.</th>
|
||||
<th className="text-end">Crítico</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{_stats.trendDay.dates.map((d, i) => (
|
||||
<tr key={d}>
|
||||
<td className="small">{d}</td>
|
||||
<td className="text-end font-monospace">{_sumSeriesAt(i, _stats.trendDay.series)}</td>
|
||||
<td className="text-end font-monospace">
|
||||
{_stats.trendDay.series.critical[i] ?? 0}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card mb-4">
|
||||
<div className="card-header fw-semibold">
|
||||
Recorrência (top por volume de ocorrências — últimos {_stats.recurrence.windowDays} dias)
|
||||
</div>
|
||||
<div className="card-body p-0">
|
||||
<div className="table-responsive">
|
||||
<table className="table table-sm table-striped mb-0 align-middle">
|
||||
<thead className="table-light">
|
||||
<tr>
|
||||
<th className="text-end">Hits</th>
|
||||
<th>Projeto</th>
|
||||
<th>Severidade</th>
|
||||
<th>Título</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{_stats.recurrence.top.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="text-muted p-3">
|
||||
Sem ocorrências no período.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
_stats.recurrence.top.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td className="text-end font-monospace">{r.hitsInWindow}</td>
|
||||
<td>
|
||||
<code className="small">{r.projectSlug}</code>
|
||||
</td>
|
||||
<td className="small">{r.severity}</td>
|
||||
<td className="text-break small">{r.title}</td>
|
||||
<td className="text-end">
|
||||
<Link
|
||||
href={`/incidents/${encodeURIComponent(r.id)}`}
|
||||
className="btn btn-sm btn-outline-primary"
|
||||
>
|
||||
Detalhe
|
||||
</Link>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : _list.source === "api" ? (
|
||||
<DataAlert variant="warning" title="Estatísticas indisponíveis" body={_stats.message} />
|
||||
) : null}
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header d-flex align-items-center justify-content-between">
|
||||
<span className="fw-semibold">Atalhos</span>
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
function _envStr(key: string): string | undefined {
|
||||
const v = Reflect.get(process.env, key);
|
||||
return typeof v === "string" ? v : undefined;
|
||||
}
|
||||
|
||||
async function _sessionCookieHeader(): Promise<string | undefined> {
|
||||
try {
|
||||
const _jar = await cookies();
|
||||
const _access = _jar.get("__Host-access")?.value;
|
||||
if (!_access) {
|
||||
return undefined;
|
||||
}
|
||||
return `__Host-access=${_access}`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function _apiBase(): string | null {
|
||||
const _raw = _envStr("ERROR_REPORTING_ADMIN_API_BASE")?.trim();
|
||||
if (!_raw) {
|
||||
return null;
|
||||
}
|
||||
return _raw.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function _fetchJson<T>(_path: string): Promise<T> {
|
||||
const _base = _apiBase();
|
||||
if (!_base) {
|
||||
throw new Error("API base not configured");
|
||||
}
|
||||
const _url = `${_base}${_path.startsWith("/") ? _path : `/${_path}`}`;
|
||||
const _cookie = await _sessionCookieHeader();
|
||||
const _res = await fetch(_url, {
|
||||
next: { revalidate: 0 },
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(_cookie ? { Cookie: _cookie } : {}),
|
||||
},
|
||||
});
|
||||
if (!_res.ok) {
|
||||
throw new Error(`HTTP ${_res.status}`);
|
||||
}
|
||||
return (await _res.json()) as T;
|
||||
}
|
||||
|
||||
export type ProjectRollup = {
|
||||
slug: string;
|
||||
total: number;
|
||||
open: number;
|
||||
investigating: number;
|
||||
resolved: number;
|
||||
ignored: number;
|
||||
critical: number;
|
||||
};
|
||||
|
||||
export type StatsSummaryPayload = {
|
||||
byProject: ProjectRollup[];
|
||||
bySeverity: Record<string, number>;
|
||||
resolvedLast24h: number;
|
||||
totalLast24h: number;
|
||||
};
|
||||
|
||||
export type TrendDayPayload = {
|
||||
granularity: "day";
|
||||
dates: string[];
|
||||
series: Record<string, number[]>;
|
||||
};
|
||||
|
||||
export type TrendHourPayload = {
|
||||
granularity: "hour";
|
||||
hours: string[];
|
||||
series: Record<string, number[]>;
|
||||
};
|
||||
|
||||
export type RecurrenceRow = {
|
||||
id: string;
|
||||
projectSlug: string;
|
||||
fingerprint: string;
|
||||
title: string;
|
||||
severity: string;
|
||||
currentState: string;
|
||||
hitsInWindow: number;
|
||||
lifetimeOccurrences: number;
|
||||
};
|
||||
|
||||
export type RecurrencePayload = {
|
||||
windowDays: number;
|
||||
rangeStart: string;
|
||||
rangeEndExclusive: string;
|
||||
top: RecurrenceRow[];
|
||||
};
|
||||
|
||||
export type OperationalStatsResult =
|
||||
| {
|
||||
ok: true;
|
||||
summary: StatsSummaryPayload;
|
||||
trendDay: TrendDayPayload;
|
||||
trendHour: TrendHourPayload;
|
||||
recurrence: RecurrencePayload;
|
||||
}
|
||||
| { ok: false; message: string };
|
||||
|
||||
export async function fetchOperationalStats(): Promise<OperationalStatsResult> {
|
||||
if (!_apiBase()) {
|
||||
return { ok: false, message: "API não configurada." };
|
||||
}
|
||||
try {
|
||||
const [summary, trendDay, trendHour, recurrence] = await Promise.all([
|
||||
_fetchJson<StatsSummaryPayload>("/v1/stats/summary"),
|
||||
_fetchJson<TrendDayPayload>("/v1/stats/trend?granularity=day&days=14"),
|
||||
_fetchJson<TrendHourPayload>("/v1/stats/trend?granularity=hour&hours=24"),
|
||||
_fetchJson<RecurrencePayload>("/v1/stats/recurrence?days=7&limit=12"),
|
||||
]);
|
||||
return { ok: true, summary, trendDay, trendHour, recurrence };
|
||||
} catch (_e) {
|
||||
const _msg = _e instanceof Error ? _e.message : "fetch failed";
|
||||
return {
|
||||
ok: false,
|
||||
message: `Não foi possível carregar estatísticas (${_msg}).`,
|
||||
};
|
||||
}
|
||||
}
|
||||
+249
-19
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* 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
|
||||
* GET /v1/stats/trend — occurrences per day or hour × severity (granularity=day|hour)
|
||||
* GET /v1/stats/summary — incidents by project (totals, open, resolved, critical, …), severity totals, 24h activity
|
||||
* GET /v1/stats/recurrence — top incidents by occurrence volume in a time window
|
||||
*/
|
||||
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
@@ -28,6 +29,83 @@ function parseDays(raw: string | undefined): number {
|
||||
return n;
|
||||
}
|
||||
|
||||
function parseHours(raw: string | undefined): number {
|
||||
if (raw === undefined || raw === '') {
|
||||
return 24;
|
||||
}
|
||||
const n = parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return 24;
|
||||
}
|
||||
if (n > 168) {
|
||||
return 168;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function parseLimit(raw: string | undefined, fallback: number, max: number): number {
|
||||
if (raw === undefined || raw === '') {
|
||||
return fallback;
|
||||
}
|
||||
const n = parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return fallback;
|
||||
}
|
||||
if (n > max) {
|
||||
return max;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function parseRecurrenceDays(raw: string | undefined): number {
|
||||
if (raw === undefined || raw === '') {
|
||||
return 7;
|
||||
}
|
||||
const n = parseInt(raw, 10);
|
||||
if (!Number.isFinite(n) || n < 1) {
|
||||
return 7;
|
||||
}
|
||||
if (n > 90) {
|
||||
return 90;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** UTC hour labels `YYYY-MM-DD HH:00:00` aligned with `DATE_FORMAT(utc…)` when DB stores UTC. */
|
||||
function enumerateUtcHourBucketLabels(endInclusiveUtc: Date, count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const end = new Date(endInclusiveUtc);
|
||||
end.setUTCMinutes(0, 0, 0);
|
||||
end.setUTCMilliseconds(0);
|
||||
for (let i = count - 1; i >= 0; i--) {
|
||||
const d = new Date(end.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 h = String(d.getUTCHours()).padStart(2, '0');
|
||||
out.push(`${y}-${mo}-${day} ${h}:00:00`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** End of window as MySQL DATETIME string (UTC wall clock). */
|
||||
function utcHourRangeEndExclusiveAfterLastBucket(lastBucketLabel: string): string {
|
||||
const iso = `${lastBucketLabel.replace(' ', 'T')}Z`;
|
||||
const ms = Date.parse(iso);
|
||||
if (!Number.isFinite(ms)) {
|
||||
throw new Error('invalid bucket label');
|
||||
}
|
||||
const end = new Date(ms + 3600_000);
|
||||
const y = end.getUTCFullYear();
|
||||
const mo = String(end.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(end.getUTCDate()).padStart(2, '0');
|
||||
const h = String(end.getUTCHours()).padStart(2, '0');
|
||||
const mi = String(end.getUTCMinutes()).padStart(2, '0');
|
||||
const s = String(end.getUTCSeconds()).padStart(2, '0');
|
||||
const f = String(end.getUTCMilliseconds()).padStart(3, '0');
|
||||
return `${y}-${mo}-${day} ${h}:${mi}:${s}.${f}000`;
|
||||
}
|
||||
|
||||
/** UTC calendar date string YYYY-MM-DD for each day in [startDay, endDay] inclusive. */
|
||||
function enumerateUtcDatesInclusive(startDay: string, endDay: string): string[] {
|
||||
const out: string[] = [];
|
||||
@@ -61,7 +139,9 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
querystring: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
granularity: { type: 'string', enum: ['day', 'hour'] },
|
||||
days: { type: 'string' },
|
||||
hours: { type: 'string' },
|
||||
project: { type: 'string', maxLength: 64 },
|
||||
},
|
||||
additionalProperties: false,
|
||||
@@ -69,10 +149,88 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
},
|
||||
},
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const q = request.query as { days?: string; project?: string };
|
||||
const days = parseDays(q.days);
|
||||
const q = request.query as { granularity?: string; days?: string; hours?: string; project?: string };
|
||||
const granularity = q.granularity === 'hour' ? 'hour' : 'day';
|
||||
const projectSlug = q.project?.trim() || null;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (granularity === 'hour') {
|
||||
const hours = parseHours(q.hours);
|
||||
const now = new Date();
|
||||
const endHourUtc = new Date(now);
|
||||
endHourUtc.setUTCMinutes(0, 0, 0);
|
||||
endHourUtc.setUTCMilliseconds(0);
|
||||
const hourLabels = enumerateUtcHourBucketLabels(endHourUtc, hours);
|
||||
const rangeStart = `${hourLabels[0]}.000000`;
|
||||
let rangeEndExclusive: string;
|
||||
try {
|
||||
rangeEndExclusive = utcHourRangeEndExclusiveAfterLastBucket(hourLabels[hourLabels.length - 1]!);
|
||||
} catch {
|
||||
return reply.code(500).send({ error: 'Internal error', message: 'Invalid trend range' });
|
||||
}
|
||||
|
||||
const [aggRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT DATE_FORMAT(
|
||||
CONVERT_TZ(o.occurred_at, @@session.time_zone, '+00:00'),
|
||||
'%Y-%m-%d %H:00:00'
|
||||
) AS b,
|
||||
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 b, o.severity`,
|
||||
projectId ? [rangeStart, rangeEndExclusive, projectId] : [rangeStart, rangeEndExclusive],
|
||||
);
|
||||
|
||||
const byBucket = new Map<string, Map<Severity, number>>();
|
||||
for (const row of aggRows) {
|
||||
const b = String(row.b);
|
||||
const sev = String(row.severity);
|
||||
const c = Number(row.c);
|
||||
if (!isSeverity(sev)) {
|
||||
continue;
|
||||
}
|
||||
if (!byBucket.has(b)) {
|
||||
byBucket.set(b, new Map());
|
||||
}
|
||||
byBucket.get(b)!.set(sev, c);
|
||||
}
|
||||
|
||||
const series: Record<Severity, number[]> = {
|
||||
critical: [],
|
||||
high: [],
|
||||
medium: [],
|
||||
low: [],
|
||||
info: [],
|
||||
};
|
||||
for (const label of hourLabels) {
|
||||
const m = byBucket.get(label) ?? new Map();
|
||||
for (const sev of SEVERITIES) {
|
||||
series[sev].push(m.get(sev) ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
granularity: 'hour' as const,
|
||||
hours: hourLabels,
|
||||
series,
|
||||
});
|
||||
}
|
||||
|
||||
const days = parseDays(q.days);
|
||||
const endDay = utcTodayString();
|
||||
const startDate = new Date(`${endDay}T00:00:00.000Z`);
|
||||
startDate.setUTCDate(startDate.getUTCDate() - (days - 1));
|
||||
@@ -88,19 +246,6 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
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
|
||||
@@ -139,7 +284,11 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
}
|
||||
}
|
||||
|
||||
return reply.send({ dates, series });
|
||||
return reply.send({
|
||||
granularity: 'day' as const,
|
||||
dates,
|
||||
series,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -174,10 +323,12 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
const [byProjectRows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT
|
||||
p.slug AS slug,
|
||||
COUNT(i.id) AS total_incidents,
|
||||
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
|
||||
SUM(CASE WHEN i.id IS NOT NULL AND i.current_state = 'ignored' THEN 1 ELSE 0 END) AS ignored_cnt,
|
||||
SUM(CASE WHEN i.id IS NOT NULL AND 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
|
||||
WHERE (? IS NULL OR p.slug = ?)
|
||||
@@ -188,10 +339,12 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
|
||||
const byProject = byProjectRows.map((row) => ({
|
||||
slug: String(row.slug),
|
||||
total: Number(row.total_incidents) || 0,
|
||||
open: Number(row.open_cnt) || 0,
|
||||
investigating: Number(row.investigating_cnt) || 0,
|
||||
resolved: Number(row.resolved_cnt) || 0,
|
||||
ignored: Number(row.ignored_cnt) || 0,
|
||||
critical: Number(row.critical_cnt) || 0,
|
||||
}));
|
||||
|
||||
const [sevRows] = await db.execute<RowDataPacket[]>(
|
||||
@@ -246,4 +399,81 @@ export default async function adminStatsRoutes(app: FastifyInstance): Promise<vo
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
app.get(
|
||||
'/v1/stats/recurrence',
|
||||
{
|
||||
preHandler: [...pre],
|
||||
schema: {
|
||||
querystring: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
project: { type: 'string', maxLength: 64 },
|
||||
days: { type: 'string' },
|
||||
limit: { type: 'string' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const q = request.query as { project?: string; days?: string; limit?: string };
|
||||
const projectSlug = q.project?.trim() || null;
|
||||
const windowDays = parseRecurrenceDays(q.days);
|
||||
const lim = parseLimit(q.limit, 15, 100);
|
||||
|
||||
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 rangeEndExclusive = new Date();
|
||||
const rangeStart = new Date(rangeEndExclusive.getTime() - windowDays * 86400_000);
|
||||
const rangeStartStr = rangeStart.toISOString().slice(0, 19).replace('T', ' ') + '.000000';
|
||||
const rangeEndStr = rangeEndExclusive.toISOString().slice(0, 19).replace('T', ' ') + '.000000';
|
||||
|
||||
const [rows] = await db.execute<RowDataPacket[]>(
|
||||
`SELECT CAST(i.id AS CHAR) AS id,
|
||||
p.slug AS project_slug,
|
||||
i.fingerprint,
|
||||
i.title,
|
||||
i.severity,
|
||||
i.current_state AS current_state,
|
||||
COUNT(o.id) AS hits_in_window,
|
||||
i.occurrences_count AS lifetime_occurrences
|
||||
FROM er_incident_occurrences o
|
||||
INNER JOIN er_incidents i ON i.id = o.incident_id
|
||||
INNER JOIN er_projects p ON p.id = o.project_id
|
||||
WHERE o.occurred_at >= ? AND o.occurred_at < ?
|
||||
AND (? IS NULL OR p.slug = ?)
|
||||
GROUP BY i.id, p.slug, i.fingerprint, i.title, i.severity, i.current_state, i.occurrences_count
|
||||
ORDER BY hits_in_window DESC
|
||||
LIMIT ?`,
|
||||
[rangeStartStr, rangeEndStr, projectSlug, projectSlug, lim],
|
||||
);
|
||||
|
||||
const top = rows.map((row) => ({
|
||||
id: String(row.id),
|
||||
projectSlug: String(row.project_slug),
|
||||
fingerprint: String(row.fingerprint),
|
||||
title: String(row.title),
|
||||
severity: String(row.severity),
|
||||
currentState: String(row.current_state),
|
||||
hitsInWindow: Number(row.hits_in_window) || 0,
|
||||
lifetimeOccurrences: Number(row.lifetime_occurrences) || 0,
|
||||
}));
|
||||
|
||||
return reply.send({
|
||||
windowDays,
|
||||
rangeStart: rangeStartStr,
|
||||
rangeEndExclusive: rangeEndStr,
|
||||
top,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
BEGIN;
|
||||
|
||||
DROP INDEX er_incident_occurrences_occurred_at_idx ON er_incident_occurrences;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,7 @@
|
||||
BEGIN;
|
||||
|
||||
-- Time-range aggregations (recurrence, global trends without project filter)
|
||||
CREATE INDEX IF NOT EXISTS er_incident_occurrences_occurred_at_idx
|
||||
ON er_incident_occurrences (occurred_at DESC);
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,71 @@
|
||||
# Admin API — operational statistics (`/v1/stats/*`)
|
||||
|
||||
**Audience:** `errors.bitreport.pt` admin UI, internal dashboards, automation.
|
||||
**Auth:** Same as other admin routes — JWT cookie (`__Host-access`) and permission `errors:read`.
|
||||
**Base URL:** `ERROR_REPORTING_ADMIN_API_BASE` (Fastify service, typically port `3200` behind `/admin/` proxy).
|
||||
|
||||
## `GET /v1/stats/summary`
|
||||
|
||||
Aggregates over **all incidents** (current state), optional filter by project.
|
||||
|
||||
| Query | Description |
|
||||
|--------|-------------|
|
||||
| `project` | Optional. Project `slug`; omit for all projects. |
|
||||
|
||||
### Response
|
||||
|
||||
- `byProject[]`: per slug — `total` (incident count), `open`, `investigating`, `resolved`, `ignored`, `critical` (incidents with `severity = critical`, any state).
|
||||
- `bySeverity`: global counts keyed by severity.
|
||||
- `resolvedLast24h`: distinct incidents moved to `resolved` in the last 24 hours (state history).
|
||||
- `totalLast24h`: occurrence rows in the last 24 hours.
|
||||
|
||||
## `GET /v1/stats/trend`
|
||||
|
||||
Occurrence counts bucketed by time and severity.
|
||||
|
||||
| Query | Description |
|
||||
|--------|-------------|
|
||||
| `granularity` | `day` (default) or `hour`. |
|
||||
| `days` | With `granularity=day`: window length, default `30`, max `366`. |
|
||||
| `hours` | With `granularity=hour`: number of UTC hour buckets ending at the current hour, default `24`, max `168`. |
|
||||
| `project` | Optional project `slug`. |
|
||||
|
||||
### Response — daily (`granularity=day`)
|
||||
|
||||
- `granularity`: `"day"`
|
||||
- `dates`: UTC calendar dates `YYYY-MM-DD` (inclusive window).
|
||||
- `series`: for each severity, an array of counts aligned with `dates`.
|
||||
|
||||
### Response — hourly (`granularity=hour`)
|
||||
|
||||
- `granularity`: `"hour"`
|
||||
- `hours`: UTC hour bucket labels `YYYY-MM-DD HH:00:00` (start of bucket).
|
||||
- `series`: same shape as daily, aligned with `hours`.
|
||||
|
||||
Hourly buckets use `CONVERT_TZ(..., @@session.time_zone, '+00:00')` so labels match UTC wall-clock when the DB session timezone is configured consistently.
|
||||
|
||||
## `GET /v1/stats/recurrence`
|
||||
|
||||
Ranks incidents by **how many occurrence rows** they received in a sliding window (recurrence / noise hotspots).
|
||||
|
||||
| Query | Description |
|
||||
|--------|-------------|
|
||||
| `project` | Optional project `slug`. |
|
||||
| `days` | Window length in days, default `7`, max `90`. |
|
||||
| `limit` | Max rows, default `15`, max `100`. |
|
||||
|
||||
### Response
|
||||
|
||||
- `windowDays`, `rangeStart`, `rangeEndExclusive`: bounds used for the query (MySQL `DATETIME(6)` strings).
|
||||
- `top[]`: `id`, `projectSlug`, `fingerprint`, `title`, `severity`, `currentState`, `hitsInWindow`, `lifetimeOccurrences`.
|
||||
|
||||
## Indexes
|
||||
|
||||
Heavy queries use:
|
||||
|
||||
- `er_incident_occurrences (project_id, occurred_at DESC)` — filtered trends and recurrence by project.
|
||||
- `er_incident_occurrences (occurred_at DESC)` — global time-range scans (see migration `20260402103000_add_occurred_at_for_stats`).
|
||||
|
||||
## Related
|
||||
|
||||
- Public ingest / `recent-errors`: `docs/` in this repo and Paperclip `ERROR_REPORTING_HUB_CONTRACT.md`.
|
||||
Reference in new issue
Block a user