/** * Missed-cron detection, the pure half. * * The store and the endpoint live in ./heartbeat-store.ts and * app/api/cron/health/route.ts; everything that decides ok/stale is here so it * can be tested without a database. * * The threshold is deliberately generous, because the cost of the two mistakes * is not symmetric. Too tight and every slow run flaps the container * unhealthy, which trains people to ignore the check. Too loose and a stalled * schedule keeps looking fine — the failure mode this exists to catch (see the * 2026-11-15 pids_limit incident in the cron_heartbeats migration). Two missed * intervals plus a two-minute floor means a per-minute job is flagged after * 4 minutes and a daily job after 48 h 2 min, while one skipped tick or one * slow run is not. */ import type { CronScheduleEntry } from './schedules.generated' /** A run is stale after this many missed intervals. */ export const CRON_STALE_MULTIPLIER = 2 /** Floor added on top of the interval, absorbing clock skew and one slow run. */ export const CRON_STALE_GRACE_SECONDS = 120 export type CronHeartbeatState = 'ok' | 'pending' | 'stale' /** A row as the store returns it (snake_case columns already mapped). */ export interface CronHeartbeatRow { path: string declaredAt: string | null lastStartedAt: string | null lastCompletedAt: string | null lastStatus: string | null lastHttpStatus: number | null lastDurationMs: number | null } export interface CronHeartbeatCheck { path: string schedule: string maxIntervalSeconds: number /** Age at which this path is reported stale. */ allowedAgeSeconds: number lastStartedAt: string | null ageSeconds: number | null state: CronHeartbeatState lastStatus: string | null lastHttpStatus: number | null lastDurationMs: number | null } export interface CronHeartbeatReport { /** False only when at least one path is stale. Pending paths do not fail. */ ok: boolean checkedAt: string total: number stale: number pending: number checks: CronHeartbeatCheck[] } export function allowedAgeSeconds(maxIntervalSeconds: number): number { return maxIntervalSeconds * CRON_STALE_MULTIPLIER + CRON_STALE_GRACE_SECONDS } function ageInSeconds(reference: string | null, now: number): number | null { if (!reference) return null const at = Date.parse(reference) if (!Number.isFinite(at)) return null return Math.max(0, Math.round((now - at) / 1000)) } /** * Evaluate every scheduled path against its heartbeat row. * * States: * ok — a run started within the allowed age. * pending — no run yet, but the path has not been declared longer than its * own cadence allows. A freshly added job, or a fresh install. * stale — a run used to arrive and stopped, OR the path was declared * longer ago than its cadence and has never run. Both are real * defects; only `stale` fails the endpoint. * * A path with neither a row nor a declaration is reported `pending` here; the * route declares it before evaluating, so this only happens on the first call. */ export function evaluateCronHeartbeats(params: { entries: readonly CronScheduleEntry[] rows: readonly CronHeartbeatRow[] now: number }): CronHeartbeatReport { const byPath = new Map(params.rows.map((row) => [row.path, row])) const checks: CronHeartbeatCheck[] = params.entries.map((entry) => { const row = byPath.get(entry.path) const allowed = allowedAgeSeconds(entry.maxIntervalSeconds) // Staleness is measured from the last START. A run that hangs never // completes, and supercronic skips every later tick while it hangs, so // last_completed_at would keep a dead schedule looking alive. const ranAt = row?.lastStartedAt ?? null const reference = ranAt ?? row?.declaredAt ?? null const age = ageInSeconds(reference, params.now) let state: CronHeartbeatState = 'ok' if (age === null) state = 'pending' else if (age > allowed) state = 'stale' else if (ranAt === null) state = 'pending' return { path: entry.path, schedule: entry.schedule, maxIntervalSeconds: entry.maxIntervalSeconds, allowedAgeSeconds: allowed, lastStartedAt: ranAt, ageSeconds: age, state, lastStatus: row?.lastStatus ?? null, lastHttpStatus: row?.lastHttpStatus ?? null, lastDurationMs: row?.lastDurationMs ?? null, } }) const stale = checks.filter((check) => check.state === 'stale').length const pending = checks.filter((check) => check.state === 'pending').length return { ok: stale === 0, checkedAt: new Date(params.now).toISOString(), total: checks.length, stale, pending, checks, } } /** * A run that finished non-2xx is not a missed tick (it ran), but it is worth * surfacing next to the heartbeat: a schedule that "works" while every run * fails is the same silent outage with an extra step. */ export function isFailingStatus(status: string | null, httpStatus: number | null): boolean { if (status && status !== 'ok') return true return httpStatus !== null && (httpStatus < 200 || httpStatus >= 300) }