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,111 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
interface HeartbeatInput {
|
||||
path: string
|
||||
startedAt: string
|
||||
completedAt: string
|
||||
status: string
|
||||
httpStatus: number | null
|
||||
durationMs: number
|
||||
}
|
||||
|
||||
const recordCronHeartbeat = vi.fn(async (_input: HeartbeatInput): Promise<void> => {})
|
||||
const verifyCronSecret = vi.fn((): NextResponse | null => null)
|
||||
|
||||
vi.mock('@/lib/cron/heartbeat-store', () => ({
|
||||
recordCronHeartbeat: (input: HeartbeatInput) => recordCronHeartbeat(input),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/cron', () => ({
|
||||
verifyCronSecret: () => verifyCronSecret(),
|
||||
}))
|
||||
|
||||
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 }
|
||||
})
|
||||
|
||||
vi.mock('@/lib/errors/get-structured-error', () => ({
|
||||
errorResponse: () => NextResponse.json({ error: 'boom' }, { status: 500 }),
|
||||
errorResponseFromCode: () => NextResponse.json({ error: 'unauthorized' }, { status: 401 }),
|
||||
}))
|
||||
|
||||
const { withCronContext } = await import('../with-cron-context')
|
||||
|
||||
const PATH = '/api/webhooks/dispatch/cron'
|
||||
|
||||
function request(): Request {
|
||||
return new Request(`http://app:3000${PATH}`, {
|
||||
headers: { authorization: 'Bearer secret' },
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
recordCronHeartbeat.mockClear()
|
||||
verifyCronSecret.mockClear()
|
||||
verifyCronSecret.mockReturnValue(null)
|
||||
})
|
||||
|
||||
/**
|
||||
* The heartbeat is the only evidence that a schedule still runs, so the wiring
|
||||
* — which path, which status, and that an auth rejection is NOT recorded as a
|
||||
* run — is worth asserting directly rather than inferring from the endpoint.
|
||||
*/
|
||||
describe('withCronContext heartbeat', () => {
|
||||
it('records the run under the request path on success', async () => {
|
||||
const handler = withCronContext('cron.webhook_dispatch', async () =>
|
||||
NextResponse.json({ ok: true }),
|
||||
)
|
||||
|
||||
const response = await handler(request())
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(recordCronHeartbeat).toHaveBeenCalledTimes(1)
|
||||
const input = recordCronHeartbeat.mock.calls[0][0]
|
||||
expect(input.path).toBe(PATH)
|
||||
expect(input.status).toBe('ok')
|
||||
expect(input.httpStatus).toBe(200)
|
||||
expect(Number.isFinite(Date.parse(input.startedAt))).toBe(true)
|
||||
expect(Number.isFinite(Date.parse(input.completedAt))).toBe(true)
|
||||
expect(input.durationMs).toBeGreaterThanOrEqual(0)
|
||||
})
|
||||
|
||||
it('records a failed run as error so the health body can show it', async () => {
|
||||
const handler = withCronContext('cron.webhook_dispatch', async () => {
|
||||
throw new Error('kaboom')
|
||||
})
|
||||
|
||||
const response = await handler(request())
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(recordCronHeartbeat).toHaveBeenCalledTimes(1)
|
||||
expect(recordCronHeartbeat.mock.calls[0][0].status).toBe('error')
|
||||
})
|
||||
|
||||
it('does not record an auth rejection: a 401 is not a run', async () => {
|
||||
verifyCronSecret.mockReturnValue(
|
||||
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
)
|
||||
const handler = withCronContext('cron.webhook_dispatch', async () =>
|
||||
NextResponse.json({ ok: true }),
|
||||
)
|
||||
|
||||
const response = await handler(request())
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
expect(recordCronHeartbeat).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never fails the cron run when the heartbeat write rejects', async () => {
|
||||
recordCronHeartbeat.mockRejectedValueOnce(new Error('db down'))
|
||||
const handler = withCronContext('cron.webhook_dispatch', async () =>
|
||||
NextResponse.json({ ok: true }),
|
||||
)
|
||||
|
||||
// recordCronHeartbeat swallows its own errors in production; this asserts
|
||||
// the wrapper does not turn a rejected mock into a 500 either.
|
||||
await expect(handler(request())).resolves.toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
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'
|
||||
|
||||
@@ -59,6 +60,20 @@ 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,
|
||||
@@ -111,6 +126,31 @@ export function withCronContext(
|
||||
|
||||
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')) {
|
||||
@@ -120,9 +160,11 @@ export function withCronContext(
|
||||
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 })
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user