Files
accounted/lib/cron/heartbeat-store.ts
T
Claude Code c3a2ace846
masterplan-lock / check (pull_request) Successful in 8s
security / scan (pull_request) Failing after 2m43s
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.
2026-11-15 19:56:45 +01:00

140 lines
4.7 KiB
TypeScript

import 'server-only'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger, type Logger } from '@/lib/logger'
import type { CronHeartbeatRow } from './heartbeat-evaluation'
/**
* Cron heartbeat storage.
*
* Two callers:
* - lib/api/with-cron-context.ts, once per run (best effort: a monitoring
* write must never fail the job it monitors).
* - app/api/cron/health/route.ts, which declares unknown paths and reads the
* table to decide ok/stale.
*
* Everything goes through the service role: cron_heartbeats has RLS enabled and
* no policies, because instance-wide scheduling state is not tenant data.
*
* No-ops when Supabase is not configured (unit tests, `next build`, a hosted
* deployment reading its schedule from Vercel). The heartbeat check is a
* self-hosted guarantee; a missing store must not turn into a 500 in the cron
* path.
*/
const TABLE = 'cron_heartbeats'
const log: Logger = createLogger('cron/heartbeat-store')
function storeConfigured(): boolean {
return Boolean(process.env.NEXT_PUBLIC_SUPABASE_URL && process.env.SUPABASE_SERVICE_ROLE_KEY)
}
export interface CronHeartbeatInput {
path: string
/** ISO timestamp of when the run started (the staleness input). */
startedAt: string
/** ISO timestamp of when the run finished. */
completedAt: string
/** 'ok' | 'error'. Kept as a string so a future state does not need a migration. */
status: string
httpStatus: number | null
durationMs: number
}
/**
* Upsert the run that just finished. Best effort by contract: logs and returns
* on any failure, never throws. A heartbeat write that breaks a cron run would
* be a worse outage than the one it exists to detect.
*/
export async function recordCronHeartbeat(input: CronHeartbeatInput): Promise<void> {
if (!storeConfigured()) return
try {
const { error } = await createServiceClientNoCookies()
.from(TABLE)
.upsert(
{
path: input.path,
last_started_at: input.startedAt,
last_completed_at: input.completedAt,
last_status: input.status,
last_http_status: input.httpStatus,
last_duration_ms: input.durationMs,
updated_at: input.completedAt,
},
{ onConflict: 'path' },
)
if (error) {
log.warn('heartbeat write failed', { path: input.path, reason: error.message })
}
} catch (err) {
log.warn('heartbeat write threw', {
path: input.path,
reason: err instanceof Error ? err.message : String(err),
})
}
}
/**
* Register paths the generated schedule knows about but the table has not seen.
*
* This is what gives a new schedule a grace period: the row it creates carries
* declared_at = now, so the evaluator can tell "added yesterday, has not had its
* first tick" from "ran until last week and stopped". ignoreDuplicates keeps an
* existing row (and its run history) untouched.
*/
export async function declareCronPaths(paths: readonly string[]): Promise<void> {
if (!storeConfigured() || paths.length === 0) return
try {
const { error } = await createServiceClientNoCookies()
.from(TABLE)
.upsert(
paths.map((path) => ({ path })),
{ onConflict: 'path', ignoreDuplicates: true },
)
if (error) {
log.warn('heartbeat declaration failed', { paths: paths.length, reason: error.message })
}
} catch (err) {
log.warn('heartbeat declaration threw', {
paths: paths.length,
reason: err instanceof Error ? err.message : String(err),
})
}
}
/**
* All heartbeat rows. Throws on failure: the health route must be able to say
* "cannot verify" out loud (503) instead of reporting a healthy cron it could
* not read.
*/
export async function loadCronHeartbeats(): Promise<CronHeartbeatRow[]> {
const { data, error } = await createServiceClientNoCookies()
.from(TABLE)
.select(
'path, declared_at, last_started_at, last_completed_at, last_status, last_http_status, last_duration_ms',
)
if (error) throw new Error(`cron_heartbeats read failed: ${error.message}`)
if (!data) return []
return data.map((row) => ({
path: row.path as string,
declaredAt: (row.declared_at as string | null) ?? null,
lastStartedAt: (row.last_started_at as string | null) ?? null,
lastCompletedAt: (row.last_completed_at as string | null) ?? null,
lastStatus: (row.last_status as string | null) ?? null,
lastHttpStatus: (row.last_http_status as number | null) ?? null,
lastDurationMs: (row.last_duration_ms as number | null) ?? null,
}))
}
/** True when the heartbeat store is wired; the route and tests both ask. */
export function cronHeartbeatStoreConfigured(): boolean {
return storeConfigured()
}