Fetch stats summary first and tolerate trend/recurrence failures with Promise.allSettled so KPI totals no longer fall back to the 500-row incidents list cap.
171 lines
4.3 KiB
TypeScript
171 lines
4.3 KiB
TypeScript
import { cookies } from "next/headers";
|
|
import type { IncidentState } from "./types";
|
|
|
|
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 };
|
|
|
|
/** Global incident counts from SQL aggregates — not limited by the incidents list page size. */
|
|
export function aggregateIncidentKpisFromSummary(
|
|
summary: StatsSummaryPayload,
|
|
): Record<IncidentState | "total", number> {
|
|
const _acc: Record<IncidentState | "total", number> = {
|
|
total: 0,
|
|
open: 0,
|
|
investigating: 0,
|
|
resolved: 0,
|
|
ignored: 0,
|
|
};
|
|
for (const _r of summary.byProject) {
|
|
_acc.total += _r.total;
|
|
_acc.open += _r.open;
|
|
_acc.investigating += _r.investigating;
|
|
_acc.resolved += _r.resolved;
|
|
_acc.ignored += _r.ignored;
|
|
}
|
|
return _acc;
|
|
}
|
|
|
|
export async function fetchOperationalStats(): Promise<OperationalStatsResult> {
|
|
if (!_apiBase()) {
|
|
return { ok: false, message: "API nao configurada." };
|
|
}
|
|
|
|
try {
|
|
const summary = await _fetchJson<StatsSummaryPayload>("/v1/stats/summary");
|
|
|
|
const [trendDayRes, trendHourRes, recurrenceRes] = await Promise.allSettled([
|
|
_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"),
|
|
]);
|
|
|
|
const trendDay: TrendDayPayload =
|
|
trendDayRes.status === "fulfilled"
|
|
? trendDayRes.value
|
|
: { granularity: "day", dates: [], series: {} };
|
|
|
|
const trendHour: TrendHourPayload =
|
|
trendHourRes.status === "fulfilled"
|
|
? trendHourRes.value
|
|
: { granularity: "hour", hours: [], series: {} };
|
|
|
|
const recurrence: RecurrencePayload =
|
|
recurrenceRes.status === "fulfilled"
|
|
? recurrenceRes.value
|
|
: {
|
|
windowDays: 7,
|
|
rangeStart: "",
|
|
rangeEndExclusive: "",
|
|
top: [],
|
|
};
|
|
|
|
return { ok: true, summary, trendDay, trendHour, recurrence };
|
|
} catch (_e) {
|
|
const _msg = _e instanceof Error ? _e.message : "fetch failed";
|
|
return {
|
|
ok: false,
|
|
message: `Nao foi possivel carregar estatisticas (${_msg}).`,
|
|
};
|
|
}
|
|
}
|