feat(cron): missad-tick-detektion — heartbeat per schema, 503 när ett jobb slutar komma
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.
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
interface Row {
|
||||
path: string
|
||||
declaredAt: string | null
|
||||
lastStartedAt: string | null
|
||||
lastCompletedAt: string | null
|
||||
lastStatus: string | null
|
||||
lastHttpStatus: number | null
|
||||
lastDurationMs: number | null
|
||||
}
|
||||
|
||||
const verifyCronSecret = vi.fn((): NextResponse | null => null)
|
||||
const loadCronHeartbeats = vi.fn(async (): Promise<Row[]> => [])
|
||||
const declareCronPaths = vi.fn(async (_paths: readonly string[]): Promise<void> => {})
|
||||
const cronHeartbeatStoreConfigured = vi.fn((): boolean => true)
|
||||
|
||||
vi.mock('@/lib/auth/cron', () => ({
|
||||
verifyCronSecret: () => verifyCronSecret(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/cron/heartbeat-store', () => ({
|
||||
loadCronHeartbeats: () => loadCronHeartbeats(),
|
||||
declareCronPaths: (paths: readonly string[]) => declareCronPaths(paths),
|
||||
cronHeartbeatStoreConfigured: () => cronHeartbeatStoreConfigured(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/logger', () => {
|
||||
const child = () => logger
|
||||
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child }
|
||||
return { createLogger: () => logger }
|
||||
})
|
||||
|
||||
const { GET } = await import('../route')
|
||||
const { CRON_SCHEDULES } = await import('@/lib/cron/schedules.generated')
|
||||
|
||||
function request(): Request {
|
||||
return new Request('http://app:3000/api/cron/health', {
|
||||
headers: { authorization: 'Bearer secret' },
|
||||
})
|
||||
}
|
||||
|
||||
function everythingRanSecondsAgo(seconds: number) {
|
||||
const at = new Date(Date.now() - seconds * 1000).toISOString()
|
||||
return CRON_SCHEDULES.map((entry) => ({
|
||||
path: entry.path,
|
||||
declaredAt: at,
|
||||
lastStartedAt: at,
|
||||
lastCompletedAt: at,
|
||||
lastStatus: 'ok',
|
||||
lastHttpStatus: 200,
|
||||
lastDurationMs: 12,
|
||||
}))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
verifyCronSecret.mockClear()
|
||||
verifyCronSecret.mockReturnValue(null)
|
||||
loadCronHeartbeats.mockReset()
|
||||
declareCronPaths.mockClear()
|
||||
cronHeartbeatStoreConfigured.mockReturnValue(true)
|
||||
})
|
||||
|
||||
describe('GET /api/cron/health', () => {
|
||||
it('rejects an unauthenticated call before touching the store', async () => {
|
||||
verifyCronSecret.mockReturnValue(
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
)
|
||||
|
||||
const response = await GET(request())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(loadCronHeartbeats).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers 200 when every schedule ran inside its window', async () => {
|
||||
loadCronHeartbeats.mockResolvedValue(everythingRanSecondsAgo(5))
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.status).toBe('ok')
|
||||
expect(body.report.ok).toBe(true)
|
||||
expect(body.report.total).toBe(CRON_SCHEDULES.length)
|
||||
})
|
||||
|
||||
it('answers 503 when a schedule stopped arriving', async () => {
|
||||
// Every path ran 5 s ago except one stale per-minute job: the endpoint is
|
||||
// a single boolean for the container healthcheck, so one silent stop must
|
||||
// be enough to fail it. Pick a per-minute entry explicitly — a daily job
|
||||
// 30 minutes old is not stale, and a test that used index 0 would pass for
|
||||
// the wrong reason.
|
||||
const rows = everythingRanSecondsAgo(5)
|
||||
const index = CRON_SCHEDULES.findIndex((entry) => entry.maxIntervalSeconds === 60)
|
||||
expect(index).toBeGreaterThanOrEqual(0)
|
||||
const staleAt = new Date(Date.now() - 30 * 60 * 1000).toISOString()
|
||||
rows[index] = { ...rows[index], lastStartedAt: staleAt, lastCompletedAt: staleAt }
|
||||
loadCronHeartbeats.mockResolvedValue(rows)
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect(body.status).toBe('stale')
|
||||
expect(body.report.stale).toBe(1)
|
||||
expect(body.report.checks[index].state).toBe('stale')
|
||||
})
|
||||
|
||||
it('declares paths that have never run instead of failing them immediately', async () => {
|
||||
loadCronHeartbeats.mockResolvedValue([])
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.status).toBe('ok')
|
||||
expect(body.report.pending).toBe(CRON_SCHEDULES.length)
|
||||
expect(declareCronPaths).toHaveBeenCalledTimes(1)
|
||||
expect(declareCronPaths.mock.calls[0][0]).toHaveLength(CRON_SCHEDULES.length)
|
||||
})
|
||||
|
||||
it('says unverifiable (503) rather than healthy when the store cannot be read', async () => {
|
||||
loadCronHeartbeats.mockRejectedValue(new Error('connection refused'))
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect(body.status).toBe('unverifiable')
|
||||
// The driver's message must not reach the body.
|
||||
expect(JSON.stringify(body)).not.toContain('connection refused')
|
||||
})
|
||||
|
||||
it('says unverifiable when the heartbeat store is not configured', async () => {
|
||||
cronHeartbeatStoreConfigured.mockReturnValue(false)
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect(body.status).toBe('unverifiable')
|
||||
expect(loadCronHeartbeats).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces a run that arrived but failed separately from a missed tick', async () => {
|
||||
const rows = everythingRanSecondsAgo(5)
|
||||
rows[1] = { ...rows[1], lastStatus: 'error', lastHttpStatus: 500 }
|
||||
loadCronHeartbeats.mockResolvedValue(rows)
|
||||
|
||||
const response = await GET(request())
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.failing).toEqual([
|
||||
{ path: rows[1].path, lastStatus: 'error', lastHttpStatus: 500 },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
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 },
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user