Den 2026-11-15 tappade accounted-cron 1 497 av 10 455 körningar på ett dygn (14,3 %) när pids_limit 30 fick fork/exec /bin/sh att misslyckas. supercronic hoppade tyst över tickarna. Containern var Up hela tiden, appen svarade 200 på allt, och enda spåret var cron-containerns egen logg. Orsaken är fixad i #43; det här gör att ett tappat jobb SYNS nästa gång. Tre luckor stängs: 1. Ingen körningshistorik — with-cron-context loggade men skrev inget beständigt, så en körning som aldrig startade lämnade inget spår. 2. Cron-tjänstens healthcheck var `ps ax | grep supercronic`, som bara blir röd när processen dör, inte när scheman slutar köra. 3. Ingen hade kodifierat vad "för sen" betyder per schema. Implementering: - lib/cron/cron-interval.ts: tolkare för 5-fälters cron (det enda vercel.json använder) som räknar ut VÄRSTA gapet i sekunder över ett 12-årsfönster (behövs för 29 februari), inte medelgapet. Okänd syntax kastar hellre än gissar. - scripts/generate-crontabs.ts skriver nu även lib/cron/schedules.generated.ts (path + schedule + maxIntervalSeconds) från samma vercel.json-array som crontaben, så en schemalagd path som kontrollen inte känner till inte kan uppstå. Drift-testet jämför filen byte för byte. - supabase/migrations/20261115190000_cron_heartbeats.sql: en rad per path (declared_at, last_started_at, last_completed_at, last_status, last_http_status, last_duration_ms). RLS på, noll policies: instansglobal schemaläggning är inte tenantdata. - lib/cron/heartbeat-evaluation.ts: ren utvärdering — ok / pending (aldrig körd men deklarerad inom sin egen kadens) / stale. Tröskel 2 x kadens + 120 s. Mätt från last_started_at, inte completion: en hängd körning avslutas aldrig och supercronic skjuter då upp varje senare tick, så ett completion-baserat mått hade sett levande ut. - lib/cron/heartbeat-store.ts: Supabase-IO. Skrivningar är best effort (kastar aldrig — en mätningsskrivning får inte fälla jobbet den mäter); läsningar kastar så endpointen kan säga "kan inte verifiera" istället för att ljuga grönt. No-op utan Supabase-env. - app/api/cron/health/route.ts: 200 när alla scheman ligger inom sina fönster, 503 vid stale eller oläsbart lager. Deklarerar okända paths först (nytt jobb får respit istället för omedelbart rött). Autentiseras med befintlig cron-hemlighet, report:false så en felkopplad probe inte spammar auth-larm. - lib/api/with-cron-context.ts: skriver heartbeat per körning (path ur request-URL:en) med status och duration. 401 räknas inte som körning. - docker-compose.yml: cron-healthcheck byter från supercronic-grep till att anropa /api/cron/health med `$${CRON_SECRET}`/`$${APP_URL}` (dubbelt $ krävs, annars interpolerar compose på värden), start_period 120 s. Migrationen är redan applicerad på accounted-sb-db (additiv, 0 rader) så endpointen fungerar direkt vid deploy. Ordning vid utrullning: deploya appen först, recreata cron-containern sedan — den gamla imagen saknar routen, och healthchecken failar då korrekt stängt (verifierat i containern: curl -f ger 404/rc=22 mot icke-deployad route). Verifiering: 99 nya tester (kadens 60/120/300/3600/7200/86400/604800 s, 29 februari, cron-regeln OR; utvärdering ok/pending/stale/hängd körning; endpoint 200/503/401/unverifiable; wiring inklusive 401 utan heartbeat och kastat heartbeat-fel som inte fäller körningen; drift av genererad fil). Hela sviten 1687 filer / 22 400 tester grön; check:types 533/533; check:lint 0 fel; check:guards passed. Revert: git revert <sha> (kod + migration + compose i en commit). Migrationen kan lämnas kvar om bara koden rullas tillbaka.
110 lines
4.0 KiB
TypeScript
110 lines
4.0 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { verifyCronSecret } from '@/lib/auth/cron'
|
|
import {
|
|
evaluateCronHeartbeats,
|
|
isFailingStatus,
|
|
type CronHeartbeatReport,
|
|
} from '@/lib/cron/heartbeat-evaluation'
|
|
import {
|
|
cronHeartbeatStoreConfigured,
|
|
declareCronPaths,
|
|
loadCronHeartbeats,
|
|
} from '@/lib/cron/heartbeat-store'
|
|
import { CRON_SCHEDULES } from '@/lib/cron/schedules.generated'
|
|
import { createLogger } from '@/lib/logger'
|
|
|
|
const log = createLogger('cron/health')
|
|
|
|
// Reads live rows every call; a cached 200 would defeat the point of a
|
|
// healthcheck that exists to notice a schedule going quiet.
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
interface CronHealthBody {
|
|
status: 'ok' | 'stale' | 'unverifiable'
|
|
reason?: string
|
|
/** Present when the store responded. */
|
|
report?: CronHeartbeatReport
|
|
/** Runs that arrived but ended non-2xx. Informational; a failed run still ran. */
|
|
failing?: Array<{ path: string; lastStatus: string | null; lastHttpStatus: number | null }>
|
|
}
|
|
|
|
/**
|
|
* GET /api/cron/health
|
|
*
|
|
* Answers the question the 2026-11-15 incident proved nobody was asking: did
|
|
* every scheduled job actually start when it should?
|
|
*
|
|
* 200 = every scheduled path has run within its own worst-case window.
|
|
* 503 = at least one path is stale, or the heartbeat store could not be read
|
|
* (an unreadable store is not evidence of a healthy cron).
|
|
*
|
|
* Called by the cron container's own healthcheck (docker-compose.yml), which is
|
|
* what turns this answer into `unhealthy` and into the existing alerting chain.
|
|
* Auth is the normal cron secret: the body names instance-wide schedules, so it
|
|
* is not public, but the same credential the scheduler already holds is the
|
|
* right one — no new secret to distribute.
|
|
*/
|
|
export async function GET(request: Request): Promise<NextResponse<CronHealthBody>> {
|
|
// report: false — this endpoint is itself polled by a healthcheck, so a
|
|
// misconfigured probe must not emit an auth-failure event every minute.
|
|
const authError = verifyCronSecret(request, { report: false })
|
|
if (authError) return authError as NextResponse<CronHealthBody>
|
|
|
|
if (!cronHeartbeatStoreConfigured()) {
|
|
return NextResponse.json<CronHealthBody>(
|
|
{
|
|
status: 'unverifiable',
|
|
reason:
|
|
'heartbeat store not configured (NEXT_PUBLIC_SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY missing)',
|
|
},
|
|
{ status: 503 },
|
|
)
|
|
}
|
|
|
|
try {
|
|
// Declare first, read second: a path that has never run needs its
|
|
// declared_at anchor before the evaluator can tell a fresh job from a
|
|
// stopped one. ignoreDuplicates keeps existing rows untouched.
|
|
const known = new Set((await loadCronHeartbeats()).map((row) => row.path))
|
|
const undeclared = CRON_SCHEDULES.map((entry) => entry.path).filter((path) => !known.has(path))
|
|
if (undeclared.length > 0) await declareCronPaths(undeclared)
|
|
|
|
const rows = await loadCronHeartbeats()
|
|
const report = evaluateCronHeartbeats({ entries: CRON_SCHEDULES, rows, now: Date.now() })
|
|
|
|
const failing = report.checks
|
|
.filter((check) => isFailingStatus(check.lastStatus, check.lastHttpStatus))
|
|
.map((check) => ({
|
|
path: check.path,
|
|
lastStatus: check.lastStatus,
|
|
lastHttpStatus: check.lastHttpStatus,
|
|
}))
|
|
|
|
if (!report.ok) {
|
|
const stale = report.checks.filter((check) => check.state === 'stale')
|
|
log.warn('cron schedule stale', {
|
|
stale: stale.map((check) => ({
|
|
path: check.path,
|
|
ageSeconds: check.ageSeconds,
|
|
allowedAgeSeconds: check.allowedAgeSeconds,
|
|
})),
|
|
})
|
|
}
|
|
|
|
return NextResponse.json<CronHealthBody>(
|
|
{ status: report.ok ? 'ok' : 'stale', report, failing },
|
|
{ status: report.ok ? 200 : 503 },
|
|
)
|
|
} catch (err) {
|
|
// Never echo the driver's message: it can name tables and query fragments.
|
|
log.error('cron health check failed', err as Error)
|
|
return NextResponse.json<CronHealthBody>(
|
|
{
|
|
status: 'unverifiable',
|
|
reason: 'heartbeat store read failed',
|
|
},
|
|
{ status: 503 },
|
|
)
|
|
}
|
|
}
|