This commit is contained in:
nate 2026-04-08 16:06:55 +04:00
parent a7fef0a2b7
commit 33896daf77
1 changed files with 21 additions and 1 deletions

View File

@ -116,7 +116,7 @@ export async function loadMonitors(pageId: string, window: Window): Promise<Moni
const { bucket, count } = WINDOW_TO_BUCKET[window];
const truncUnit = bucket === "hourly" ? "hour" : bucket === "daily" ? "day" : "week";
const intervalLiteral = `${count} ${truncUnit}s`;
const rollupRows = await sql<any[]>`
let rollupRows = await sql<any[]>`
SELECT monitor_id, bucket_start, sum(total)::int AS total, sum(up_count)::int AS up_count, avg(avg_latency)::real AS avg_latency
FROM monitor_uptime_rollup
WHERE monitor_id = ANY(${sql.array(ids)}::text[])
@ -125,6 +125,26 @@ export async function loadMonitors(pageId: string, window: Window): Promise<Moni
GROUP BY monitor_id, bucket_start
ORDER BY monitor_id, bucket_start ASC
`;
// Fallback: if the rollup table has nothing for any of these monitors in
// this window (e.g. the api hasn't backfilled yet, or the rollup job is
// silently broken), aggregate directly from pings. Bounded by the window so
// it stays cheap. Once the rollup catches up this branch never fires.
if (rollupRows.length === 0) {
rollupRows = await sql<any[]>`
SELECT
monitor_id,
date_trunc(${truncUnit}, checked_at) AS bucket_start,
count(*)::int AS total,
count(*) FILTER (WHERE up)::int AS up_count,
avg(latency_ms)::real AS avg_latency
FROM pings
WHERE monitor_id = ANY(${sql.array(ids)}::text[])
AND checked_at > date_trunc(${truncUnit}, now()) - ${intervalLiteral}::interval
GROUP BY monitor_id, date_trunc(${truncUnit}, checked_at)
ORDER BY monitor_id, bucket_start ASC
`;
}
// Index actual rollup data by (monitor_id, isoBucketStart) so we can fill in
// the missing slots below.
const indexed: Record<string, Record<string, { total: number; up: number; avg_latency: number | null }>> = {};