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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
describeGap,
|
||||
maxIntervalSeconds,
|
||||
parseCronExpression,
|
||||
} from '../cron-interval'
|
||||
|
||||
/**
|
||||
* These are the numbers app/api/cron/health turns into alert thresholds, so the
|
||||
* tests assert the actual worst-case gaps rather than "returns a number". A
|
||||
* wrong threshold is not a cosmetic bug: too small and every slow run flaps the
|
||||
* cron container unhealthy, too large and a stopped schedule keeps looking fine
|
||||
* — the exact failure the 2026-11-15 incident was.
|
||||
*/
|
||||
describe('parseCronExpression', () => {
|
||||
it('parses the five fields in order', () => {
|
||||
const spec = parseCronExpression('15 3 * * 1-5')
|
||||
expect(spec.minutes).toEqual([15])
|
||||
expect(spec.hours).toEqual([3])
|
||||
expect(spec.daysOfMonth).toHaveLength(31)
|
||||
expect(spec.months).toHaveLength(12)
|
||||
expect(spec.daysOfWeek).toEqual([1, 2, 3, 4, 5])
|
||||
expect(spec.dayOfMonthRestricted).toBe(false)
|
||||
expect(spec.dayOfWeekRestricted).toBe(true)
|
||||
})
|
||||
|
||||
it('expands steps, ranges and lists', () => {
|
||||
expect(parseCronExpression('*/15 * * * *').minutes).toEqual([0, 15, 30, 45])
|
||||
expect(parseCronExpression('2,4,6-8 * * * *').minutes).toEqual([2, 4, 6, 7, 8])
|
||||
expect(parseCronExpression('5/20 * * * *').minutes).toEqual([5, 25, 45])
|
||||
})
|
||||
|
||||
it('normalises Sunday 7 to 0', () => {
|
||||
expect(parseCronExpression('0 0 * * 7').daysOfWeek).toEqual([0])
|
||||
expect(parseCronExpression('0 0 * * 0').daysOfWeek).toEqual([0])
|
||||
expect(parseCronExpression('0 0 * * 0,7').daysOfWeek).toEqual([0])
|
||||
})
|
||||
|
||||
it('treats a star step as unrestricted, like every cron implementation', () => {
|
||||
expect(parseCronExpression('0 0 */1 * *').dayOfMonthRestricted).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['* * * *', 'four fields'],
|
||||
['* * * * * *', 'six fields'],
|
||||
['60 * * * *', 'minute out of range'],
|
||||
['* 24 * * *', 'hour out of range'],
|
||||
['* * 0 * *', 'day-of-month out of range'],
|
||||
['* * * 13 *', 'month out of range'],
|
||||
['* * * * 8', 'day-of-week out of range'],
|
||||
['*/0 * * * *', 'zero step'],
|
||||
['5-2 * * * *', 'inverted range'],
|
||||
['a * * * *', 'non-numeric'],
|
||||
])('rejects %s (%s)', (expression) => {
|
||||
expect(() => parseCronExpression(expression)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('maxIntervalSeconds', () => {
|
||||
it('every-minute is exactly 60 s', () => {
|
||||
expect(maxIntervalSeconds('* * * * *')).toBe(60)
|
||||
})
|
||||
|
||||
it('*/2 is 120 s and */5 is 300 s', () => {
|
||||
expect(maxIntervalSeconds('*/2 * * * *')).toBe(120)
|
||||
expect(maxIntervalSeconds('*/5 * * * *')).toBe(300)
|
||||
})
|
||||
|
||||
it('hourly on the hour is 3600 s', () => {
|
||||
expect(maxIntervalSeconds('0 * * * *')).toBe(3600)
|
||||
})
|
||||
|
||||
it('a daily job is 86400 s', () => {
|
||||
expect(maxIntervalSeconds('0 6 * * *')).toBe(86_400)
|
||||
expect(maxIntervalSeconds('30 4 * * *')).toBe(86_400)
|
||||
})
|
||||
|
||||
it('every other hour at :30 is 7200 s, not 3600 s', () => {
|
||||
// The gap between 22:30 and 00:30 spans two hours; an average-gap
|
||||
// implementation would say 3600 and alert on the normal cadence.
|
||||
expect(maxIntervalSeconds('30 */2 * * *')).toBe(7200)
|
||||
})
|
||||
|
||||
it('weekly is seven days', () => {
|
||||
expect(maxIntervalSeconds('0 3 * * 0')).toBe(7 * 86_400)
|
||||
})
|
||||
|
||||
it('yearly on 2 January is 365 or 366 days depending on the leap year it spans', () => {
|
||||
// 2003-01-02 -> 2004-01-02 spans no 29 February, 2004 -> 2005 does not
|
||||
// either; 1 Jan -> 1 Jan crossing a leap day is the 8784-hour case. Either
|
||||
// way the threshold must be at least a year, never 0.
|
||||
expect(maxIntervalSeconds('0 0 2 1 *')).toBeGreaterThanOrEqual(365 * 86_400)
|
||||
})
|
||||
|
||||
it('29 February only matches in leap years and still returns a finite gap', () => {
|
||||
const gap = maxIntervalSeconds('0 0 29 2 *')
|
||||
expect(gap).toBeGreaterThanOrEqual(365 * 86_400)
|
||||
expect(Number.isFinite(gap)).toBe(true)
|
||||
})
|
||||
|
||||
it('honours the cron day rule: restricted day-of-month OR day-of-week', () => {
|
||||
// "1st of the month OR every Monday" still has a Monday every seven days,
|
||||
// so the worst case is a week — a naive AND would report ~28 days and hide
|
||||
// a fortnight of misses.
|
||||
expect(maxIntervalSeconds('0 0 1 * 1')).toBe(7 * 86_400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('describeGap', () => {
|
||||
it.each([
|
||||
[60, '60 s'],
|
||||
[120, '2 min'],
|
||||
[3600, '60 min'],
|
||||
[7200, '2 h'],
|
||||
[86_400, '24 h'],
|
||||
[7 * 86_400, '7 dygn'],
|
||||
])('renders %i s as %s', (seconds, expected) => {
|
||||
expect(describeGap(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
CRON_STALE_GRACE_SECONDS,
|
||||
CRON_STALE_MULTIPLIER,
|
||||
allowedAgeSeconds,
|
||||
evaluateCronHeartbeats,
|
||||
isFailingStatus,
|
||||
type CronHeartbeatRow,
|
||||
} from '../heartbeat-evaluation'
|
||||
import type { CronScheduleEntry } from '../schedules.generated'
|
||||
|
||||
const NOW = Date.parse('2026-11-15T12:00:00.000Z')
|
||||
|
||||
function entry(path: string, maxIntervalSeconds: number): CronScheduleEntry {
|
||||
return { path, schedule: '* * * * *', maxIntervalSeconds }
|
||||
}
|
||||
|
||||
function row(overrides: Partial<CronHeartbeatRow> & { path: string }): CronHeartbeatRow {
|
||||
return {
|
||||
declaredAt: '2026-11-15T11:00:00.000Z',
|
||||
lastStartedAt: null,
|
||||
lastCompletedAt: null,
|
||||
lastStatus: null,
|
||||
lastHttpStatus: null,
|
||||
lastDurationMs: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function isoSecondsAgo(seconds: number): string {
|
||||
return new Date(NOW - seconds * 1000).toISOString()
|
||||
}
|
||||
|
||||
describe('allowedAgeSeconds', () => {
|
||||
it('is two intervals plus the grace floor', () => {
|
||||
expect(CRON_STALE_MULTIPLIER).toBe(2)
|
||||
expect(CRON_STALE_GRACE_SECONDS).toBe(120)
|
||||
expect(allowedAgeSeconds(60)).toBe(240)
|
||||
expect(allowedAgeSeconds(86_400)).toBe(2 * 86_400 + 120)
|
||||
})
|
||||
})
|
||||
|
||||
describe('evaluateCronHeartbeats', () => {
|
||||
it('reports ok when the newest run is inside the window', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/invoices/recurring/cron', 3600)],
|
||||
rows: [row({ path: '/api/invoices/recurring/cron', lastStartedAt: isoSecondsAgo(1800), lastStatus: 'ok' })],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.checks[0].state).toBe('ok')
|
||||
expect(report.checks[0].ageSeconds).toBe(1800)
|
||||
expect(report.stale).toBe(0)
|
||||
})
|
||||
|
||||
it('reports stale when a per-minute schedule has not started for four minutes', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/webhooks/dispatch/cron', 60)],
|
||||
rows: [
|
||||
row({
|
||||
path: '/api/webhooks/dispatch/cron',
|
||||
lastStartedAt: isoSecondsAgo(241),
|
||||
lastStatus: 'ok',
|
||||
}),
|
||||
],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(false)
|
||||
expect(report.checks[0].state).toBe('stale')
|
||||
expect(report.stale).toBe(1)
|
||||
})
|
||||
|
||||
it('does not flag a single skipped tick', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/webhooks/dispatch/cron', 60)],
|
||||
rows: [row({ path: '/api/webhooks/dispatch/cron', lastStartedAt: isoSecondsAgo(120) })],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.checks[0].state).toBe('ok')
|
||||
})
|
||||
|
||||
it('treats a never-run path inside its declared grace as pending, not stale', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/new/job/cron', 86_400)],
|
||||
rows: [row({ path: '/api/new/job/cron', declaredAt: isoSecondsAgo(3600) })],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.pending).toBe(1)
|
||||
expect(report.checks[0].state).toBe('pending')
|
||||
})
|
||||
|
||||
it('flags a declared path that never ran once the grace is spent', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/new/job/cron', 86_400)],
|
||||
rows: [row({ path: '/api/new/job/cron', declaredAt: isoSecondsAgo(3 * 86_400) })],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(false)
|
||||
expect(report.checks[0].state).toBe('stale')
|
||||
})
|
||||
|
||||
it('reports a path with no row at all as pending on the first call', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/unknown/job/cron', 60)],
|
||||
rows: [],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.checks[0].state).toBe('pending')
|
||||
expect(report.checks[0].ageSeconds).toBeNull()
|
||||
})
|
||||
|
||||
it('measures staleness from the last START, so a hung run looks dead', () => {
|
||||
// The run started 3 h ago and (in this row) completed successfully 2 h 59
|
||||
// min ago — the row is doctored to prove last_started_at wins. After a hang
|
||||
// supercronic stops scheduling, so a completed_at-based check would keep
|
||||
// reporting ok while nothing new runs.
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/invoices/recurring/cron', 3600)],
|
||||
rows: [
|
||||
row({
|
||||
path: '/api/invoices/recurring/cron',
|
||||
lastStartedAt: isoSecondsAgo(3 * 3600),
|
||||
lastCompletedAt: isoSecondsAgo(60),
|
||||
}),
|
||||
],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.checks[0].state).toBe('stale')
|
||||
})
|
||||
|
||||
it('fails the report when any single path is stale', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/a/cron', 60), entry('/api/b/cron', 60)],
|
||||
rows: [
|
||||
row({ path: '/api/a/cron', lastStartedAt: isoSecondsAgo(30) }),
|
||||
row({ path: '/api/b/cron', lastStartedAt: isoSecondsAgo(600) }),
|
||||
],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(false)
|
||||
expect(report.stale).toBe(1)
|
||||
expect(report.checks.filter((check) => check.state === 'ok')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('carries the last outcome through so a failing-but-running job is visible', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/a/cron', 60)],
|
||||
rows: [
|
||||
row({
|
||||
path: '/api/a/cron',
|
||||
lastStartedAt: isoSecondsAgo(30),
|
||||
lastStatus: 'error',
|
||||
lastHttpStatus: 500,
|
||||
lastDurationMs: 42,
|
||||
}),
|
||||
],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.checks[0].lastStatus).toBe('error')
|
||||
expect(report.checks[0].lastHttpStatus).toBe(500)
|
||||
expect(report.checks[0].lastDurationMs).toBe(42)
|
||||
expect(isFailingStatus('error', 500)).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores a malformed timestamp instead of throwing', () => {
|
||||
const report = evaluateCronHeartbeats({
|
||||
entries: [entry('/api/a/cron', 60)],
|
||||
rows: [row({ path: '/api/a/cron', lastStartedAt: 'not-a-date' })],
|
||||
now: NOW,
|
||||
})
|
||||
|
||||
expect(report.ok).toBe(true)
|
||||
expect(report.checks[0].state).toBe('pending')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isFailingStatus', () => {
|
||||
it.each([
|
||||
['ok', 200, false],
|
||||
// A cron endpoint that redirects did not do its work either; curl -f
|
||||
// accepts a 3xx, which is exactly why this is worth surfacing separately.
|
||||
['ok', 302, true],
|
||||
['error', 200, true],
|
||||
['ok', 500, true],
|
||||
[null, 401, true],
|
||||
[null, null, false],
|
||||
])('status %s / http %s -> %s', (status, httpStatus, expected) => {
|
||||
expect(isFailingStatus(status as string | null, httpStatus as number | null)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Cron expression → the longest gap between two scheduled runs.
|
||||
*
|
||||
* Why this exists: the 2026-11-15 accounted incident. `accounted-cron` lost
|
||||
* 1 497 of 10 455 runs in a day (14,3 %) because `pids_limit: 30` made
|
||||
* `fork/exec /bin/sh` fail under the per-minute schedules, and supercronic
|
||||
* simply skipped those ticks. Nothing in the product noticed: the container
|
||||
* stayed "Up", every endpoint still answered, and the only trace was a line in
|
||||
* the cron container's own log. A schedule whose runs stop arriving is the
|
||||
* worst failure mode in this product — nothing looks broken, the work just
|
||||
* never happens — so `cron_heartbeats` records every run and
|
||||
* app/api/cron/health turns "no run arrived within the expected window" into a
|
||||
* 503 the container healthcheck can fail on.
|
||||
*
|
||||
* That check needs to know, per path, how long a gap is normal. That is this
|
||||
* module: a small, dependency-free interpreter for the 5-field cron syntax
|
||||
* `vercel.json` is restricted to, plus a brute-force scan of a 12-year window
|
||||
* to get the WORST-CASE gap rather than an average. Worst case is the correct
|
||||
* threshold input: a job that runs at 00:00 daily must be allowed 24 h, not
|
||||
* the 12 h its mean gap would suggest.
|
||||
*
|
||||
* The scan is exact for every expression the product uses, including the
|
||||
* calendar-sensitive ones (`0 0 2 1 *` once a year, `0 0 29 2 *` only in leap
|
||||
* years). It is not a general cron library: no seconds field, no `@daily`
|
||||
* aliases, no `L`/`W`/`#` extensions. Anything outside the supported subset
|
||||
* throws instead of guessing, and the generator that consumes it runs in CI, so
|
||||
* an unsupported expression fails the build rather than silently producing a
|
||||
* wrong alert threshold.
|
||||
*/
|
||||
|
||||
const MINUTE_MS = 60_000
|
||||
const HOUR_MS = 60 * MINUTE_MS
|
||||
const DAY_MS = 24 * HOUR_MS
|
||||
|
||||
/**
|
||||
* Scan window: 2001-01-01 + 12 years. Twelve years is what it takes to see
|
||||
* three occurrences of 29 February (2004, 2008, 2012), which is the rarest
|
||||
* yearly form a cron expression can express.
|
||||
*/
|
||||
const SCAN_START_MS = Date.UTC(2001, 0, 1)
|
||||
const SCAN_DAYS = 12 * 366
|
||||
|
||||
/**
|
||||
* Upper bound on matched timestamps per expression. A per-minute job matches
|
||||
* 1 440 times a day; 20 000 is two weeks of it, far more than needed to see the
|
||||
* 60-second gap, and it keeps the generator fast when the whole vercel.json is
|
||||
* scanned.
|
||||
*/
|
||||
const MAX_MATCHES = 20_000
|
||||
|
||||
export interface CronSpec {
|
||||
readonly minutes: readonly number[]
|
||||
readonly hours: readonly number[]
|
||||
readonly daysOfMonth: readonly number[]
|
||||
readonly months: readonly number[]
|
||||
readonly daysOfWeek: readonly number[]
|
||||
/**
|
||||
* Cron's day rule: when BOTH day-of-month and day-of-week are restricted the
|
||||
* expression matches if EITHER does; when only one is restricted only that
|
||||
* one applies. A step over the whole range (star followed by a step) counts
|
||||
* as unrestricted, as in every cron implementation, because the field still
|
||||
* starts with a star.
|
||||
*/
|
||||
readonly dayOfMonthRestricted: boolean
|
||||
readonly dayOfWeekRestricted: boolean
|
||||
}
|
||||
|
||||
function parseField(
|
||||
field: string,
|
||||
min: number,
|
||||
max: number,
|
||||
name: string,
|
||||
): { values: number[]; restricted: boolean } {
|
||||
const trimmed = field.trim()
|
||||
if (trimmed.length === 0) throw new Error(`cron: empty ${name} field`)
|
||||
|
||||
const seen = new Set<number>()
|
||||
for (const part of trimmed.split(',')) {
|
||||
const [rangePart, stepPart, ...rest] = part.split('/')
|
||||
if (rest.length > 0) throw new Error(`cron: bad step in ${name} field: ${part}`)
|
||||
|
||||
const step = stepPart === undefined ? 1 : Number(stepPart)
|
||||
if (!Number.isInteger(step) || step < 1) {
|
||||
throw new Error(`cron: bad step in ${name} field: ${part}`)
|
||||
}
|
||||
|
||||
let lo: number
|
||||
let hi: number
|
||||
if (rangePart === '*') {
|
||||
lo = min
|
||||
hi = max
|
||||
} else if (rangePart.includes('-')) {
|
||||
const [a, b, ...tail] = rangePart.split('-')
|
||||
if (tail.length > 0) throw new Error(`cron: bad range in ${name} field: ${part}`)
|
||||
lo = Number(a)
|
||||
hi = Number(b)
|
||||
} else {
|
||||
lo = Number(rangePart)
|
||||
// A bare value with a step (`5/10`) means "from 5 to max, every 10th".
|
||||
hi = stepPart === undefined ? lo : max
|
||||
}
|
||||
|
||||
if (!Number.isInteger(lo) || !Number.isInteger(hi)) {
|
||||
throw new Error(`cron: non-numeric value in ${name} field: ${part}`)
|
||||
}
|
||||
if (lo < min || hi > max || lo > hi) {
|
||||
throw new Error(`cron: ${name} field out of range ${min}-${max}: ${part}`)
|
||||
}
|
||||
|
||||
for (let v = lo; v <= hi; v += step) seen.add(v)
|
||||
}
|
||||
|
||||
return { values: [...seen].sort((a, b) => a - b), restricted: !trimmed.startsWith('*') }
|
||||
}
|
||||
|
||||
/** Parse a standard 5-field cron expression. Throws on anything unsupported. */
|
||||
export function parseCronExpression(expression: string): CronSpec {
|
||||
const fields = expression.trim().split(/\s+/)
|
||||
if (fields.length !== 5) {
|
||||
throw new Error(`cron: expected 5 fields, got ${fields.length}: ${JSON.stringify(expression)}`)
|
||||
}
|
||||
|
||||
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields
|
||||
const minutes = parseField(minute, 0, 59, 'minute')
|
||||
const hours = parseField(hour, 0, 23, 'hour')
|
||||
const dom = parseField(dayOfMonth, 1, 31, 'day-of-month')
|
||||
const months = parseField(month, 1, 12, 'month')
|
||||
// Cron allows both 0 and 7 for Sunday; normalise 7 to 0.
|
||||
const dow = parseField(dayOfWeek, 0, 7, 'day-of-week')
|
||||
|
||||
return {
|
||||
minutes: minutes.values,
|
||||
hours: hours.values,
|
||||
daysOfMonth: dom.values,
|
||||
months: months.values,
|
||||
daysOfWeek: [...new Set(dow.values.map((d) => (d === 7 ? 0 : d)))].sort((a, b) => a - b),
|
||||
dayOfMonthRestricted: dom.restricted,
|
||||
dayOfWeekRestricted: dow.restricted,
|
||||
}
|
||||
}
|
||||
|
||||
function matchesDay(spec: CronSpec, dayStartMs: number): boolean {
|
||||
const date = new Date(dayStartMs)
|
||||
if (!spec.months.includes(date.getUTCMonth() + 1)) return false
|
||||
|
||||
const domMatch = spec.daysOfMonth.includes(date.getUTCDate())
|
||||
const dowMatch = spec.daysOfWeek.includes(date.getUTCDay())
|
||||
|
||||
if (spec.dayOfMonthRestricted && spec.dayOfWeekRestricted) return domMatch || dowMatch
|
||||
if (spec.dayOfMonthRestricted) return domMatch
|
||||
if (spec.dayOfWeekRestricted) return dowMatch
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* The longest interval, in seconds, between two consecutive runs of
|
||||
* `expression` over a 12-year window.
|
||||
*
|
||||
* Throws when the expression never matches twice in the window — that is not a
|
||||
* schedule, and silently returning 0 would make the health check permanently
|
||||
* red or permanently green depending on which way the caller rounds.
|
||||
*/
|
||||
export function maxIntervalSeconds(expression: string): number {
|
||||
const spec = parseCronExpression(expression)
|
||||
|
||||
// Every minute: the answer is exactly one minute and the scan is pointless.
|
||||
if (spec.minutes.length * spec.hours.length === 24 * 60) return 60
|
||||
|
||||
let previous: number | null = null
|
||||
let longest = 0
|
||||
let matches = 0
|
||||
|
||||
for (let day = 0; day < SCAN_DAYS && matches < MAX_MATCHES; day++) {
|
||||
const dayStart = SCAN_START_MS + day * DAY_MS
|
||||
if (!matchesDay(spec, dayStart)) continue
|
||||
|
||||
for (const hour of spec.hours) {
|
||||
for (const minute of spec.minutes) {
|
||||
const at = dayStart + hour * HOUR_MS + minute * MINUTE_MS
|
||||
if (previous !== null) {
|
||||
const gap = (at - previous) / 1000
|
||||
if (gap > longest) longest = gap
|
||||
}
|
||||
previous = at
|
||||
if (++matches >= MAX_MATCHES) break
|
||||
}
|
||||
if (matches >= MAX_MATCHES) break
|
||||
}
|
||||
}
|
||||
|
||||
if (matches < 2) {
|
||||
throw new Error(`cron: ${JSON.stringify(expression)} never matches twice in the scan window`)
|
||||
}
|
||||
|
||||
return longest
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable worst-case gap, for the generated file and for operators
|
||||
* reading a 503 body. Deliberately coarse: it is a threshold input, not a
|
||||
* display string that needs to be exact.
|
||||
*/
|
||||
export function describeGap(seconds: number): string {
|
||||
if (seconds < 120) return `${seconds} s`
|
||||
if (seconds < 2 * 3600) return `${Math.round(seconds / 60)} min`
|
||||
if (seconds < 2 * 86_400) return `${Math.round(seconds / 3600)} h`
|
||||
return `${Math.round(seconds / 86_400)} dygn`
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Missed-cron detection, the pure half.
|
||||
*
|
||||
* The store and the endpoint live in ./heartbeat-store.ts and
|
||||
* app/api/cron/health/route.ts; everything that decides ok/stale is here so it
|
||||
* can be tested without a database.
|
||||
*
|
||||
* The threshold is deliberately generous, because the cost of the two mistakes
|
||||
* is not symmetric. Too tight and every slow run flaps the container
|
||||
* unhealthy, which trains people to ignore the check. Too loose and a stalled
|
||||
* schedule keeps looking fine — the failure mode this exists to catch (see the
|
||||
* 2026-11-15 pids_limit incident in the cron_heartbeats migration). Two missed
|
||||
* intervals plus a two-minute floor means a per-minute job is flagged after
|
||||
* 4 minutes and a daily job after 48 h 2 min, while one skipped tick or one
|
||||
* slow run is not.
|
||||
*/
|
||||
|
||||
import type { CronScheduleEntry } from './schedules.generated'
|
||||
|
||||
/** A run is stale after this many missed intervals. */
|
||||
export const CRON_STALE_MULTIPLIER = 2
|
||||
|
||||
/** Floor added on top of the interval, absorbing clock skew and one slow run. */
|
||||
export const CRON_STALE_GRACE_SECONDS = 120
|
||||
|
||||
export type CronHeartbeatState = 'ok' | 'pending' | 'stale'
|
||||
|
||||
/** A row as the store returns it (snake_case columns already mapped). */
|
||||
export interface CronHeartbeatRow {
|
||||
path: string
|
||||
declaredAt: string | null
|
||||
lastStartedAt: string | null
|
||||
lastCompletedAt: string | null
|
||||
lastStatus: string | null
|
||||
lastHttpStatus: number | null
|
||||
lastDurationMs: number | null
|
||||
}
|
||||
|
||||
export interface CronHeartbeatCheck {
|
||||
path: string
|
||||
schedule: string
|
||||
maxIntervalSeconds: number
|
||||
/** Age at which this path is reported stale. */
|
||||
allowedAgeSeconds: number
|
||||
lastStartedAt: string | null
|
||||
ageSeconds: number | null
|
||||
state: CronHeartbeatState
|
||||
lastStatus: string | null
|
||||
lastHttpStatus: number | null
|
||||
lastDurationMs: number | null
|
||||
}
|
||||
|
||||
export interface CronHeartbeatReport {
|
||||
/** False only when at least one path is stale. Pending paths do not fail. */
|
||||
ok: boolean
|
||||
checkedAt: string
|
||||
total: number
|
||||
stale: number
|
||||
pending: number
|
||||
checks: CronHeartbeatCheck[]
|
||||
}
|
||||
|
||||
export function allowedAgeSeconds(maxIntervalSeconds: number): number {
|
||||
return maxIntervalSeconds * CRON_STALE_MULTIPLIER + CRON_STALE_GRACE_SECONDS
|
||||
}
|
||||
|
||||
function ageInSeconds(reference: string | null, now: number): number | null {
|
||||
if (!reference) return null
|
||||
const at = Date.parse(reference)
|
||||
if (!Number.isFinite(at)) return null
|
||||
return Math.max(0, Math.round((now - at) / 1000))
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate every scheduled path against its heartbeat row.
|
||||
*
|
||||
* States:
|
||||
* ok — a run started within the allowed age.
|
||||
* pending — no run yet, but the path has not been declared longer than its
|
||||
* own cadence allows. A freshly added job, or a fresh install.
|
||||
* stale — a run used to arrive and stopped, OR the path was declared
|
||||
* longer ago than its cadence and has never run. Both are real
|
||||
* defects; only `stale` fails the endpoint.
|
||||
*
|
||||
* A path with neither a row nor a declaration is reported `pending` here; the
|
||||
* route declares it before evaluating, so this only happens on the first call.
|
||||
*/
|
||||
export function evaluateCronHeartbeats(params: {
|
||||
entries: readonly CronScheduleEntry[]
|
||||
rows: readonly CronHeartbeatRow[]
|
||||
now: number
|
||||
}): CronHeartbeatReport {
|
||||
const byPath = new Map(params.rows.map((row) => [row.path, row]))
|
||||
|
||||
const checks: CronHeartbeatCheck[] = params.entries.map((entry) => {
|
||||
const row = byPath.get(entry.path)
|
||||
const allowed = allowedAgeSeconds(entry.maxIntervalSeconds)
|
||||
|
||||
// Staleness is measured from the last START. A run that hangs never
|
||||
// completes, and supercronic skips every later tick while it hangs, so
|
||||
// last_completed_at would keep a dead schedule looking alive.
|
||||
const ranAt = row?.lastStartedAt ?? null
|
||||
const reference = ranAt ?? row?.declaredAt ?? null
|
||||
const age = ageInSeconds(reference, params.now)
|
||||
|
||||
let state: CronHeartbeatState = 'ok'
|
||||
if (age === null) state = 'pending'
|
||||
else if (age > allowed) state = 'stale'
|
||||
else if (ranAt === null) state = 'pending'
|
||||
|
||||
return {
|
||||
path: entry.path,
|
||||
schedule: entry.schedule,
|
||||
maxIntervalSeconds: entry.maxIntervalSeconds,
|
||||
allowedAgeSeconds: allowed,
|
||||
lastStartedAt: ranAt,
|
||||
ageSeconds: age,
|
||||
state,
|
||||
lastStatus: row?.lastStatus ?? null,
|
||||
lastHttpStatus: row?.lastHttpStatus ?? null,
|
||||
lastDurationMs: row?.lastDurationMs ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
const stale = checks.filter((check) => check.state === 'stale').length
|
||||
const pending = checks.filter((check) => check.state === 'pending').length
|
||||
|
||||
return {
|
||||
ok: stale === 0,
|
||||
checkedAt: new Date(params.now).toISOString(),
|
||||
total: checks.length,
|
||||
stale,
|
||||
pending,
|
||||
checks,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A run that finished non-2xx is not a missed tick (it ran), but it is worth
|
||||
* surfacing next to the heartbeat: a schedule that "works" while every run
|
||||
* fails is the same silent outage with an extra step.
|
||||
*/
|
||||
export function isFailingStatus(status: string | null, httpStatus: number | null): boolean {
|
||||
if (status && status !== 'ok') return true
|
||||
return httpStatus !== null && (httpStatus < 200 || httpStatus >= 300)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// AUTO-GENERATED: do not edit. Run `npm run crontabs:generate` to regenerate.
|
||||
//
|
||||
// Variant: self-hosted (the crontab a Docker install runs).
|
||||
// Source of truth: the `crons` array in vercel.json, via
|
||||
// scripts/generate-crontabs.ts. scripts/__tests__/generate-crontabs.test.ts
|
||||
// fails CI if this file drifts from it.
|
||||
//
|
||||
// Consumed by lib/cron/heartbeats.ts: app/api/cron/health compares the last
|
||||
// recorded run of each path against maxIntervalSeconds and answers 503 when a
|
||||
// schedule stops arriving. The container healthcheck on the cron service calls
|
||||
// that endpoint, so a silent stop becomes a visible unhealthy container
|
||||
// instead of a log line nobody reads (see the 2026-11-15 pids_limit incident).
|
||||
//
|
||||
// maxIntervalSeconds is the WORST-CASE gap over a 12-year scan, not an
|
||||
// average: a daily job must be allowed 24 h, and 29 February must not make a
|
||||
// yearly job look dead for four years.
|
||||
|
||||
export interface CronScheduleEntry {
|
||||
readonly path: string
|
||||
readonly schedule: string
|
||||
/** Worst-case seconds between two runs, over a 12-year scan window. */
|
||||
readonly maxIntervalSeconds: number
|
||||
}
|
||||
|
||||
export const CRON_SCHEDULES: readonly CronScheduleEntry[] = [
|
||||
{ path: '/api/deadlines/status/cron', schedule: '0 6 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/invoices/recurring/cron', schedule: '0 * * * *', maxIntervalSeconds: 3600 }, // 60 min
|
||||
{ path: '/api/settings/booking-templates/sync/cron', schedule: '30 4 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/tax-deadlines/cron', schedule: '0 0 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/enable-banking/sync/cron', schedule: '0 5 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/stripe/transactions/cron', schedule: '30 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/woocommerce/orders/cron', schedule: '45 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/shopify/orders/cron', schedule: '15 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/zettle/orders/cron', schedule: '30 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/documents/verify/cron', schedule: '0 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/documents/reanchor/cron', schedule: '30 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/sandbox/cleanup/cron', schedule: '0 4 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/events/cleanup/cron', schedule: '0 2 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/cloud-backup/auto-sync/cron', schedule: '0 * * * *', maxIntervalSeconds: 3600 }, // 60 min
|
||||
{ path: '/api/idempotency/cleanup/cron', schedule: '30 * * * *', maxIntervalSeconds: 3600 }, // 60 min
|
||||
{ path: '/api/pending-operations/expire/cron', schedule: '30 2 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/skatteverket/ombud/sync/cron', schedule: '30 3 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/skatteverket/skattekonto/sync/cron', schedule: '0 4 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/skatteverket/agi/kvittenser/cron', schedule: '*/15 * * * *', maxIntervalSeconds: 900 }, // 15 min
|
||||
{ path: '/api/extensions/skatteverket/vat/kvittenser/cron', schedule: '30 */2 * * *', maxIntervalSeconds: 7200 }, // 2 h
|
||||
{ path: '/api/webhooks/dispatch/cron', schedule: '* * * * *', maxIntervalSeconds: 60 }, // 60 s
|
||||
{ path: '/api/extensions/whatsapp-inbox/sweep/cron', schedule: '* * * * *', maxIntervalSeconds: 60 }, // 60 s
|
||||
{ path: '/api/extensions/whatsapp-inbox/retention/cron', schedule: '15 4 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/invoice-inbox/sweep/cron', schedule: '*/2 * * * *', maxIntervalSeconds: 120 }, // 2 min
|
||||
{ path: '/api/extensions/invoice-inbox/underlag-reconcile/cron', schedule: '45 5 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/extensions/arcim-migration/complete-invoice-lines/cron', schedule: '20 * * * *', maxIntervalSeconds: 3600 }, // 60 min
|
||||
{ path: '/api/extensions/arcim-migration/cleanup/cron', schedule: '*/5 * * * *', maxIntervalSeconds: 300 }, // 5 min
|
||||
{ path: '/api/bookkeeping/accruals/post-due/cron', schedule: '15 5 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/receipt-hunt/cron', schedule: '30 5 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/notifications/bookkeeping-digest/cron', schedule: '45 5 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/notifications/multi-user-grace/cron', schedule: '0 7 * * *', maxIntervalSeconds: 86400 }, // 24 h
|
||||
{ path: '/api/peppol/inbound/cron', schedule: '*/10 * * * *', maxIntervalSeconds: 600 }, // 10 min
|
||||
{ path: '/api/peppol/outbound/status/cron', schedule: '5,20,35,50 * * * *', maxIntervalSeconds: 900 }, // 15 min
|
||||
{ path: '/api/connector/sync/cron', schedule: '17 * * * *', maxIntervalSeconds: 3600 }, // 60 min
|
||||
]
|
||||
Reference in New Issue
Block a user