Files
accounted/lib/api/with-cron-context.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

172 lines
5.7 KiB
TypeScript

/**
* Sibling of withRouteContext for cron endpoints.
*
* - Verifies CRON_SECRET via verifyCronSecret(); returns the standard envelope
* on failure.
* - Generates a parent requestId so every per-item log line for a single run
* shares a correlation id you can grep for in Vercel logs.
* - Provides a `forEach` helper that runs the iteratee in an isolated try/catch
* per item and logs the outcome at info/error level. A single failing item
* never aborts the run.
*
* Usage:
* export const GET = withCronContext('cron.invoice-reminders', async (ctx) => {
* const reminders = await loadDueReminders()
* const summary = await ctx.forEach('reminder', reminders, async (item, itemCtx) => {
* await sendReminder(item)
* })
* return NextResponse.json({ data: summary })
* })
*/
import { NextResponse } from 'next/server'
import { verifyCronSecret } from '@/lib/auth/cron'
import { recordCronHeartbeat } from '@/lib/cron/heartbeat-store'
import { createLogger, type Logger } from '@/lib/logger'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
export interface CronItemContext {
/** Per-item requestId, child of the run's parent requestId. */
requestId: string
log: Logger
parentRequestId: string
}
interface CronForEachResult {
total: number
succeeded: number
failed: number
failures: Array<{ index: number; error: string }>
}
export interface CronContext {
requestId: string
log: Logger
/**
* Iterate items with isolated try/catch + structured per-item logs. The
* returned summary is suitable to ship in the response body so an operator
* can see how many succeeded/failed at a glance.
*/
forEach<T>(
label: string,
items: T[],
iteratee: (item: T, itemCtx: CronItemContext) => Promise<void>,
): Promise<CronForEachResult>
}
type CronHandler = (request: Request, ctx: CronContext) => Promise<NextResponse | Response>
function generateRequestId(prefix: 'cron' | 'cron_item' = 'cron'): string {
return `${prefix}_${crypto.randomUUID()}`
}
/**
* The schedule identity used for heartbeat detection. The request path, not the
* `operation` label: lib/cron/schedules.generated.ts is keyed by path because
* that is the one identifier the generator and the runtime both know without a
* lookup table that can drift.
*/
function cronHeartbeatPath(request: Request): string | null {
try {
return new URL(request.url).pathname
} catch {
return null
}
}
export function withCronContext(
operation: string,
handler: CronHandler,
): (request: Request) => Promise<Response> {
return async function wrapped(request: Request): Promise<Response> {
const requestId = generateRequestId('cron')
const start = Date.now()
const log = createLogger(`cron/${operation}`, { requestId, operation })
const authError = verifyCronSecret(request)
if (authError) {
log.warn('cron auth failed')
return errorResponseFromCode('UNAUTHORIZED', log, { requestId })
}
log.info('cron run started')
const forEach: CronContext['forEach'] = async (label, items, iteratee) => {
const result: CronForEachResult = {
total: items.length,
succeeded: 0,
failed: 0,
failures: [],
}
for (let i = 0; i < items.length; i++) {
const item = items[i]
const itemRequestId = generateRequestId('cron_item')
const itemLog = log.child({ itemRequestId, itemIndex: i, itemLabel: label })
const itemCtx: CronItemContext = {
requestId: itemRequestId,
log: itemLog,
parentRequestId: requestId,
}
try {
await iteratee(item, itemCtx)
result.succeeded++
itemLog.info('cron item ok')
} catch (err) {
result.failed++
const errorMessage = err instanceof Error ? err.message : String(err)
result.failures.push({ index: i, error: errorMessage })
itemLog.error('cron item failed', err as Error)
}
}
return result
}
const ctx: CronContext = { requestId, log, forEach }
// Heartbeat: app/api/cron/health reads this row to decide whether this
// schedule still runs on time. start is captured before the handler so a
// run that hangs shows up as an ageing last_started_at, which is exactly
// the silent-stop shape seen in the 2026-11-15 pids_limit incident.
const heartbeatPath = cronHeartbeatPath(request)
const startedAt = new Date(start).toISOString()
const recordRun = async (status: string, httpStatus: number): Promise<void> => {
if (!heartbeatPath) return
try {
await recordCronHeartbeat({
path: heartbeatPath,
startedAt,
completedAt: new Date().toISOString(),
status,
httpStatus,
durationMs: Date.now() - start,
})
} catch {
// A monitoring write must never break the job it monitors. The store
// swallows its own failures; this is the second, cheap guard so a
// future change there cannot turn a heartbeat problem into a failing
// cron run.
}
}
try {
const response = await handler(request, ctx)
if (response instanceof Response && !response.headers.get('X-Request-Id')) {
response.headers.set('X-Request-Id', requestId)
}
log.info('cron run completed', {
durationMs: Date.now() - start,
status: response.status,
})
await recordRun('ok', response.status)
return response
} catch (err) {
log.error('cron run failed', err as Error, { durationMs: Date.now() - start })
await recordRun('error', 500)
return errorResponse(err, log, { requestId })
}
}
}