|
| 1 | +import { failureNotificationDeliveryFromJobState } from "./failure-alerts.js"; |
| 2 | +import { nextWakeAtMs, recomputeNextRunsForMaintenance } from "./jobs.js"; |
| 3 | +import { locked } from "./locked.js"; |
| 4 | +import { emitCronRunFinished } from "./ops-run-preparation.js"; |
| 5 | +import { cancelCronRunAdmissionWaiters } from "./run-admission.js"; |
| 6 | +import { |
| 7 | + type InterruptedStartupRun, |
| 8 | + markInterruptedStartupRun, |
| 9 | + restoreFinalizedStartupRun, |
| 10 | + STARTUP_INTERRUPTED_ERROR, |
| 11 | +} from "./startup-run-repair.js"; |
| 12 | +import type { CronServiceState } from "./state.js"; |
| 13 | +import { ensureLoaded, persist } from "./store.js"; |
| 14 | +import { tryFindCronTaskRunIdForRecovery, tryFindFinalizedCronTaskRun } from "./task-runs.js"; |
| 15 | +import { armTimer, runMissedJobs, stopTimer } from "./timer.js"; |
| 16 | + |
| 17 | +/** Starts the cron service, recovers interrupted runs, catches up missed jobs, and arms the timer. */ |
| 18 | +export async function start(state: CronServiceState) { |
| 19 | + state.stopped = false; |
| 20 | + if (!state.deps.cronEnabled) { |
| 21 | + state.deps.log.info({ enabled: false }, "cron: disabled"); |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + const interruptedJobIds = new Set<string>(); |
| 26 | + const interruptedRuns: InterruptedStartupRun[] = []; |
| 27 | + const completedJobIdsToDelete = new Set<string>(); |
| 28 | + let repairedAnyStartupRun = false; |
| 29 | + await locked(state, async () => { |
| 30 | + await ensureLoaded(state, { skipRecompute: true }); |
| 31 | + if (state.stopped) { |
| 32 | + return; |
| 33 | + } |
| 34 | + const jobs = state.store?.jobs ?? []; |
| 35 | + for (const job of jobs) { |
| 36 | + job.state ??= {}; |
| 37 | + if (typeof job.state.queuedAtMs === "number") { |
| 38 | + state.deps.log.info( |
| 39 | + { jobId: job.id, queuedAtMs: job.state.queuedAtMs }, |
| 40 | + "cron: releasing queued job reservation on startup", |
| 41 | + ); |
| 42 | + job.state.queuedAtMs = undefined; |
| 43 | + repairedAnyStartupRun = true; |
| 44 | + } |
| 45 | + if (typeof job.state.runningAtMs === "number") { |
| 46 | + // Older releases used runningAtMs for both queued and active work. Those |
| 47 | + // rows are intentionally recovered conservatively to avoid replaying side effects. |
| 48 | + const runningAtMs = job.state.runningAtMs; |
| 49 | + const taskRunId = tryFindCronTaskRunIdForRecovery(state, job.id, runningAtMs); |
| 50 | + const finalized = tryFindFinalizedCronTaskRun(state, job.id, runningAtMs); |
| 51 | + if (finalized) { |
| 52 | + interruptedJobIds.add(job.id); |
| 53 | + if ( |
| 54 | + restoreFinalizedStartupRun({ |
| 55 | + state, |
| 56 | + job, |
| 57 | + runningAtMs, |
| 58 | + entry: finalized.entry, |
| 59 | + ...(finalized.scriptResult ? { scriptResult: finalized.scriptResult } : {}), |
| 60 | + ...(finalized.triggerEval ? { triggerEval: finalized.triggerEval } : {}), |
| 61 | + }) |
| 62 | + ) { |
| 63 | + completedJobIdsToDelete.add(job.id); |
| 64 | + } |
| 65 | + repairedAnyStartupRun = true; |
| 66 | + continue; |
| 67 | + } |
| 68 | + const nowMs = state.deps.nowMs(); |
| 69 | + const interrupted = markInterruptedStartupRun({ |
| 70 | + state, |
| 71 | + job, |
| 72 | + taskRunId, |
| 73 | + runningAtMs, |
| 74 | + nowMs, |
| 75 | + }); |
| 76 | + interruptedJobIds.add(job.id); |
| 77 | + interruptedRuns.push(interrupted); |
| 78 | + repairedAnyStartupRun = true; |
| 79 | + } |
| 80 | + } |
| 81 | + if (completedJobIdsToDelete.size > 0 && state.store) { |
| 82 | + state.store.jobs = jobs.filter((job) => !completedJobIdsToDelete.has(job.id)); |
| 83 | + } |
| 84 | + if (repairedAnyStartupRun || jobs.length > 0) { |
| 85 | + await persist(state, repairedAnyStartupRun ? undefined : { stateOnly: true }); |
| 86 | + } |
| 87 | + }); |
| 88 | + |
| 89 | + if (state.stopped) { |
| 90 | + return; |
| 91 | + } |
| 92 | + await runMissedJobs(state, { |
| 93 | + skipJobIds: interruptedJobIds.size > 0 ? interruptedJobIds : undefined, |
| 94 | + deferAgentTurnJobs: true, |
| 95 | + }); |
| 96 | + |
| 97 | + await locked(state, async () => { |
| 98 | + // Startup catch-up already persisted the latest in-memory store state, and |
| 99 | + // this path runs before the scheduler begins servicing regular timer ticks. |
| 100 | + // Avoid an extra reload/write cycle on startup. |
| 101 | + await ensureLoaded(state, { skipRecompute: true }); |
| 102 | + if (state.stopped) { |
| 103 | + return; |
| 104 | + } |
| 105 | + const changed = recomputeNextRunsForMaintenance(state, { recomputeExpired: true }); |
| 106 | + if (changed) { |
| 107 | + await persist(state); |
| 108 | + } |
| 109 | + for (const interrupted of interruptedRuns) { |
| 110 | + const job = state.store?.jobs.find((entry) => entry.id === interrupted.jobId); |
| 111 | + emitCronRunFinished( |
| 112 | + state, |
| 113 | + { |
| 114 | + jobId: interrupted.jobId, |
| 115 | + action: "finished", |
| 116 | + job, |
| 117 | + status: "error", |
| 118 | + error: STARTUP_INTERRUPTED_ERROR, |
| 119 | + delivered: false, |
| 120 | + deliveryStatus: "unknown", |
| 121 | + deliveryError: STARTUP_INTERRUPTED_ERROR, |
| 122 | + failureNotificationDelivery: job |
| 123 | + ? failureNotificationDeliveryFromJobState(job) |
| 124 | + : undefined, |
| 125 | + runAtMs: interrupted.runAtMs, |
| 126 | + durationMs: interrupted.durationMs, |
| 127 | + nextRunAtMs: job?.state.nextRunAtMs, |
| 128 | + }, |
| 129 | + undefined, |
| 130 | + interrupted.taskRunId, |
| 131 | + ); |
| 132 | + } |
| 133 | + armTimer(state); |
| 134 | + state.deps.log.info( |
| 135 | + { |
| 136 | + enabled: true, |
| 137 | + jobs: state.store?.jobs.length ?? 0, |
| 138 | + nextWakeAtMs: nextWakeAtMs(state) ?? null, |
| 139 | + }, |
| 140 | + "cron: started", |
| 141 | + ); |
| 142 | + }); |
| 143 | +} |
| 144 | + |
| 145 | +/** Stops the cron service timer without mutating persisted job state. */ |
| 146 | +export function stop(state: CronServiceState) { |
| 147 | + state.stopped = true; |
| 148 | + cancelCronRunAdmissionWaiters(state); |
| 149 | + state.schedulerStarted = false; |
| 150 | + stopTimer(state); |
| 151 | +} |
| 152 | + |
| 153 | +/** Temporarily stops automatic ticks without running startup recovery on resume. */ |
| 154 | +export function pauseScheduling(state: CronServiceState) { |
| 155 | + state.schedulingPaused = true; |
| 156 | + stopTimer(state); |
| 157 | +} |
| 158 | + |
| 159 | +export function resumeScheduling(state: CronServiceState) { |
| 160 | + if (!state.schedulingPaused) { |
| 161 | + return; |
| 162 | + } |
| 163 | + state.schedulingPaused = false; |
| 164 | + if (!state.schedulerStarted) { |
| 165 | + return; |
| 166 | + } |
| 167 | + try { |
| 168 | + armTimer(state); |
| 169 | + } catch (err) { |
| 170 | + // armTimer can install a timer before a later dependency throws. Roll the |
| 171 | + // whole transition back so a suspension retry cannot reopen without cron. |
| 172 | + state.schedulingPaused = true; |
| 173 | + stopTimer(state); |
| 174 | + throw err; |
| 175 | + } |
| 176 | +} |
0 commit comments