diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cf64b2291ae..b2f08244db8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ Work in this release was contributed by @kunal649. Thank you for your contribution! +### Important Changes + +- **ref(server-utils): Share one cron converter across cron integrations ([#25918](https://github.com/getsentry/sentry-javascript/pull/25918))** + + `Sentry.cron.instrumentCron`, `instrumentNodeCron` and `instrumentNodeSchedule` send the server's time zone when a job has none, so monitors don't report false misses on servers that aren't on UTC. Schedules Sentry can't express exactly, such as per-second schedules, send no monitor config, so the monitor keeps the schedule set in Sentry. `Sentry.cron.instrumentNodeCron` is deprecated; use `nodeCronIntegration` instead. + ## 11.12.0 ### Important Changes diff --git a/dev-packages/node-integration-tests/suites/cron/cron/scenario.ts b/dev-packages/node-integration-tests/suites/cron/cron/scenario.ts index 68cf28bcde94..7b09360de5e8 100644 --- a/dev-packages/node-integration-tests/suites/cron/cron/scenario.ts +++ b/dev-packages/node-integration-tests/suites/cron/cron/scenario.ts @@ -10,32 +10,26 @@ const CronJobWithCheckIn = Sentry.cron.instrumentCron(CronJob, 'my-cron-job'); let closeNext = false; -const cron = new CronJobWithCheckIn('* * * * * *', () => { - if (closeNext) { - cron.stop(); - throw new Error('Error in cron job'); - } - - // eslint-disable-next-line no-console - console.log('You will see this message every second'); - closeNext = true; -}); - -cron.start(); - -// `cron` sizes the delay to the next tick from two clock reads, clamps a negative result to -1 and -// then treats that -1 as "stop". A pause between those two reads that straddles a second boundary -// is enough to hit it, and the job is left scheduled for nothing: no ticks, no check-ins, and the -// scenario exits on the timeout below having sent nothing at all. Starting again re-reads the clock -// away from the boundary. -for (let attempt = 0; attempt < 5 && !cron.isActive; attempt++) { - cron.start(); -} - -if (!cron.isActive) { - throw new Error('`cron` refused to schedule the job'); -} +const cron = new CronJobWithCheckIn( + '0 9 * * 1-5', + () => { + if (closeNext) { + throw new Error('Error in cron job'); + } + + closeNext = true; + }, + undefined, + false, + 'Europe/Vienna', +); + +// Run the job without waiting for its schedule. +(async () => { + await cron.fireOnTick(); + await cron.fireOnTick(); +})(); setTimeout(() => { process.exit(); -}, 15_000); +}, 10_000); diff --git a/dev-packages/node-integration-tests/suites/cron/cron/test.ts b/dev-packages/node-integration-tests/suites/cron/cron/test.ts index 68f0beda37d3..fe1a91fe0620 100644 --- a/dev-packages/node-integration-tests/suites/cron/cron/test.ts +++ b/dev-packages/node-integration-tests/suites/cron/cron/test.ts @@ -1,6 +1,11 @@ import { afterAll, expect, test } from 'vitest'; import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; +const MONITOR_CONFIG = { + schedule: { type: 'crontab', value: '0 9 * * 1-5' }, + timezone: 'Europe/Vienna', +}; + afterAll(() => { cleanupChildProcesses(); }); @@ -17,7 +22,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -47,7 +52,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), diff --git a/dev-packages/node-integration-tests/suites/cron/node-cron/base/scenario.ts b/dev-packages/node-integration-tests/suites/cron/node-cron/base/scenario.ts index fb69a5de2482..6466eaf27137 100644 --- a/dev-packages/node-integration-tests/suites/cron/node-cron/base/scenario.ts +++ b/dev-packages/node-integration-tests/suites/cron/node-cron/base/scenario.ts @@ -13,24 +13,24 @@ const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron); let closeNext = false; const task = cronWithCheckIn.schedule( - '* * * * * *', + '0 9 * * 1-5', () => { if (closeNext) { - // https://github.com/node-cron/node-cron/issues/317 - setImmediate(() => { - task.stop(); - }); - throw new Error('Error in cron job'); } - // eslint-disable-next-line no-console - console.log('You will see this message every second'); closeNext = true; }, - { name: 'my-cron-job' }, + { name: 'my-cron-job', timezone: 'Europe/Vienna' }, ); +// Run the task without waiting for its schedule. +task.stop(); +task + .execute() + .then(() => task.execute()) + .catch(() => {}); + setTimeout(() => { process.exit(); -}, 15_000); +}, 10_000); diff --git a/dev-packages/node-integration-tests/suites/cron/node-cron/base/test.ts b/dev-packages/node-integration-tests/suites/cron/node-cron/base/test.ts index 61cfe7bf2943..e58302bd4007 100644 --- a/dev-packages/node-integration-tests/suites/cron/node-cron/base/test.ts +++ b/dev-packages/node-integration-tests/suites/cron/node-cron/base/test.ts @@ -1,6 +1,11 @@ import { afterAll, expect, test } from 'vitest'; import { cleanupChildProcesses, createRunner } from '../../../../utils/runner'; +const MONITOR_CONFIG = { + schedule: { type: 'crontab', value: '0 9 * * 1-5' }, + timezone: 'Europe/Vienna', +}; + afterAll(() => { cleanupChildProcesses(); }); @@ -13,7 +18,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -43,7 +48,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), diff --git a/dev-packages/node-integration-tests/suites/cron/node-schedule/scenario.ts b/dev-packages/node-integration-tests/suites/cron/node-schedule/scenario.ts index 2bb67cc0047c..cb85838f9ff5 100644 --- a/dev-packages/node-integration-tests/suites/cron/node-schedule/scenario.ts +++ b/dev-packages/node-integration-tests/suites/cron/node-schedule/scenario.ts @@ -12,17 +12,19 @@ const scheduleWithCheckIn = Sentry.cron.instrumentNodeSchedule(schedule); let closeNext = false; -const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '* * * * * *', () => { +const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '0 9 * * 1-5', () => { if (closeNext) { - job.cancel(); throw new Error('Error in cron job'); } - // eslint-disable-next-line no-console - console.log('You will see this message every second'); closeNext = true; }); +// Run the job without waiting for its schedule. +job.cancel(); +// The second run's error is unhandled, like when node-schedule runs the job. +void Promise.resolve(job.invoke()).then(() => job.invoke()); + setTimeout(() => { process.exit(); -}, 15_000); +}, 10_000); diff --git a/dev-packages/node-integration-tests/suites/cron/node-schedule/test.ts b/dev-packages/node-integration-tests/suites/cron/node-schedule/test.ts index 08905b77e45f..a237cc72fd17 100644 --- a/dev-packages/node-integration-tests/suites/cron/node-schedule/test.ts +++ b/dev-packages/node-integration-tests/suites/cron/node-schedule/test.ts @@ -1,6 +1,11 @@ import { afterAll, expect, test } from 'vitest'; import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; +const MONITOR_CONFIG = { + schedule: { type: 'crontab', value: '0 9 * * 1-5' }, + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, +}; + afterAll(() => { cleanupChildProcesses(); }); @@ -13,7 +18,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -43,7 +48,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index 0a74734adb8b..f255e293fcb4 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -3,6 +3,7 @@ import { CODE_FUNCTION_NAME, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/convention import { captureException, debug } from '@sentry/core'; import * as Sentry from '@sentry/node'; import { startSpan } from '@sentry/node'; +import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils'; import { DEBUG_BUILD } from './debug-build'; import { isExpectedError } from './helpers'; import type { ReflectWithMetadata } from './integrations/helpers'; @@ -98,18 +99,6 @@ function resolveMonitorConfig( const SCHEDULE_CRON_OPTIONS = 'SCHEDULE_CRON_OPTIONS'; -// `cron` presets (case-insensitive). Sentry accepts only the first five, so the others are sent as crontabs. -const CRON_PRESETS: Record = { - '@yearly': '@yearly', - '@monthly': '@monthly', - '@weekly': '@weekly', - '@daily': '@daily', - '@hourly': '@hourly', - '@minutely': '* * * * *', - '@weekdays': '0 0 * * 1-5', - '@weekends': '0 0 * * 0,6', -}; - interface NestCronOptions { cronTime?: unknown; timeZone?: unknown; @@ -150,118 +139,15 @@ export function nestCronOptionsToMonitorConfig( return undefined; } + // `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps and names don't depend on that. const fields = cronTime.trim().split(/\s+/); - let crontab: string | undefined; - if (fields.length === 1) { - crontab = CRON_PRESETS[(fields[0] as string).toLowerCase()]; - } else if (fields.length === 5) { - crontab = isSupportedCrontab(fields, scheduleVersion) ? fields.join(' ') : undefined; - } else if (fields.length === 6 && /^\d+$/.test(fields[0] as string)) { - // Sentry schedules have minute granularity, so only a fixed second can be dropped. - crontab = isSupportedCrontab(fields.slice(1), scheduleVersion) ? fields.slice(1).join(' ') : undefined; - } - - if (!crontab) { - return undefined; - } - - // Without a `timeZone`, `cron` uses the server's time zone, but Sentry would assume UTC. - const timezone = toSentryTimeZone(typeof timeZone === 'string' && timeZone ? timeZone : getLocalTimeZone()); - if (!timezone) { - return undefined; - } - - return { - schedule: { type: 'crontab', value: crontab }, - timezone, - }; -} - -/** - * Whether Sentry reads the 5 crontab fields the same way `cron` (used by `@nestjs/schedule`) runs them. - */ -function isSupportedCrontab( - [, , dayOfMonth = '', month = '', dayOfWeek = '']: string[], - scheduleVersion: string | undefined, -): boolean { - // `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps don't depend on that. + const month = fields.length >= 5 ? (fields[fields.length - 2] as string) : ''; const countsMonthsFromOne = parseInt(scheduleVersion ?? '', 10) >= 4; if (!countsMonthsFromOne && /\d/.test(month.replace(/\/\d+/g, ''))) { - return false; - } - - const daysOfMonth = countCronValues(dayOfMonth, 1, 31); - const daysOfWeek = countCronValues(dayOfWeek, 0, 7); - if (daysOfMonth === undefined || daysOfWeek === undefined) { - return false; - } - - // `cron` ignores a day field that covers every day (like `1-31` or `sun-sat`) and runs on either day field - // otherwise. Sentry reads full ranges as they are and needs both day fields when one starts with `*` (like `*/2`). - const allDaysOfMonth = daysOfMonth === 31; - const allDaysOfWeek = daysOfWeek === 7; - const cronRunsOnEither = !allDaysOfMonth && !allDaysOfWeek; - const sentryRunsOnEither = !dayOfMonth.startsWith('*') && !dayOfWeek.startsWith('*'); - return (allDaysOfMonth && allDaysOfWeek) || cronRunsOnEither === sentryRunsOnEither; -} - -const DAY_NAMES: Record = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }; - -/** - * How many days a day field matches, expanded the way `cron` does it, or `undefined` if `cron` can't parse it. - * Day of week `7` is Sunday, like `0`. - */ -function countCronValues(field: string, low: number, high: number): number | undefined { - let unknownName = false; - const numericField = field.replace(/[a-z]{1,3}/gi, name => { - const value = DAY_NAMES[name.toLowerCase()]; - unknownName ||= value === undefined; - return String(value); - }); - if (unknownName) { return undefined; } - const values = new Set(); - for (const part of numericField.split(',')) { - const match = part.match(/^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/); - if (!match) { - return undefined; - } - const [, wildcard, from, to, step] = match; - const lower = wildcard ? low : Number(from); - const upper = wildcard || (step && !to) ? high : Number(to ?? from); - const increment = Number(step ?? 1); - if (!increment || lower < low || upper > high || lower > upper) { - return undefined; - } - for (let value = lower; value <= upper; value += increment) { - values.add(high === 7 && value === 7 ? 0 : value); - } - } - return values.size; -} - -/** - * The canonical IANA name of the time zone, or `undefined` if Sentry won't accept it (like `UTC+3`). - */ -function toSentryTimeZone(timezone: string | undefined): string | undefined { - if (!timezone || timezone === 'Etc/Unknown' || /^(?:utc|gmt)?[+-]/i.test(timezone)) { - return undefined; - } - try { - return new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone || undefined; - } catch { - return undefined; - } -} - -function getLocalTimeZone(): string | undefined { - try { - return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined; - } catch { - return undefined; - } + return cronExpressionToMonitorConfig(cronTime, timeZone, 'cron'); } /** diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 47bc07d14ab4..66f75a616a28 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -310,7 +310,7 @@ describe('SentryCron decorator with @Cron', () => { locales?: string | string[], options?: Intl.DateTimeFormatOptions, ) { - return new DateTimeFormat(locales, { timeZone: 'Asia/Tokyo', ...options }); + return new DateTimeFormat(locales, { ...options, timeZone: options?.timeZone ?? 'Asia/Tokyo' }); } as typeof Intl.DateTimeFormat); }); @@ -382,22 +382,13 @@ describe('SentryCron decorator with @Cron', () => { ['a numeric month range', Cron('0 9 1 1-6 *')], ['a numeric month list', Cron('0 9 1 1,7 *')], ['a numeric month with a step', Cron('0 9 1 2/3 *')], + ['a numeric month with seconds', Cron('0 0 9 1 5 *')], // `0 0 1 0 *` in `@nestjs/schedule` 3 ['CronExpression.EVERY_YEAR', Cron('0 0 1 1 *')], - ['a day-of-month step with a day of week', Cron('0 9 */2 * MON')], - ['a full day-of-month range with a day of week', Cron('0 9 1-31 * MON')], - ['a full day-of-week range with a day of month', Cron('0 9 1 * 0-6')], - ['a full 1-7 day-of-week range with a day of month', Cron('0 9 15 * 1-7')], ['a full day-of-week name range with a day of month', Cron('0 9 1 * sun-sat')], - ['a full upper-case day-of-week name range with a day of month', Cron('0 9 1 * SUN-SAT')], - ['a full mon-sun day-of-week range with a day of month', Cron('0 9 1 * mon-sun')], - ['a full day-of-week list with a day of month', Cron('0 9 1 * 0,1,2,3,4,5,6')], - ['a full day-of-month range with a step of 1 and a day of week', Cron('0 9 1-31/1 * MON')], ['an unknown day name', Cron('0 9 1 * sunday')], - ['an out-of-range day of month', Cron('0 9 32 * *')], ['a numeric month from @nestjs/schedule 3', VersionedCron('0 9 1 5 *', '3.0.4')], ['a fixed-offset time zone', Cron('0 * * * *', { timeZone: 'UTC+3' })], - ['an unknown time zone', Cron('0 * * * *', { timeZone: 'Mars/Olympus' })], ])('sends no monitor config for %s', async (_, cronDecorator) => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); const service = decorate(SentryCron('my-job'), cronDecorator); @@ -407,17 +398,17 @@ describe('SentryCron decorator with @Cron', () => { }); it.each([ - ['a month name', '0 9 1 MAY *'], - ['both day fields', '0 9 1-7 * MON'], - ['a day-of-week name list with a day of month', '0 9 1 * mon,fri'], - ['a full day-of-month range with a day-of-week step', '0 9 1-31 * */2'], - ['a day-of-month step of 1 with a day of week', '0 9 */1 * MON'], - ['both day fields covering every day', '0 9 1-31 * sun-sat'], - ['CronExpression.EVERY_QUARTER', '0 0 1 */3 *'], - ['CronExpression.EVERY_6_MONTHS', '0 0 1 */6 *'], - ])('sends a crontab with %s', async (_, crontab) => { + ['a month name', '0 9 1 MAY *', '0 9 1 5 *'], + ['a day-of-week name list with a day of month', '0 9 1 * mon,fri', '0 9 1 * 1,5'], + ['both day fields covering every day', '0 9 1-31 * sun-sat', '0 9 1-31 * 0-6'], + ['a day-of-month range of 29 days with a day of week', '0 9 1-29 * 1', '0 9 1-29 * 1'], + ['a day-of-month range of 30 days with a day of week', '0 9 2-31 * 1', '0 9 2-31 * 1'], + ['a day-of-month list of 30 days with a day of week', '0 9 1,3-31 * 1', '0 9 1,3-31 * 1'], + ['CronExpression.EVERY_QUARTER', '0 0 1 */3 *', '0 0 1 */3 *'], + ['a preset', '@WEEKLY', '0 0 * * 0'], + ])('sends a crontab with %s', async (_, cronTime, crontab) => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); - const service = decorate(SentryCron('my-job'), Cron(crontab)); + const service = decorate(SentryCron('my-job'), Cron(cronTime)); await service.job(); expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { @@ -452,24 +443,6 @@ describe('SentryCron decorator with @Cron', () => { expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), undefined); }); - it.each([ - ['@hourly', '@hourly'], - ['@daily', '@daily'], - ['@WEEKLY', '@weekly'], - ['@monthly', '@monthly'], - ['@yearly', '@yearly'], - ['@weekdays', '0 0 * * 1-5'], - ])('sends the preset %s as %s', async (preset, value) => { - const withMonitorSpy = vi.spyOn(core, 'withMonitor'); - const service = decorate(SentryCron('my-job'), Cron(preset)); - - await service.job(); - expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { - schedule: { type: 'crontab', value }, - timezone: 'Asia/Tokyo', - }); - }); - it('warns when monitor settings are passed but no schedule can be derived', async () => { const warnSpy = vi.spyOn(core.debug, 'warn').mockImplementation(() => undefined); const withMonitorSpy = vi.spyOn(core, 'withMonitor').mockImplementation((_, callback) => callback()); @@ -531,6 +504,21 @@ describe('SentryCron decorator with @Cron', () => { }); }); + it.each([undefined, 1, 5])( + 'sends only the checkinMargin passed for a dropped seconds value, given %s', + async checkinMargin => { + const withMonitorSpy = vi.spyOn(core, 'withMonitor'); + const service = decorate(SentryCron('my-job', { checkinMargin }), Cron('59 0 9 * * *')); + + await service.job(); + expect(withMonitorSpy).toHaveBeenCalledWith('my-job', expect.any(Function), { + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'Asia/Tokyo', + checkinMargin, + }); + }, + ); + it('uses an explicit monitor config as is', async () => { const withMonitorSpy = vi.spyOn(core, 'withMonitor'); const monitorConfig: core.MonitorConfig = { schedule: { type: 'interval', value: 1, unit: 'hour' } }; diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index c2f2cb088859..be0097ab7142 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -1,51 +1,27 @@ -const replacements: [string, string][] = [ - ['january', '1'], - ['february', '2'], - ['march', '3'], - ['april', '4'], - ['may', '5'], - ['june', '6'], - ['july', '7'], - ['august', '8'], - ['september', '9'], - ['october', '10'], - ['november', '11'], - ['december', '12'], - ['jan', '1'], - ['feb', '2'], - ['mar', '3'], - ['apr', '4'], - ['may', '5'], - ['jun', '6'], - ['jul', '7'], - ['aug', '8'], - ['sep', '9'], - ['oct', '10'], - ['nov', '11'], - ['dec', '12'], - ['sunday', '0'], - ['monday', '1'], - ['tuesday', '2'], - ['wednesday', '3'], - ['thursday', '4'], - ['friday', '5'], - ['saturday', '6'], - ['sun', '0'], - ['mon', '1'], - ['tue', '2'], - ['wed', '3'], - ['thu', '4'], - ['fri', '5'], - ['sat', '6'], -]; +import type { MonitorConfig } from '@sentry/core'; +import { debug } from '@sentry/core'; +import type { _INTERNAL_CronDialect as CronDialect } from '@sentry/server-utils'; +import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils'; +import { DEBUG_BUILD } from '../debug-build'; /** - * Replaces names in cron expressions + * The monitor config for a cron expression, or `undefined` if Sentry would read the expression differently than the + * scheduler runs it. */ -export function replaceCronNames(cronExpression: string): string { - return replacements.reduce( - // oxlint-disable-next-line sdk/no-regexp-constructor - (acc, [name, replacement]) => acc.replace(new RegExp(name, 'gi'), replacement), - cronExpression, - ); +export function getCronMonitorConfig( + expression: string, + timezone: unknown, + dialect: CronDialect, + isReadAlike: (expression: string) => boolean = () => true, +): MonitorConfig | undefined { + const monitorConfig = isReadAlike(expression) + ? cronExpressionToMonitorConfig(expression, timezone, dialect) + : undefined; + if (!monitorConfig) { + DEBUG_BUILD && + debug.warn( + `[Cron] Can't convert "${expression}" to a Sentry schedule, sending check-ins without a monitor config.`, + ); + } + return monitorConfig; } diff --git a/packages/node/src/cron/cron.ts b/packages/node/src/cron/cron.ts index dd3edf1c95b5..529d47b0aed0 100644 --- a/packages/node/src/cron/cron.ts +++ b/packages/node/src/cron/cron.ts @@ -1,5 +1,5 @@ import { addNonEnumerableProperty, captureException, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { getCronMonitorConfig } from './common'; export type CronJobParams = { cronTime: string | Date; @@ -94,7 +94,8 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const cronString = replaceCronNames(cronTime); + const utcOffset = args[7]; + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; async function monitoredTick(context: unknown, onComplete?: unknown): Promise { return withMonitor( @@ -112,10 +113,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri throw e; } }, - { - schedule: { type: 'crontab', value: cronString }, - timezone: timeZone || undefined, - }, + monitorConfig, ); } @@ -127,7 +125,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri get(target, prop: keyof CronJobConstructor) { if (prop === 'from') { return (param: CronJobParams) => { - const { cronTime, onTick, timeZone } = param; + const { cronTime, onTick, timeZone, utcOffset } = param; if (typeof cronTime !== 'string') { throw new Error(ERROR_TEXT); @@ -139,7 +137,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const cronString = replaceCronNames(cronTime); + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; param.onTick = async (context: unknown, onComplete?: unknown) => { return withMonitor( @@ -157,10 +155,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri throw e; } }, - { - schedule: { type: 'crontab', value: cronString }, - timezone: timeZone || undefined, - }, + monitorConfig, ); }; diff --git a/packages/node/src/cron/index.ts b/packages/node/src/cron/index.ts index 890d88441ec1..56144101264c 100644 --- a/packages/node/src/cron/index.ts +++ b/packages/node/src/cron/index.ts @@ -6,6 +6,7 @@ import { instrumentNodeSchedule } from './node-schedule'; export const cron = { // oxlint-disable-next-line typescript/no-deprecated instrumentCron, + // oxlint-disable-next-line typescript/no-deprecated instrumentNodeCron, instrumentNodeSchedule, }; diff --git a/packages/node/src/cron/node-cron.ts b/packages/node/src/cron/node-cron.ts index ab3d935c1a89..f56b61b144cc 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -1,5 +1,12 @@ -import { addNonEnumerableProperty, captureException, type MonitorConfig, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { + addNonEnumerableProperty, + captureException, + type MonitorConfig, + startNewTrace, + withMonitor, +} from '@sentry/core'; +import { _INTERNAL_isReadAlikeByNodeCron3 as isReadAlikeByNodeCron3 } from '@sentry/server-utils'; +import { getCronMonitorConfig } from './common'; export interface NodeCronOptions { name: string; @@ -31,6 +38,11 @@ export interface NodeCron { * { name: "my-cron-job" }, * ); * ``` + * + * On node-cron 4, steps on `*` in the day-of-month or month field (such as every second day) aren't sent as a + * schedule, because this wrapper can't tell the node-cron version. `nodeCronIntegration` can. + * + * @deprecated Use `nodeCronIntegration` instead. */ export function instrumentNodeCron( lib: Partial & T, @@ -51,31 +63,36 @@ export function instrumentNodeCron( throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); } + // The node-cron version is unknown here, so check for node-cron 3 quirks, which include those before 4.6. + const cronConfig = getCronMonitorConfig(expression, timezone, 'node-cron', isReadAlikeByNodeCron3); + const upsertMonitorConfig = cronConfig && { ...cronConfig, ...monitorConfig }; + const monitoredCallback = async (...args: Parameters): Promise => { - return withMonitor( - name, - async () => { - // We have to manually catch here and capture the exception because node-cron swallows errors - // https://github.com/node-cron/node-cron/issues/399 - try { - // oxlint-disable-next-line typescript/await-thenable, typescript/return-await -- callback may be async at runtime; awaiting inside the try lets us capture its rejection - return await callback(...args); - } catch (e) { - captureException(e, { - mechanism: { - handled: false, - type: 'auto.function.node-cron.instrumentNodeCron', - }, - }); - throw e; - } - }, - { - schedule: { type: 'crontab', value: replaceCronNames(expression) }, - timezone, - ...monitorConfig, - }, - ); + const runWithMonitor = (): Promise => + withMonitor( + name, + async () => { + // We have to manually catch here and capture the exception because node-cron swallows errors + // https://github.com/node-cron/node-cron/issues/399 + try { + // oxlint-disable-next-line typescript/await-thenable, typescript/return-await -- callback may be async at runtime; awaiting inside the try lets us capture its rejection + return await callback(...args); + } catch (e) { + captureException(e, { + mechanism: { + handled: false, + type: 'auto.function.node-cron.instrumentNodeCron', + }, + }); + throw e; + } + }, + upsertMonitorConfig, + ); + // `withMonitor` reads `isolateTrace` from the monitor config, which is not sent without a schedule. + return !upsertMonitorConfig && monitorConfig.isolateTrace + ? startNewTrace(runWithMonitor) + : runWithMonitor(); }; // Tells `nodeCronIntegration` that this task is already monitored. diff --git a/packages/node/src/cron/node-schedule.ts b/packages/node/src/cron/node-schedule.ts index 548f60ac48f8..7920350a5a34 100644 --- a/packages/node/src/cron/node-schedule.ts +++ b/packages/node/src/cron/node-schedule.ts @@ -1,5 +1,5 @@ import { addNonEnumerableProperty, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { getCronMonitorConfig } from './common'; export interface NodeSchedule { scheduleJob( @@ -44,6 +44,7 @@ export function instrumentNodeSchedule(lib: T & NodeSchedule): T { const monitorSlug = nameOrExpression; const expression = expressionOrCallback; + const monitorConfig = getCronMonitorConfig(expression, undefined, 'cron-parser'); async function monitoredCallback(): Promise { return withMonitor( @@ -52,9 +53,7 @@ export function instrumentNodeSchedule(lib: T & NodeSchedule): T { // oxlint-disable-next-line typescript/await-thenable -- callback may be async at runtime await callback?.(); }, - { - schedule: { type: 'crontab', value: replaceCronNames(expression) }, - }, + monitorConfig, ); } diff --git a/packages/node/test/cron.test.ts b/packages/node/test/cron.test.ts index f5178dc98e88..a0027520cef7 100644 --- a/packages/node/test/cron.test.ts +++ b/packages/node/test/cron.test.ts @@ -4,6 +4,8 @@ import { cron } from '../src'; import type { CronJob, CronJobParams } from '../src/cron/cron'; import type { NodeCron, NodeCronOptions } from '../src/cron/node-cron'; +const localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + describe('cron check-ins', () => { let withMonitorSpy: MockInstance; @@ -82,12 +84,27 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }, }); })); + test('sends no monitor config with a utc offset', () => + new Promise(done => { + const CronJobWithCheckIn = cron.instrumentCron(CronJobMock, 'my-cron-job'); + + CronJobWithCheckIn.from({ + cronTime: '* * * Jan,Sep Sun', + utcOffset: 60, + onTick: () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + }); + })); + test('throws with multiple jobs same name', () => { const CronJobWithCheckIn = cron.instrumentCron(CronJobMock, 'my-cron-job'); @@ -131,6 +148,7 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }, @@ -138,6 +156,61 @@ describe('cron check-ins', () => { ); })); + test('sends no monitor config for a schedule Sentry would read differently', () => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron).schedule( + '*/10 * * * * *', + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + { name: 'my-cron-job' }, + ); + })); + + test.each(['0 9 * * 5-0', '0 9 * * sat-sun', '0 9 * * 1-7', '0 9 */2 * 1'])( + 'sends no monitor config for %s, which node-cron before 4.6 reads differently', + expression => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron).schedule( + expression, + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), undefined); + done(); + }, + { name: 'my-cron-job' }, + ); + }), + ); + + test('keeps isolateTrace in the monitor config', () => + new Promise(done => { + const nodeCron: NodeCron = { + schedule: (_expression: string, callback: () => void): unknown => callback(), + }; + + cron.instrumentNodeCron(nodeCron, { isolateTrace: true }).schedule( + '0 9 * * *', + () => { + expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'Europe/Vienna', + isolateTrace: true, + }); + done(); + }, + { name: 'my-cron-job', timezone: 'Europe/Vienna' }, + ); + })); + test('throws without supplied name', () => { const nodeCron: NodeCron = { schedule: (): unknown => { @@ -180,6 +253,7 @@ describe('cron check-ins', () => { expect(withMonitorSpy).toHaveBeenCalledTimes(1); expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), { schedule: { type: 'crontab', value: '* * * 1,9 0' }, + timezone: localTimezone, }); done(); }); diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 77c1fd37c2ea..2554c49e3901 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -40,10 +40,15 @@ export { dataloaderIntegration } from './integrations/dataloader'; export { genericPoolIntegration } from './integrations/generic-pool'; export { cronJobIntegration } from './integrations/cron'; export type { CronJobIntegrationOptions } from './integrations/cron'; -export { nodeCronIntegration } from './integrations/node-cron'; +export { + isReadAlikeByNodeCron3 as _INTERNAL_isReadAlikeByNodeCron3, + nodeCronIntegration, +} from './integrations/node-cron'; export type { NodeCronIntegrationOptions } from './integrations/node-cron'; export { nodeScheduleIntegration } from './integrations/node-schedule'; export type { NodeScheduleIntegrationOptions } from './integrations/node-schedule'; +export { cronExpressionToMonitorConfig as _INTERNAL_cronExpressionToMonitorConfig } from './utils/cronMonitoring'; +export type { CronDialect as _INTERNAL_CronDialect } from './utils/cronMonitoring'; export { googleGenAIIntegration } from './integrations/google-genai'; export { graphqlIntegration } from './integrations/graphql'; export { hapiIntegration } from './integrations/hapi'; diff --git a/packages/server-utils/src/integrations/cron.ts b/packages/server-utils/src/integrations/cron.ts index 8a08c2fede4f..acea96ffd948 100644 --- a/packages/server-utils/src/integrations/cron.ts +++ b/packages/server-utils/src/integrations/cron.ts @@ -52,7 +52,9 @@ export function onSetTime({ arguments: [cronTime], self }: ScheduleChange): void } const { source, timeZone, utcOffset } = cronTime as { source?: unknown; timeZone?: unknown; utcOffset?: unknown }; const monitorConfig: MonitorConfig | undefined = - typeof source === 'string' && utcOffset == null ? cronExpressionToMonitorConfig(source, timeZone, 'or') : undefined; + typeof source === 'string' && utcOffset == null + ? cronExpressionToMonitorConfig(source, timeZone, 'cron') + : undefined; for (const callback of job._callbacks || []) { updateMonitorConfig(callback, monitorConfig); } @@ -66,6 +68,6 @@ function wrapJob(args: unknown[], options: CronJobIntegrationOptions): void { if (typeof cronTime !== 'string' || !shouldMonitorJob(name, onTick, options.excludeJobs)) { return; } - const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, 'or') : undefined; + const monitorConfig = utcOffset == null ? cronExpressionToMonitorConfig(cronTime, timeZone, 'cron') : undefined; args[1] = wrapScheduledJob(onTick as AnyFn, name, monitorConfig, 'auto.function.cron'); } diff --git a/packages/server-utils/src/integrations/node-cron.ts b/packages/server-utils/src/integrations/node-cron.ts index 330870117aca..aef5095b1e5f 100644 --- a/packages/server-utils/src/integrations/node-cron.ts +++ b/packages/server-utils/src/integrations/node-cron.ts @@ -70,18 +70,22 @@ export function getMonitorConfig( ): MonitorConfig | undefined { return isReadAlike && !isReadAlike(expression) ? undefined - : cronExpressionToMonitorConfig(expression, timezone, 'and'); + : cronExpressionToMonitorConfig(expression, timezone, 'node-cron'); } const NODE_CRON_3_FIELD_MINIMUMS = [0, 0, 1, 1, 0]; /** * node-cron before 4.6 reads `7` as `0` and swaps reversed ranges, so it runs `sat-sun`, `6-0` and `6-7` every day. - * Returns `false` for weekday ranges that could hit that. + * It also reads a step without a range, like `5/10`, as its start. Returns `false` where that could differ. */ export function isReadAlikeByNodeCron4(expression: string): boolean { - const weekday = expression.trim().split(/\s+/).pop() || ''; - return !(weekday.includes('-') && (weekday.includes('7') || /-(?:0|sun)/i.test(weekday))); + const fields = expression.trim().split(/\s+/); + const weekday = fields[fields.length - 1] || ''; + return ( + !(weekday.includes('-') && (weekday.includes('7') || /-(?:0|sun)/i.test(weekday))) && + !fields.some(field => field.split(',').some(part => /^[a-z\d]+\//i.test(part))) + ); } /** diff --git a/packages/server-utils/src/integrations/node-schedule.ts b/packages/server-utils/src/integrations/node-schedule.ts index 426c362d0021..d3f1b92d29ca 100644 --- a/packages/server-utils/src/integrations/node-schedule.ts +++ b/packages/server-utils/src/integrations/node-schedule.ts @@ -105,8 +105,10 @@ function isCronShaped(value: string): boolean { // Only cron strings convert; recurrence rules and rules limited by `start` or `end` don't. export function getMonitorConfig(spec: unknown): MonitorConfig | undefined { if (typeof spec === 'string') { - return cronExpressionToMonitorConfig(spec, undefined, 'or'); + return cronExpressionToMonitorConfig(spec, undefined, 'cron-parser'); } const { rule, tz, start, end } = (spec || {}) as { rule?: unknown; tz?: unknown; start?: unknown; end?: unknown }; - return typeof rule === 'string' && !start && !end ? cronExpressionToMonitorConfig(rule, tz, 'or') : undefined; + return typeof rule === 'string' && !start && !end + ? cronExpressionToMonitorConfig(rule, tz, 'cron-parser') + : undefined; } diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index 117e37c513ef..e595fc010920 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -81,28 +81,41 @@ export function shouldMonitorJob( ); } -const NICKNAMES: Record = { +/** + * The library that parses a scheduler's cron expressions: `node-cron`, `cron` (also behind `@nestjs/schedule`), or + * `cron-parser` 4 or 5 (behind `node-schedule` and BullMQ). + */ +export type CronDialect = 'node-cron' | 'cron' | 'cron-parser'; + +const COMMON_NICKNAMES: Record = { '@yearly': '0 0 1 1 *', - '@annually': '0 0 1 1 *', '@monthly': '0 0 1 * *', '@weekly': '0 0 * * 0', '@daily': '0 0 * * *', - '@midnight': '0 0 * * *', '@hourly': '0 * * * *', - '@minutely': '* * * * *', - '@weekdays': '0 0 * * 1-5', - '@weekends': '0 0 * * 0,6', }; -const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; -const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; +const NICKNAMES: Record> = { + 'node-cron': { ...COMMON_NICKNAMES, '@annually': '0 0 1 1 *', '@midnight': '0 0 * * *' }, + cron: { ...COMMON_NICKNAMES, '@minutely': '* * * * *', '@weekdays': '0 0 * * 1-5', '@weekends': '0 0 * * 0,6' }, + 'cron-parser': COMMON_NICKNAMES, +}; -/** - * How a scheduler combines a restricted day-of-month and day-of-week: - * - `and`: both must match (`node-cron`). - * - `or`: either matches, unless one is `*` or a full range (`cron-parser`, `cron`). - */ -export type DayFieldSemantics = 'and' | 'or'; +const MONTHS = [ + 'january', + 'february', + 'march', + 'april', + 'may', + 'june', + 'july', + 'august', + 'september', + 'october', + 'november', + 'december', +]; +const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; /** * The Sentry monitor config for a cron expression, or `undefined` if Sentry would read it differently. @@ -111,27 +124,34 @@ export type DayFieldSemantics = 'and' | 'or'; export function cronExpressionToMonitorConfig( expression: string, timezone: unknown, - daySemantics: DayFieldSemantics, + dialect: CronDialect, ): MonitorConfig | undefined { const trimmed = expression.trim(); - const fields = (NICKNAMES[trimmed.toLowerCase()] || trimmed).split(/\s+/); + const fields = (NICKNAMES[dialect][trimmed.toLowerCase()] || trimmed).split(/\s+/); // Sentry schedules have minute granularity, so only a fixed second can be dropped. if (fields.length === 6 && /^\d+$/.test(fields[0] as string)) { fields.shift(); } - if (fields.length !== 5 || !fields.every(field => /^[\d*,/a-z-]+$/i.test(field))) { - return undefined; - } - - const [minute, hour, dayOfMonth, month, dayOfWeekWithNames] = fields as [string, string, string, string, string]; - const dayOfWeek = replaceNames(dayOfWeekWithNames, WEEKDAYS, 0); - if (!isSameDayMatching(dayOfMonth, dayOfWeek, daySemantics)) { + if (fields.length !== 5 || !fields.every(field => /^[\d*,/a-z#-]+$/i.test(field))) { return undefined; } - const crontab = [minute, hour, dayOfMonth, replaceNames(month, MONTHS, 1), endRangesOnSundayAsSeven(dayOfWeek)]; - if (crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field))) { + const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]; + const monthNumbers = replaceNames(month, MONTHS, 1, dialect); + const weekdayNames = replaceNames(dayOfWeek, WEEKDAYS, 0, dialect); + const weekdayNumbers = dialect === 'node-cron' ? endRangesOnSundayAsSeven(weekdayNames) : weekdayNames; + const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers]; + if ( + crontab.some( + (field, index) => + hasUnsupportedCharacter(field, dialect === 'cron-parser' ? CRON_PARSER_DAY_TOKENS[index] : undefined) || + hasReversedRange(field) || + hasSteppedSingleValueRange(field), + ) || + !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) || + !hasDayInSelectedMonths(dayOfMonth, monthNumbers) + ) { return undefined; } @@ -143,54 +163,129 @@ export function cronExpressionToMonitorConfig( return { schedule: { type: 'crontab', value: crontab.join(' ') }, timezone: sentryTimezone }; } -// Sentry requires both day fields to match when one starts with `*`, and either otherwise. -function isSameDayMatching(dayOfMonth: string, dayOfWeek: string, daySemantics: DayFieldSemantics): boolean { - if (dayOfMonth === '*' || dayOfWeek === '*') { +// `cron-parser` reads these like Sentry: `L` is the last day of the month, `5L` the last Friday, `5#2` the second Friday. +const CRON_PARSER_DAY_TOKENS = [undefined, undefined, /^L$/, undefined, /^[0-7](?:L|#[1-5])$/]; + +function hasUnsupportedCharacter(field: string, dayToken: RegExp | undefined): boolean { + return field.split(',').some(part => /[a-z#]/i.test(part) && !dayToken?.test(part)); +} + +// Sentry needs both day fields to match when one starts with `*`, and either otherwise. +function isSameDayMatching(dayOfMonth: string, dayOfWeek: string, dialect: CronDialect): boolean { + const monthDays = parseDayField(dayOfMonth, 1, 31); + const weekdays = parseDayField(dayOfWeek, 0, 7); + if (!monthDays || !weekdays) { + return false; + } + const sentryNeedsBoth = dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*'); + if (dialect === 'cron-parser') { + return isSameDayMatchingInCronParser(dayOfMonth, dayOfWeek, monthDays, weekdays, sentryNeedsBoth); + } + // `cron` needs either day field to match, but ignores one that lists every day, like `1-31` or `sun-sat`. + const allMonthDays = monthDays.days === 31; + const allWeekdays = weekdays.days === 7; + const schedulerNeedsBoth = dialect === 'node-cron' || allMonthDays || allWeekdays; + return (allMonthDays && allWeekdays) || schedulerNeedsBoth === sentryNeedsBoth; +} + +// `cron-parser` ignores a day-of-week with 8 values, and a day-of-month with at least as many values as the month has +// days (29 in February), duplicates included. Then only the other field has to match, and otherwise either. +function isSameDayMatchingInCronParser( + dayOfMonth: string, + dayOfWeek: string, + monthDays: DayField, + weekdays: DayField, + sentryNeedsBoth: boolean, +): boolean { + // `cron-parser` 4 ignores a restricted day of month when the day of week has a `#`. + if (weekdays.cronParserAddsSunday || (dayOfWeek.includes('#') && (dayOfMonth !== '*' || dayOfWeek.includes(',')))) { + return false; + } + if (dayOfWeek === '*') { return true; } - if (daySemantics === 'and') { - return dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*'); + if (dayOfMonth === '*') { + return weekdays.cronParserValues !== 8 || weekdays.days === 7; } - // `cron` reads a field that lists every day like `*`. `cron-parser` does so for a day-of-month that lists every day - // of the current month, and February has 29 there. - return !( - dayOfMonth.startsWith('*') || - dayOfWeek.startsWith('*') || - countValues(dayOfMonth, 1, 31) >= 29 || - countValues(dayOfWeek, 0, 7, day => day % 7) === 7 - ); + return !sentryNeedsBoth && monthDays.cronParserValues < 29 && weekdays.cronParserValues !== 8; } -function countValues(field: string, min: number, max: number, normalize = (value: number): number => value): number { - const values = new Set(); +const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +// Sentry rejects a day of month that none of the months have, like `31` in `0 9 31 2,4 *`. The schedulers run these on +// the day of week or not at all. +function hasDayInSelectedMonths(dayOfMonth: string, month: string): boolean { + const days = parseDayField(dayOfMonth, 1, 31)?.values; + const months = parseDayField(month, 1, 12)?.values; + if (!days || !months) { + return false; + } + return !days.size || Math.min(...days) <= Math.max(...[...months].map(m => DAYS_IN_MONTH[m - 1] as number)); +} + +interface DayField { + values: Set; + days: number; + cronParserValues: number; + cronParserAddsSunday: boolean; +} + +function parseDayField(field: string, low: number, high: number): DayField | undefined { + const days = new Set(); + let cronParserValues = 0; + let cronParserListsSunday = false; for (const part of field.split(',')) { - const match = /^(?:\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part); - if (!match) { + // `L`, `5L` and `5#2` stand for one day each. Only the `cron-parser` dialect lets them through. + if (/^(?:L|[0-7](?:L|#[1-5]))$/.test(part)) { + cronParserValues++; continue; } - const [, start, end, step] = match; - const first = start === undefined ? min : Number(start); - const last = Math.min( - end !== undefined ? Number(end) : start !== undefined && step === undefined ? first : max, - max, - ); - for (let value = first; value <= last; value += Number(step) || 1) { - values.add(normalize(value)); + const match = /^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part); + if (!match) { + return undefined; + } + const [, wildcard, from, to, step] = match; + const lower = wildcard ? low : Number(from); + const upper = wildcard || (step && !to) ? high : Number(to ?? from); + const increment = Number(step ?? 1); + if (!increment || lower < low || upper > high || lower > upper) { + return undefined; + } + // `cron-parser` starts a weekday range that ends on 7 with a Sunday, whatever the step. + if (high === 7 && upper === 7 && lower !== 0 && (to || step)) { + cronParserValues++; + cronParserListsSunday = true; + } + for (let day = lower; day <= upper; day += increment) { + days.add(high === 7 && day === 7 ? 0 : day); + cronParserValues++; } } - return values.size; + return { + values: days, + days: days.size, + cronParserValues, + cronParserAddsSunday: cronParserListsSunday && !days.has(0), + }; } -function replaceNames(field: string, names: string[], offset: number): string { +function replaceNames(field: string, names: string[], offset: number, dialect: CronDialect): string { return field.replace(/[a-z]+/gi, word => { - const index = names.indexOf(word.slice(0, 3).toLowerCase()); + const lowerCase = word.toLowerCase(); + const index = names.findIndex( + name => lowerCase === name.slice(0, 3) || (dialect === 'node-cron' && lowerCase === name), + ); return index === -1 ? word : String(index + offset); }); } -// `sat-sun` is `6-0`, which node-cron 4.6+ runs on Saturday and Sunday. Sentry only accepts it as `6-7`. +// `sat-sun` is `6-0`, which node-cron 4.6+ runs on Saturday and Sunday. Sentry only accepts it as `6-7`. The other +// schedulers reject it. function endRangesOnSundayAsSeven(field: string): string { - return field.replace(/(\d+)-0(?!\d)/g, (range, start: string) => (Number(start) ? `${start}-7` : range)); + return field + .split(',') + .map(part => part.replace(/^(\d+)-0(?!\d)/, (range, start: string) => (Number(start) ? `${start}-7` : range))) + .join(','); } // node-cron 4.6+ wraps these around (`22-2` hours), earlier versions swap them, the other schedulers reject them, @@ -202,6 +297,14 @@ function hasReversedRange(field: string): boolean { }); } +// The schedulers run `13-13/3` only on the 13th, but Sentry reads it as `13/3`. +function hasSteppedSingleValueRange(field: string): boolean { + return field.split(',').some(part => { + const range = /^(\d+)-(\d+)\//.exec(part); + return !!range && Number(range[1]) === Number(range[2]); + }); +} + function toSentryTimezone(timezone: string | undefined): string | undefined { if (timezone && /^(?:utc|gmt)?[+-]/i.test(timezone)) { return undefined; diff --git a/packages/server-utils/test/integrations/cron.test.ts b/packages/server-utils/test/integrations/cron.test.ts index ec83e6882d98..f7518f35a20c 100644 --- a/packages/server-utils/test/integrations/cron.test.ts +++ b/packages/server-utils/test/integrations/cron.test.ts @@ -22,7 +22,7 @@ describe('onSetTime', () => { const onTick = wrapScheduledJob( () => {}, 'my-job', - cronExpressionToMonitorConfig('0 9 * * *', 'UTC', 'or'), + cronExpressionToMonitorConfig('0 9 * * *', 'UTC', 'cron'), 'auto.function.cron', ); return { cronTime: {} as unknown, _callbacks: [onTick], onTick }; diff --git a/packages/server-utils/test/integrations/node-cron.test.ts b/packages/server-utils/test/integrations/node-cron.test.ts index c3c78dc701f9..7451b66da135 100644 --- a/packages/server-utils/test/integrations/node-cron.test.ts +++ b/packages/server-utils/test/integrations/node-cron.test.ts @@ -34,12 +34,18 @@ describe('isReadAlikeByNodeCron4', () => { }, ); - it.each(['0 9 * * sat-sun', '0 9 * * 6-0', '0 9 * * 6-7', '0 9 * * 5-0/2', '0 9 * * 1-3,sat-sun'])( - 'is false for %s', - expression => { - expect(isReadAlikeByNodeCron4(expression)).toBe(false); - }, - ); + it.each([ + '0 9 * * sat-sun', + '0 9 * * 6-0', + '0 9 * * 6-7', + '0 9 * * 5-0/2', + '0 9 * * 1-3,sat-sun', + '5/15 * * * *', + '0 9 * * fri/2', + '0 9 1,10/5 * *', + ])('is false for %s', expression => { + expect(isReadAlikeByNodeCron4(expression)).toBe(false); + }); }); describe('getMonitorConfig', () => { diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index d21b12fa7fe4..cd901879de3a 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -4,7 +4,7 @@ import { cronExpressionToMonitorConfig, shouldMonitorJob, wrapScheduledJob } fro import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; const toMonitorConfig = (expression: string, timezone: unknown) => - cronExpressionToMonitorConfig(expression, timezone, 'and'); + cronExpressionToMonitorConfig(expression, timezone, 'node-cron'); describe('cronExpressionToMonitorConfig with node-cron day matching', () => { it.each([ @@ -15,7 +15,9 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { ['0 9 */2 * 1', '0 9 */2 * 1'], ['@daily', '0 0 * * *'], ['@Weekly', '0 0 * * 0'], - ['@weekdays', '0 0 * * 1-5'], + ['@annually', '0 0 1 1 *'], + ['@midnight', '0 0 * * *'], + ['0 9 * january,JULY MONDAY-friday', '0 9 * 1,7 1-5'], ['*/15 * * * *', '*/15 * * * *'], ['0 9 * * sun', '0 9 * * 0'], ['0 9 * * sat-sun', '0 9 * * 6-7'], @@ -25,6 +27,7 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { ['0 9 * * 5-0', '0 9 * * 5-7'], ['0 9 * * 5-0/2', '0 9 * * 5-7/2'], ['0 9 * * 1-3,sat-sun', '0 9 * * 1-3,6-7'], + ['0 9 1-31 * 0-7', '0 9 1-31 * 0-7'], ])('sends %s as %s', (expression, crontab) => { expect(toMonitorConfig(expression, 'Europe/Vienna')).toEqual({ schedule: { type: 'crontab', value: crontab }, @@ -45,7 +48,18 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { '0 9 * * tue-mon', '0 9 * * 7-2', '0 22-2 * * *', + '31 9 13-13/3 * *', + '5-5/2 9 * * *', + '0 9 * * 2-2/3', '0 9 * nov-feb *', + '0 9 32 * *', + '0 9 * * 8', + '@reboot', + '@secondly', + '@weekdays', + '0 9 * * sunx', + '0 9 * * su', + '0 9 * janx *', ])('sends no config for %s', expression => { expect(toMonitorConfig(expression, 'UTC')).toBeUndefined(); }); @@ -64,19 +78,25 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { }); }); -describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { +describe('cronExpressionToMonitorConfig with cron day matching', () => { it.each([ ['0 9 1,15 * mon', '0 9 1,15 * 1'], ['0 9 */2 * *', '0 9 */2 * *'], ['0 9 * * 1-5', '0 9 * * 1-5'], + ['0 9 1-7 * MON', '0 9 1-7 * 1'], + ['0 9 1-31 * */2', '0 9 1-31 * */2'], + ['0 9 */1 * MON', '0 9 */1 * 1'], + ['0 9 1-31 * sun-sat', '0 9 1-31 * 0-6'], ['0 9 15 * sun-fri', '0 9 15 * 0-5'], - ['0 9 15 * 1,2,3,4,5,6', '0 9 15 * 1,2,3,4,5,6'], ['0 9 1-28 * 1', '0 9 1-28 * 1'], - ['0 9 15 * 0', '0 9 15 * 0'], - ['0 9 15 * sun', '0 9 15 * 0'], - ['0 9 15 * 0,6', '0 9 15 * 0,6'], + ['0 9 1-29 * 1', '0 9 1-29 * 1'], + ['0 9 2-31 * 1', '0 9 2-31 * 1'], + ['0 9 1,3-31 * 1', '0 9 1,3-31 * 1'], + ['0 9 1-20,10-20 * 1', '0 9 1-20,10-20 * 1'], + ['0 0 1 */3 *', '0 0 1 */3 *'], + ['@weekdays', '0 0 * * 1-5'], ])('sends %s as %s', (expression, crontab) => { - expect(cronExpressionToMonitorConfig(expression, 'UTC', 'or')?.schedule).toEqual({ + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron')?.schedule).toEqual({ type: 'crontab', value: crontab, }); @@ -86,20 +106,135 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { '0 9 */2 * 1', '0 9 1 * */2', '0 9 1-31 * 1', - '0 9 1-30 * 1', - '0 9 1-15,16-29 * 1', + '0 9 1-31/1 * MON', '0 9 15 * 0-6', - '0 9 15 * 0-7', '0 9 15 * 1-7', '0 9 15 * sun-sat', - '0 9 15 * SUN-SAT', + '0 9 1 * mon-sun', + '0 9 * * sat-sun', + '0 9 * * mon-sun', + '0 9 * * 5-0', '0 9 15 * 0,1,2,3,4,5,6', - '0 9 15 * 1,2,3,4,5,6,7', - '0 9 15 * sun,mon,tue,wed,thu,fri,sat', '0 9 15 * 0-3,4-6', - '0 9 15 * 0-6/1', + '0 9 * * sunday', + '0 9 * * monday', + '0 9 * january *', + '0 9 15 * sunx', + '@annually', + '@midnight', + '0 9 L * *', + '0 9 * * 5L', + '0 9 * * 5#2', ])('sends no config for %s', expression => { - expect(cronExpressionToMonitorConfig(expression, 'UTC', 'or')).toBeUndefined(); + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron')).toBeUndefined(); + }); +}); + +describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { + it.each([ + ['0 9 1,15 * mon', '0 9 1,15 * 1'], + ['0 9 */2 * *', '0 9 */2 * *'], + ['0 9 * * 1-5', '0 9 * * 1-5'], + ['0 9 * * 2-6/2', '0 9 * * 2-6/2'], + ['0 9 1 * mon,fri', '0 9 1 * 1,5'], + ['0 9 15 * 0,6', '0 9 15 * 0,6'], + ['0 9 15 * 5-7', '0 9 15 * 5-7'], + ['0 9 15 * 0-6', '0 9 15 * 0-6'], + ['0 9 1-28 * 1', '0 9 1-28 * 1'], + ['0 9 1-30 * *', '0 9 1-30 * *'], + ['0 9 1-20,10-20 * *', '0 9 1-20,10-20 * *'], + ['@yearly', '0 0 1 1 *'], + ['0 9 L * *', '0 9 L * *'], + ['0 9 1,L * *', '0 9 1,L * *'], + ['0 9 L 2 *', '0 9 L 2 *'], + ['0 9 * * 5L', '0 9 * * 5L'], + ['0 9 * * 7L', '0 9 * * 7L'], + ['0 9 * * 1,5L', '0 9 * * 1,5L'], + ['0 9 * * 5#2', '0 9 * * 5#2'], + ['0 9 * * FRI#2', '0 9 * * 5#2'], + ['0 9 * 2 1#5', '0 9 * 2 1#5'], + ['0 9 15 * 5L', '0 9 15 * 5L'], + ['0 9 L * 1-5', '0 9 L * 1-5'], + ])('sends %s as %s', (expression, crontab) => { + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron-parser')?.schedule).toEqual({ + type: 'crontab', + value: crontab, + }); + }); + + it.each([ + '0 9 */2 * 1', + '0 9 */2 * sun-sat', + '0 9 */1 * MON', + '0 9 1 * */2', + '0 9 15 * *,7', + '0 9 1-31 * */2', + '0 9 1-31 * 1', + '0 9 1-29 * 1', + '0 9 1-15,16-29 * 1', + '0 9 1-20,10-20 * 1', + '0 9 15 * 1-7', + '0 9 15 * 0-7', + '0 9 1 * mon-sun', + '0 9 * * sat-sun', + '0 9 * * mon-sun', + '0 9 * * 5-0', + '0 9 * * 1-5,1-3', + '0 9 15 * 1-5,1-3', + '0 9 * * 2-7/2', + '0 9 * * 2/2', + '0 9 * * monday', + '0 9 * january *', + '@annually', + '@minutely', + '@weekdays', + '0 9 LW * *', + '0 9 15W * *', + '0 9 L/2 * *', + '0 9 l * *', + '0 9 * * L', + '0 9 * * FRIL', + '0 9 * * 5L-6', + '0 9 * * 5#6', + '0 9 * * 5#2,1', + '0 9 15 * 5#2', + '0 9 L * 1#1', + '0 9 1-29,L * 1', + '0 9 */2 * 5L', + '0 9 L * */2', + ])('sends no config for %s', expression => { + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron-parser')).toBeUndefined(); + }); +}); + +describe('cronExpressionToMonitorConfig with days the months lack', () => { + it.each(['node-cron', 'cron', 'cron-parser'] as const)('sends no config with %s', dialect => { + expect(cronExpressionToMonitorConfig('0 9 31 2,4 *', 'UTC', dialect)).toBeUndefined(); + expect(cronExpressionToMonitorConfig('0 9 30 2 1', 'UTC', dialect)).toBeUndefined(); + expect(cronExpressionToMonitorConfig('0 9 31 feb,apr *', 'UTC', dialect)).toBeUndefined(); + }); + + it.each(['node-cron', 'cron', 'cron-parser'] as const)( + 'sends a config if one of the months has the day, with %s', + dialect => { + expect(cronExpressionToMonitorConfig('0 9 31 2,3 *', 'UTC', dialect)?.schedule).toEqual({ + type: 'crontab', + value: '0 9 31 2,3 *', + }); + expect(cronExpressionToMonitorConfig('0 9 29 2 *', 'UTC', dialect)?.schedule).toEqual({ + type: 'crontab', + value: '0 9 29 2 *', + }); + }, + ); +}); + +describe('cronExpressionToMonitorConfig with a dropped seconds value', () => { + it.each(['node-cron', 'cron', 'cron-parser'] as const)('sends no checkinMargin with %s', dialect => { + expect(cronExpressionToMonitorConfig('59 0 9 * * *', 'UTC', dialect)).toEqual({ + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'UTC', + }); }); });