|
| 1 | +// Failure alerts must describe only cron outcomes that survived durable persistence. |
| 2 | +import { describe, expect, it, vi } from "vitest"; |
| 3 | +import { |
| 4 | + createDueIsolatedJob, |
| 5 | + noopLogger, |
| 6 | + setupCronRegressionFixtures, |
| 7 | +} from "../../../test/helpers/cron/service-regression-fixtures.js"; |
| 8 | +import { markCronJobActive } from "../active-jobs.js"; |
| 9 | +import * as cronStoreModule from "../store.js"; |
| 10 | +import { loadCronStore, saveCronStore } from "../store.js"; |
| 11 | +import type { CronJob, CronRunStatus } from "../types.js"; |
| 12 | +import { createCronServiceState } from "./state.js"; |
| 13 | +import { finalizeCompletedCronRunOutcomes } from "./timer-outcome-finalization.js"; |
| 14 | + |
| 15 | +const fixtures = setupCronRegressionFixtures({ |
| 16 | + prefix: "cron-failure-alert-persistence-", |
| 17 | +}); |
| 18 | + |
| 19 | +type SendCronFailureAlert = NonNullable< |
| 20 | + Parameters<typeof createCronServiceState>[0]["sendCronFailureAlert"] |
| 21 | +>; |
| 22 | + |
| 23 | +function createAlertJob(params: { id: string; dueAt: number; includeSkipped?: boolean }): CronJob { |
| 24 | + const job = createDueIsolatedJob({ |
| 25 | + id: params.id, |
| 26 | + nowMs: params.dueAt, |
| 27 | + nextRunAtMs: params.dueAt, |
| 28 | + }); |
| 29 | + job.schedule = { kind: "every", everyMs: 60_000, anchorMs: params.dueAt - 60_000 }; |
| 30 | + job.failureAlert = { |
| 31 | + after: 1, |
| 32 | + cooldownMs: 60_000, |
| 33 | + ...(params.includeSkipped ? { includeSkipped: true } : {}), |
| 34 | + }; |
| 35 | + job.state.runningAtMs = params.dueAt; |
| 36 | + return job; |
| 37 | +} |
| 38 | + |
| 39 | +function createAlertState(params: { |
| 40 | + storePath: string; |
| 41 | + nowMs: () => number; |
| 42 | + sendCronFailureAlert: SendCronFailureAlert; |
| 43 | +}) { |
| 44 | + return createCronServiceState({ |
| 45 | + cronEnabled: true, |
| 46 | + storePath: params.storePath, |
| 47 | + log: noopLogger, |
| 48 | + nowMs: params.nowMs, |
| 49 | + enqueueSystemEvent: vi.fn(), |
| 50 | + requestHeartbeat: vi.fn(), |
| 51 | + sendCronFailureAlert: params.sendCronFailureAlert, |
| 52 | + runIsolatedAgentJob: vi.fn(), |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +async function finalizeAlertOutcome(params: { |
| 57 | + state: ReturnType<typeof createCronServiceState>; |
| 58 | + job: CronJob; |
| 59 | + status: Extract<CronRunStatus, "error" | "skipped">; |
| 60 | + error: string; |
| 61 | + startedAt: number; |
| 62 | + endedAt: number; |
| 63 | +}) { |
| 64 | + await finalizeCompletedCronRunOutcomes(params.state, [ |
| 65 | + { |
| 66 | + jobId: params.job.id, |
| 67 | + job: structuredClone(params.job), |
| 68 | + activeJobMarker: markCronJobActive(params.job.id), |
| 69 | + status: params.status, |
| 70 | + error: params.error, |
| 71 | + startedAt: params.startedAt, |
| 72 | + endedAt: params.endedAt, |
| 73 | + }, |
| 74 | + ]); |
| 75 | +} |
| 76 | + |
| 77 | +describe("cron failure alert persistence", () => { |
| 78 | + it.each([ |
| 79 | + { status: "error", includeSkipped: false }, |
| 80 | + { status: "skipped", includeSkipped: true }, |
| 81 | + ] as const)("delivers a $status alert once after the outcome is durable", async (testCase) => { |
| 82 | + const store = fixtures.makeStorePath(); |
| 83 | + const dueAt = Date.parse("2026-08-01T14:50:00.000Z"); |
| 84 | + const endedAt = dueAt + 10; |
| 85 | + const job = createAlertJob({ |
| 86 | + id: `${testCase.status}-alert-after-persist`, |
| 87 | + dueAt, |
| 88 | + includeSkipped: testCase.includeSkipped, |
| 89 | + }); |
| 90 | + await saveCronStore(store.storePath, { version: 1, jobs: [job] }); |
| 91 | + |
| 92 | + const order: string[] = []; |
| 93 | + const sendCronFailureAlert = vi.fn(async () => { |
| 94 | + order.push("alert"); |
| 95 | + }); |
| 96 | + const state = createAlertState({ |
| 97 | + storePath: store.storePath, |
| 98 | + nowMs: () => endedAt, |
| 99 | + sendCronFailureAlert, |
| 100 | + }); |
| 101 | + const save = cronStoreModule.saveCronJobsStore; |
| 102 | + const saveSpy = vi |
| 103 | + .spyOn(cronStoreModule, "saveCronJobsStore") |
| 104 | + .mockImplementation(async (...args) => { |
| 105 | + if (args[1].jobs[0]?.state.lastFailureAlertAtMs === endedAt) { |
| 106 | + expect(sendCronFailureAlert).not.toHaveBeenCalled(); |
| 107 | + await save(...args); |
| 108 | + order.push("persist"); |
| 109 | + return; |
| 110 | + } |
| 111 | + await save(...args); |
| 112 | + }); |
| 113 | + |
| 114 | + try { |
| 115 | + await finalizeAlertOutcome({ |
| 116 | + state, |
| 117 | + job, |
| 118 | + status: testCase.status, |
| 119 | + error: testCase.status === "error" ? "provider unavailable" : "disabled", |
| 120 | + startedAt: dueAt, |
| 121 | + endedAt, |
| 122 | + }); |
| 123 | + |
| 124 | + expect(order).toEqual(["persist", "alert"]); |
| 125 | + expect(sendCronFailureAlert).toHaveBeenCalledOnce(); |
| 126 | + expect((await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs).toBe( |
| 127 | + endedAt, |
| 128 | + ); |
| 129 | + } finally { |
| 130 | + saveSpy.mockRestore(); |
| 131 | + } |
| 132 | + }); |
| 133 | + |
| 134 | + it("rolls back the cooldown without delivery when persistence fails", async () => { |
| 135 | + const store = fixtures.makeStorePath(); |
| 136 | + const dueAt = Date.parse("2026-08-01T14:55:00.000Z"); |
| 137 | + const job = createAlertJob({ id: "failure-alert-persist-rollback", dueAt }); |
| 138 | + await saveCronStore(store.storePath, { version: 1, jobs: [job] }); |
| 139 | + |
| 140 | + const sendCronFailureAlert = vi.fn(async () => undefined); |
| 141 | + const state = createAlertState({ |
| 142 | + storePath: store.storePath, |
| 143 | + nowMs: () => dueAt + 10, |
| 144 | + sendCronFailureAlert, |
| 145 | + }); |
| 146 | + const saveSpy = vi |
| 147 | + .spyOn(cronStoreModule, "saveCronJobsStore") |
| 148 | + .mockRejectedValueOnce(new Error("terminal write failed")); |
| 149 | + |
| 150 | + try { |
| 151 | + await expect( |
| 152 | + finalizeAlertOutcome({ |
| 153 | + state, |
| 154 | + job, |
| 155 | + status: "error", |
| 156 | + error: "provider unavailable", |
| 157 | + startedAt: dueAt, |
| 158 | + endedAt: dueAt + 10, |
| 159 | + }), |
| 160 | + ).rejects.toThrow("terminal write failed"); |
| 161 | + |
| 162 | + expect(sendCronFailureAlert).not.toHaveBeenCalled(); |
| 163 | + expect(state.store?.jobs[0]?.state.lastFailureAlertAtMs).toBeUndefined(); |
| 164 | + expect( |
| 165 | + (await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs, |
| 166 | + ).toBeUndefined(); |
| 167 | + } finally { |
| 168 | + saveSpy.mockRestore(); |
| 169 | + } |
| 170 | + }); |
| 171 | + |
| 172 | + it("persists the cooldown atomically and suppresses a second alert", async () => { |
| 173 | + const store = fixtures.makeStorePath(); |
| 174 | + const dueAt = Date.parse("2026-08-01T14:58:00.000Z"); |
| 175 | + const firstAlertAt = dueAt + 10; |
| 176 | + const job = createAlertJob({ id: "failure-alert-cooldown-persisted", dueAt }); |
| 177 | + await saveCronStore(store.storePath, { version: 1, jobs: [job] }); |
| 178 | + |
| 179 | + let now = firstAlertAt; |
| 180 | + const sendCronFailureAlert = vi.fn(async () => undefined); |
| 181 | + const state = createAlertState({ |
| 182 | + storePath: store.storePath, |
| 183 | + nowMs: () => now, |
| 184 | + sendCronFailureAlert, |
| 185 | + }); |
| 186 | + |
| 187 | + await finalizeAlertOutcome({ |
| 188 | + state, |
| 189 | + job, |
| 190 | + status: "error", |
| 191 | + error: "first failure", |
| 192 | + startedAt: dueAt, |
| 193 | + endedAt: firstAlertAt, |
| 194 | + }); |
| 195 | + expect(sendCronFailureAlert).toHaveBeenCalledOnce(); |
| 196 | + expect((await loadCronStore(store.storePath)).jobs[0]?.state.lastFailureAlertAtMs).toBe( |
| 197 | + firstAlertAt, |
| 198 | + ); |
| 199 | + |
| 200 | + now += 30_000; |
| 201 | + const currentJob = state.store?.jobs[0]; |
| 202 | + if (!currentJob) { |
| 203 | + throw new Error("expected persisted cron job"); |
| 204 | + } |
| 205 | + await finalizeAlertOutcome({ |
| 206 | + state, |
| 207 | + job: currentJob, |
| 208 | + status: "error", |
| 209 | + error: "second failure", |
| 210 | + startedAt: now, |
| 211 | + endedAt: now + 10, |
| 212 | + }); |
| 213 | + |
| 214 | + expect(sendCronFailureAlert).toHaveBeenCalledOnce(); |
| 215 | + expect((await loadCronStore(store.storePath)).jobs[0]).toMatchObject({ |
| 216 | + state: { consecutiveErrors: 2, lastFailureAlertAtMs: firstAlertAt }, |
| 217 | + }); |
| 218 | + }); |
| 219 | +}); |
0 commit comments