From d492b2f019e0470cb8be0940d4016c57c6a98519 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 29 Oct 2026 14:26:12 -0700 Subject: [PATCH 01/19] ref(server-utils): Share one cron converter across cron integrations @SentryCron, Sentry.cron.* and nodeCronIntegration each turned cron expressions into monitor configs on their own. They now all use cronExpressionToMonitorConfig from @sentry/server-utils, so they can't drift apart. --- .../suites/cron/cron/test.ts | 2 - .../suites/cron/node-cron/base/test.ts | 2 - .../suites/cron/node-schedule/test.ts | 2 - packages/nestjs/src/decorators.ts | 122 +----------------- packages/nestjs/test/decorators.test.ts | 50 ++----- packages/node/src/cron/common.ts | 67 +++------- packages/node/src/cron/cron.ts | 19 +-- packages/node/src/cron/node-cron.ts | 62 +++++---- packages/node/src/cron/node-schedule.ts | 7 +- packages/node/test/cron.test.ts | 55 ++++++++ packages/server-utils/src/index.ts | 2 + .../server-utils/src/utils/cronMonitoring.ts | 54 +++++--- .../test/utils/cronMonitoring.test.ts | 35 ++++- 13 files changed, 203 insertions(+), 276 deletions(-) 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..69652764b596 100644 --- a/dev-packages/node-integration-tests/suites/cron/cron/test.ts +++ b/dev-packages/node-integration-tests/suites/cron/cron/test.ts @@ -17,7 +17,6 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -47,7 +46,6 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', - monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } }, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), 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..96b4d3a92ffe 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 @@ -13,7 +13,6 @@ 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: '* * * * * *' } }, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -43,7 +42,6 @@ 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: '* * * * * *' } }, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), 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..b25f7eae51ef 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 @@ -13,7 +13,6 @@ 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: '* * * * * *' } }, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -43,7 +42,6 @@ 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: '* * * * * *' } }, 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 ead5d10338f0..6bc70e45cafe 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 { cronExpressionToMonitorConfig } from '@sentry/server-utils'; import { DEBUG_BUILD } from './debug-build'; import { isExpectedError } from './helpers'; import type { ReflectWithMetadata } from './integrations/helpers'; @@ -97,18 +98,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; @@ -149,118 +138,15 @@ 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, 'or'); } /** diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 47bc07d14ab4..fe5fec5adfa5 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); }); @@ -376,28 +376,17 @@ describe('SentryCron decorator with @Cron', () => { it.each([ ['a sub-minute schedule', Cron('*/5 * * * * *')], ['a one-off date', Cron(new Date())], - ['an unknown preset', Cron('@reboot')], ['a utc offset', Cron('0 * * * *', { utcOffset: 120 })], ['a numeric month', Cron('0 9 1 5 *')], ['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 +396,14 @@ 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'], + ['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 +438,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()); diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index c2f2cb088859..c83276ff1f39 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -1,51 +1,24 @@ -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 { DayFieldSemantics } from '@sentry/server-utils'; +import { 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, + daySemantics: DayFieldSemantics, +): MonitorConfig | undefined { + const monitorConfig = cronExpressionToMonitorConfig(expression, timezone, daySemantics); + 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 2c764c877c46..0f7a35ad3a26 100644 --- a/packages/node/src/cron/cron.ts +++ b/packages/node/src/cron/cron.ts @@ -1,5 +1,5 @@ import { captureException, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { getCronMonitorConfig } from './common'; export type CronJobParams = { cronTime: string | Date; @@ -90,7 +90,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, 'or') : undefined; async function monitoredTick(context: unknown, onComplete?: unknown): Promise { return withMonitor( @@ -108,10 +109,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri throw e; } }, - { - schedule: { type: 'crontab', value: cronString }, - timezone: timeZone || undefined, - }, + monitorConfig, ); } @@ -120,7 +118,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); @@ -132,7 +130,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const cronString = replaceCronNames(cronTime); + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'or') : undefined; param.onTick = async (context: unknown, onComplete?: unknown) => { return withMonitor( @@ -150,10 +148,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/node-cron.ts b/packages/node/src/cron/node-cron.ts index ab3d935c1a89..ebe6d5d610d4 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -1,5 +1,11 @@ -import { addNonEnumerableProperty, captureException, type MonitorConfig, withMonitor } from '@sentry/core'; -import { replaceCronNames } from './common'; +import { + addNonEnumerableProperty, + captureException, + type MonitorConfig, + startNewTrace, + withMonitor, +} from '@sentry/core'; +import { getCronMonitorConfig } from './common'; export interface NodeCronOptions { name: string; @@ -51,31 +57,35 @@ export function instrumentNodeCron( throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); } + const cronConfig = getCronMonitorConfig(expression, timezone, 'and'); + 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 f174ef7c904b..340de1955f47 100644 --- a/packages/node/src/cron/node-schedule.ts +++ b/packages/node/src/cron/node-schedule.ts @@ -1,5 +1,5 @@ import { 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, 'or'); 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 bf1e83d315e5..5bda33c9dd1d 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,42 @@ 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('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 +234,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 acb0ffb47c75..3c8e209ee739 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -40,6 +40,8 @@ export { dataloaderIntegration } from './integrations/dataloader'; export { genericPoolIntegration } from './integrations/generic-pool'; export { nodeCronIntegration } from './integrations/node-cron'; export type { NodeCronIntegrationOptions } from './integrations/node-cron'; +export { cronExpressionToMonitorConfig } from './utils/cronMonitoring'; +export type { DayFieldSemantics } 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/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index 975763d3c0a7..77afca1ad0d5 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -56,6 +56,9 @@ const NICKNAMES: Record = { '@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']; @@ -89,10 +92,6 @@ export function cronExpressionToMonitorConfig( } const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]; - if (!isSameDayMatching(dayOfMonth, dayOfWeek, daySemantics)) { - return undefined; - } - const crontab = [ minute, hour, @@ -100,7 +99,10 @@ export function cronExpressionToMonitorConfig( replaceNames(month, MONTHS, 1), endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0)), ]; - if (crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field))) { + if ( + crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field)) || + !isSameDayMatching(crontab[2] as string, crontab[4] as string, daySemantics) + ) { return undefined; } @@ -112,20 +114,40 @@ 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. +// Sentry requires both day fields to match when one starts with `*`, and either otherwise. The `or` schedulers +// ignore a day field that covers every day, like `1-31` or `sun-sat`, so they count the days as `cron` does. function isSameDayMatching(dayOfMonth: string, dayOfWeek: string, daySemantics: DayFieldSemantics): boolean { - if (dayOfMonth === '*' || dayOfWeek === '*') { - return true; + const daysOfMonth = countDays(dayOfMonth, 1, 31); + const daysOfWeek = countDays(dayOfWeek, 0, 7); + if (daysOfMonth === undefined || daysOfWeek === undefined) { + return false; } - if (daySemantics === 'and') { - return dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*'); + const allDaysOfMonth = daysOfMonth === 31; + const allDaysOfWeek = daysOfWeek === 7; + const schedulerNeedsBoth = daySemantics === 'and' || allDaysOfMonth || allDaysOfWeek; + const sentryNeedsBoth = dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*'); + return (allDaysOfMonth && allDaysOfWeek) || schedulerNeedsBoth === sentryNeedsBoth; +} + +function countDays(field: string, low: number, high: number): number | undefined { + const days = new Set(); + for (const part of field.split(',')) { + 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; + } + for (let day = lower; day <= upper; day += increment) { + days.add(high === 7 && day === 7 ? 0 : day); + } } - return !( - dayOfMonth.startsWith('*') || - dayOfWeek.startsWith('*') || - dayOfMonth === '1-31' || - ['0-6', '0-7', '1-7'].includes(dayOfWeek) - ); + return days.size; } function replaceNames(field: string, names: string[], offset: number): string { diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 0950a592cc87..c8fd1febf497 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -24,6 +24,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,6 +46,10 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { '0 9 * * 7-2', '0 22-2 * * *', '0 9 * nov-feb *', + '0 9 32 * *', + '0 9 * * 8', + '@reboot', + '@secondly', ])('sends no config for %s', expression => { expect(toMonitorConfig(expression, 'UTC')).toBeUndefined(); }); @@ -68,6 +73,16 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { ['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 * mon,fri', '0 9 1 * 1,5'], + ['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 0 1 */3 *', '0 0 1 */3 *'], + ['@yearly', '0 0 1 1 *'], + ['@minutely', '* * * * *'], + ['@weekdays', '0 0 * * 1-5'], + ['@weekends', '0 0 * * 0,6'], ])('sends %s as %s', (expression, crontab) => { expect(cronExpressionToMonitorConfig(expression, 'UTC', 'or')?.schedule).toEqual({ type: 'crontab', @@ -75,12 +90,20 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { }); }); - it.each(['0 9 */2 * 1', '0 9 1 * */2', '0 9 1-31 * 1', '0 9 15 * 0-6', '0 9 15 * 1-7'])( - 'sends no config for %s', - expression => { - expect(cronExpressionToMonitorConfig(expression, 'UTC', 'or')).toBeUndefined(); - }, - ); + it.each([ + '0 9 */2 * 1', + '0 9 1 * */2', + '0 9 1-31 * 1', + '0 9 15 * 0-6', + '0 9 15 * 1-7', + '0 9 1 * sun-sat', + '0 9 1 * SUN-SAT', + '0 9 1 * mon-sun', + '0 9 1 * 0,1,2,3,4,5,6', + '0 9 1-31/1 * MON', + ])('sends no config for %s', expression => { + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'or')).toBeUndefined(); + }); }); describe('shouldMonitorJob', () => { From dff7c02da7fe3519513ec4d79749ecc8ab1b2b52 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:24:25 -0500 Subject: [PATCH 02/19] fix(server-utils): Read day fields like cron and cron-parser do cron ignores a day field that lists every day. cron-parser counts duplicate values instead, and reads a weekday range that ends on 7 as including Sunday. Each scheduler now gets its own dialect, so cron-parser quirks no longer drop cron schedules and cron rules no longer send configs that node-schedule reads differently. --- packages/nestjs/src/decorators.ts | 2 +- packages/nestjs/test/decorators.test.ts | 3 + packages/node/src/cron/common.ts | 6 +- packages/node/src/cron/cron.ts | 4 +- packages/node/src/cron/node-cron.ts | 2 +- packages/node/src/cron/node-schedule.ts | 2 +- packages/server-utils/src/index.ts | 2 +- .../server-utils/src/integrations/cron.ts | 6 +- .../src/integrations/node-cron.ts | 2 +- .../src/integrations/node-schedule.ts | 6 +- .../server-utils/src/utils/cronMonitoring.ts | 90 +++++++++++++------ .../test/integrations/cron.test.ts | 2 +- .../test/utils/cronMonitoring.test.ts | 83 +++++++++++------ 13 files changed, 138 insertions(+), 72 deletions(-) diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index a8471f3825cb..c38400434dc5 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -147,7 +147,7 @@ export function nestCronOptionsToMonitorConfig( return undefined; } - return cronExpressionToMonitorConfig(cronTime, timeZone, 'or'); + return cronExpressionToMonitorConfig(cronTime, timeZone, 'cron'); } /** diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index fe5fec5adfa5..2f682ea6bc6d 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -399,6 +399,9 @@ describe('SentryCron decorator with @Cron', () => { ['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) => { diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index c83276ff1f39..a86dcb5e1f27 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -1,6 +1,6 @@ import type { MonitorConfig } from '@sentry/core'; import { debug } from '@sentry/core'; -import type { DayFieldSemantics } from '@sentry/server-utils'; +import type { CronDialect } from '@sentry/server-utils'; import { cronExpressionToMonitorConfig } from '@sentry/server-utils'; import { DEBUG_BUILD } from '../debug-build'; @@ -11,9 +11,9 @@ import { DEBUG_BUILD } from '../debug-build'; export function getCronMonitorConfig( expression: string, timezone: unknown, - daySemantics: DayFieldSemantics, + dialect: CronDialect, ): MonitorConfig | undefined { - const monitorConfig = cronExpressionToMonitorConfig(expression, timezone, daySemantics); + const monitorConfig = cronExpressionToMonitorConfig(expression, timezone, dialect); if (!monitorConfig) { DEBUG_BUILD && debug.warn( diff --git a/packages/node/src/cron/cron.ts b/packages/node/src/cron/cron.ts index c95e4486be91..529d47b0aed0 100644 --- a/packages/node/src/cron/cron.ts +++ b/packages/node/src/cron/cron.ts @@ -95,7 +95,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; const utcOffset = args[7]; - const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'or') : undefined; + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; async function monitoredTick(context: unknown, onComplete?: unknown): Promise { return withMonitor( @@ -137,7 +137,7 @@ export function instrumentCron(lib: T & CronJobConstructor, monitorSlug: stri jobScheduled = true; - const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'or') : undefined; + const monitorConfig = utcOffset == null ? getCronMonitorConfig(cronTime, timeZone, 'cron') : undefined; param.onTick = async (context: unknown, onComplete?: unknown) => { return withMonitor( diff --git a/packages/node/src/cron/node-cron.ts b/packages/node/src/cron/node-cron.ts index ebe6d5d610d4..4d49fd20275b 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -57,7 +57,7 @@ export function instrumentNodeCron( throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); } - const cronConfig = getCronMonitorConfig(expression, timezone, 'and'); + const cronConfig = getCronMonitorConfig(expression, timezone, 'node-cron'); const upsertMonitorConfig = cronConfig && { ...cronConfig, ...monitorConfig }; const monitoredCallback = async (...args: Parameters): Promise => { diff --git a/packages/node/src/cron/node-schedule.ts b/packages/node/src/cron/node-schedule.ts index 058a4fa6729c..7920350a5a34 100644 --- a/packages/node/src/cron/node-schedule.ts +++ b/packages/node/src/cron/node-schedule.ts @@ -44,7 +44,7 @@ export function instrumentNodeSchedule(lib: T & NodeSchedule): T { const monitorSlug = nameOrExpression; const expression = expressionOrCallback; - const monitorConfig = getCronMonitorConfig(expression, undefined, 'or'); + const monitorConfig = getCronMonitorConfig(expression, undefined, 'cron-parser'); async function monitoredCallback(): Promise { return withMonitor( diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 2518c5502a3a..45bf2fc01de3 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -45,7 +45,7 @@ export type { NodeCronIntegrationOptions } from './integrations/node-cron'; export { nodeScheduleIntegration } from './integrations/node-schedule'; export type { NodeScheduleIntegrationOptions } from './integrations/node-schedule'; export { cronExpressionToMonitorConfig } from './utils/cronMonitoring'; -export type { DayFieldSemantics } from './utils/cronMonitoring'; +export type { 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..9aa0bd6b43a0 100644 --- a/packages/server-utils/src/integrations/node-cron.ts +++ b/packages/server-utils/src/integrations/node-cron.ts @@ -70,7 +70,7 @@ 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]; 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 bd1046e29fb6..794e4b1eac48 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -98,11 +98,10 @@ const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', ' const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; /** - * 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`). + * The library that parses a scheduler's cron expressions: `node-cron`, `cron` (also behind `@nestjs/schedule`), or + * `cron-parser` (behind `node-schedule`). */ -export type DayFieldSemantics = 'and' | 'or'; +export type CronDialect = 'node-cron' | 'cron' | 'cron-parser'; /** * The Sentry monitor config for a cron expression, or `undefined` if Sentry would read it differently. @@ -111,7 +110,7 @@ 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+/); @@ -125,16 +124,12 @@ export function cronExpressionToMonitorConfig( } const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]; - const crontab = [ - minute, - hour, - dayOfMonth, - replaceNames(month, MONTHS, 1), - endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0)), - ]; + const monthNumbers = replaceNames(month, MONTHS, 1); + const weekdayNumbers = endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0)); + const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers]; if ( crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field)) || - !isSameDayMatching(crontab[2] as string, crontab[4] as string, daySemantics) + !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) ) { return undefined; } @@ -147,28 +142,55 @@ 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. The `or` schedulers -// ignore a day field that covers every day, like `1-31` or `sun-sat`, so they count the days as `cron` does. -// `cron-parser` also ignores a day-of-month that covers every day of the current month, so with a day-of-week, -// 29 or 30 days depend on the month. -function isSameDayMatching(dayOfMonth: string, dayOfWeek: string, daySemantics: DayFieldSemantics): boolean { - const daysOfMonth = countDays(dayOfMonth, 1, 31); - const daysOfWeek = countDays(dayOfWeek, 0, 7); - if (daysOfMonth === undefined || daysOfWeek === undefined) { +// 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 allDaysOfMonth = daysOfMonth === 31; - const allDaysOfWeek = daysOfWeek === 7; - if (daySemantics === 'or' && daysOfMonth >= 29 && !allDaysOfMonth && !allDaysOfWeek) { + 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 { + if (weekdays.cronParserAddsSunday) { return false; } - const schedulerNeedsBoth = daySemantics === 'and' || allDaysOfMonth || allDaysOfWeek; - const sentryNeedsBoth = dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*'); - return (allDaysOfMonth && allDaysOfWeek) || schedulerNeedsBoth === sentryNeedsBoth; + if (dayOfWeek === '*') { + return true; + } + if (dayOfMonth === '*') { + return weekdays.cronParserValues !== 8 || weekdays.days === 7; + } + return !sentryNeedsBoth && monthDays.cronParserValues < 29 && weekdays.cronParserValues !== 8; +} + +interface DayField { + days: number; + cronParserValues: number; + cronParserAddsSunday: boolean; } -function countDays(field: string, low: number, high: number): number | undefined { +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) { @@ -181,11 +203,21 @@ function countDays(field: string, low: number, high: number): number | undefined 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 days.size; + return { + days: days.size, + cronParserValues, + cronParserAddsSunday: cronParserListsSunday && !days.has(0), + }; } function replaceNames(field: string, names: string[], offset: number): string { 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/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 1d11e156b654..d2b8f667af7e 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([ @@ -69,30 +69,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 * mon,fri', '0 9 1 * 1,5'], ['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 0 1 */3 *', '0 0 1 */3 *'], - ['@yearly', '0 0 1 1 *'], - ['@minutely', '* * * * *'], - ['@weekdays', '0 0 * * 1-5'], - ['@weekends', '0 0 * * 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-30 * *', '0 9 1-30 * *'], + ['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, }); @@ -102,27 +97,59 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { '0 9 */2 * 1', '0 9 1 * */2', '0 9 1-31 * 1', - '0 9 15 * 0-6', - '0 9 15 * 1-7', - '0 9 1 * sun-sat', - '0 9 1 * SUN-SAT', - '0 9 1 * mon-sun', - '0 9 1 * 0,1,2,3,4,5,6', '0 9 1-31/1 * MON', - '0 9 1-30 * 1', - '0 9 1-15,16-29 * 1', '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 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', ])('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 *'], + ])('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 * * 1-5,1-3', + '0 9 15 * 1-5,1-3', + '0 9 * * 2-7/2', + '0 9 * * 2/2', + ])('sends no config for %s', expression => { + expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron-parser')).toBeUndefined(); }); }); From 01e9e6f2be8cb0f2f7b79d60c53d297e0b6baef8 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:24:44 -0500 Subject: [PATCH 03/19] fix(server-utils): Send no monitor config for stepped single-value ranges The schedulers run `13-13/3` only on the 13th, but Sentry reads it as `13/3`. --- packages/server-utils/src/utils/cronMonitoring.ts | 10 +++++++++- .../server-utils/test/utils/cronMonitoring.test.ts | 3 +++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index 794e4b1eac48..32adae13ba29 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -128,7 +128,7 @@ export function cronExpressionToMonitorConfig( const weekdayNumbers = endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0)); const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers]; if ( - crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field)) || + crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field) || hasSteppedSingleValueRange(field)) || !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) ) { return undefined; @@ -241,6 +241,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/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index d2b8f667af7e..7848de2d858c 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -46,6 +46,9 @@ 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', From cdd715bc15696146ae216318d30917a20782592b Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:25:40 -0500 Subject: [PATCH 04/19] fix(server-utils): Accept only the names and nicknames each scheduler supports cron and cron-parser reject full names like `sunday` and some nicknames like `@annually`, so they now send no monitor config either. node-cron accepts full names. --- packages/nestjs/test/decorators.test.ts | 2 + .../server-utils/src/utils/cronMonitoring.ts | 53 ++++++++++++------- .../test/utils/cronMonitoring.test.ts | 19 ++++++- 3 files changed, 55 insertions(+), 19 deletions(-) diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 2f682ea6bc6d..5a4c41d797c0 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -376,6 +376,7 @@ describe('SentryCron decorator with @Cron', () => { it.each([ ['a sub-minute schedule', Cron('*/5 * * * * *')], ['a one-off date', Cron(new Date())], + ['an unknown preset', Cron('@reboot')], ['a utc offset', Cron('0 * * * *', { utcOffset: 120 })], ['a numeric month', Cron('0 9 1 5 *')], ['a numeric month range', Cron('0 9 1 1-6 *')], @@ -385,6 +386,7 @@ describe('SentryCron decorator with @Cron', () => { // `0 0 1 0 *` in `@nestjs/schedule` 3 ['CronExpression.EVERY_YEAR', Cron('0 0 1 1 *')], ['a full day-of-week name range with a day of month', Cron('0 9 1 * sun-sat')], + ['an unknown day name', Cron('0 9 1 * sunday')], ['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' })], ])('sends no monitor config for %s', async (_, cronDecorator) => { diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index 32adae13ba29..b206998f0386 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -81,27 +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` (behind `node-schedule`). + */ +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, +}; -/** - * The library that parses a scheduler's cron expressions: `node-cron`, `cron` (also behind `@nestjs/schedule`), or - * `cron-parser` (behind `node-schedule`). - */ -export type CronDialect = 'node-cron' | 'cron' | 'cron-parser'; +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. @@ -113,7 +127,7 @@ export function cronExpressionToMonitorConfig( 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)) { @@ -124,8 +138,8 @@ export function cronExpressionToMonitorConfig( } const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]; - const monthNumbers = replaceNames(month, MONTHS, 1); - const weekdayNumbers = endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0)); + const monthNumbers = replaceNames(month, MONTHS, 1, dialect); + const weekdayNumbers = endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0, dialect)); const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers]; if ( crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field) || hasSteppedSingleValueRange(field)) || @@ -220,9 +234,12 @@ function parseDayField(field: string, low: number, high: number): DayField | und }; } -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); }); } diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 7848de2d858c..e01044edbf5a 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -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'], @@ -54,6 +56,10 @@ describe('cronExpressionToMonitorConfig with node-cron day matching', () => { '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(); }); @@ -107,6 +113,12 @@ describe('cronExpressionToMonitorConfig with cron day matching', () => { '0 9 1 * mon-sun', '0 9 15 * 0,1,2,3,4,5,6', '0 9 15 * 0-3,4-6', + '0 9 * * sunday', + '0 9 * * monday', + '0 9 * january *', + '0 9 15 * sunx', + '@annually', + '@midnight', ])('sends no config for %s', expression => { expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron')).toBeUndefined(); }); @@ -151,6 +163,11 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { '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', ])('sends no config for %s', expression => { expect(cronExpressionToMonitorConfig(expression, 'UTC', 'cron-parser')).toBeUndefined(); }); From 16fedb52314de18a3ea39e8064c86ad83fc20190 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:26:29 -0500 Subject: [PATCH 05/19] fix(node): Check node-cron 3 quirks in instrumentNodeCron instrumentNodeCron can't tell the node-cron version, and before 4.6 node-cron reads ranges like `5-0`, `sat-sun` and `1-7` and some steps differently. It now sends no monitor config for those, like nodeCronIntegration does. --- packages/node/src/cron/common.ts | 5 ++++- packages/node/src/cron/node-cron.ts | 4 +++- packages/node/test/cron.test.ts | 19 +++++++++++++++++++ packages/server-utils/src/index.ts | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index a86dcb5e1f27..5b2bec216ab2 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -12,8 +12,11 @@ export function getCronMonitorConfig( expression: string, timezone: unknown, dialect: CronDialect, + isReadAlike: (expression: string) => boolean = () => true, ): MonitorConfig | undefined { - const monitorConfig = cronExpressionToMonitorConfig(expression, timezone, dialect); + const monitorConfig = isReadAlike(expression) + ? cronExpressionToMonitorConfig(expression, timezone, dialect) + : undefined; if (!monitorConfig) { DEBUG_BUILD && debug.warn( diff --git a/packages/node/src/cron/node-cron.ts b/packages/node/src/cron/node-cron.ts index 4d49fd20275b..f1d8fa789eb5 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -5,6 +5,7 @@ import { startNewTrace, withMonitor, } from '@sentry/core'; +import { isReadAlikeByNodeCron3 } from '@sentry/server-utils'; import { getCronMonitorConfig } from './common'; export interface NodeCronOptions { @@ -57,7 +58,8 @@ export function instrumentNodeCron( throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); } - const cronConfig = getCronMonitorConfig(expression, timezone, 'node-cron'); + // 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 => { diff --git a/packages/node/test/cron.test.ts b/packages/node/test/cron.test.ts index 1a317b9a39a7..a0027520cef7 100644 --- a/packages/node/test/cron.test.ts +++ b/packages/node/test/cron.test.ts @@ -172,6 +172,25 @@ describe('cron check-ins', () => { ); })); + 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 = { diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 45bf2fc01de3..5da5041add8f 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -40,7 +40,7 @@ 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, 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'; From df6c13383f620ab045d2fb88f7348e4df38431b9 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:29:44 -0500 Subject: [PATCH 06/19] test(node): Check the monitor config in the cron instrumentation suites The suites ran per-second jobs, which send no monitor config. They now run a weekday schedule by hand. --- .../suites/cron/cron/scenario.ts | 46 ++++++++----------- .../suites/cron/cron/test.ts | 7 +++ .../suites/cron/node-cron/base/scenario.ts | 20 ++++---- .../suites/cron/node-cron/base/test.ts | 7 +++ .../suites/cron/node-schedule/scenario.ts | 12 +++-- .../suites/cron/node-schedule/test.ts | 7 +++ 6 files changed, 58 insertions(+), 41 deletions(-) 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 69652764b596..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,6 +22,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -46,6 +52,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + 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 96b4d3a92ffe..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,6 +18,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -42,6 +48,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + 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 b25f7eae51ef..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,6 +18,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), @@ -42,6 +48,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => { monitor_slug: 'my-cron-job', status: 'in_progress', release: '1.0', + monitor_config: MONITOR_CONFIG, contexts: { trace: { trace_id: expect.stringMatching(/[a-f\d]{32}/), From e0d55ef14badc148ca27d769557727535bc20cd4 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 15:30:09 -0500 Subject: [PATCH 07/19] docs: Add a changelog entry for the shared cron converter --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cd97aa38ba7..00512e0277c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,10 @@ Work in this release was contributed by @lazerg, @chiliec, @61465, @jpdefo, and Add `Sentry.cronJobIntegration()` to `integrations` to send check-ins for every named `CronJob` of the `cron` package (4.3+), with the job name as the monitor slug. It's off by default. Each monitored job creates a monitor in Sentry, and monitors are billed. Use `excludeJobs` to skip jobs by name. `Sentry.cron.instrumentCron` is deprecated; use `cronJobIntegration` instead. +- **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` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field. + - **feat(nextjs): Mark pageloads of cached pages ([#25318](https://github.com/getsentry/sentry-javascript/pull/25318))** When Next.js serves a page from its cache, for example an ISR page or a `cacheComponents` shell, the pageload now has the `page.server_rendering.type` attribute. It is `static` if the whole page came from the cache, and `partially_static` if parts of it rendered for this request. Then the pageload stays connected to this request, as before. If the request that rendered the cached page was sampled, the pageload also links to it. So in Sentry, a cached page no longer looks like missing server instrumentation. From d04b07f8a7aaccbac0252483026aa5f631153491 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 3 Nov 2026 16:05:02 -0500 Subject: [PATCH 08/19] fix(server-utils): Send no monitor config for unranged steps before node-cron 4.6 node-cron before 4.6 reads a step without a range, like `5/10`, as its start. --- .../server-utils/src/integrations/node-cron.ts | 10 +++++++--- .../test/integrations/node-cron.test.ts | 18 ++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/server-utils/src/integrations/node-cron.ts b/packages/server-utils/src/integrations/node-cron.ts index 9aa0bd6b43a0..aef5095b1e5f 100644 --- a/packages/server-utils/src/integrations/node-cron.ts +++ b/packages/server-utils/src/integrations/node-cron.ts @@ -77,11 +77,15 @@ 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/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', () => { From 58e0168f53e2aa7064bc426ef061c84e64843012 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Mon, 9 Nov 2026 10:24:06 -0800 Subject: [PATCH 09/19] fix(server-utils): Only end Sunday ranges on 7 for node-cron The cron and cron-parser packages reject ranges like sat-sun, so don't send a monitor config for them. --- packages/server-utils/src/utils/cronMonitoring.ts | 6 ++++-- packages/server-utils/test/utils/cronMonitoring.test.ts | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index b206998f0386..407a9960c7d8 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -139,7 +139,8 @@ export function cronExpressionToMonitorConfig( const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]; const monthNumbers = replaceNames(month, MONTHS, 1, dialect); - const weekdayNumbers = endRangesOnSundayAsSeven(replaceNames(dayOfWeek, WEEKDAYS, 0, 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 => /[a-z]/i.test(field) || hasReversedRange(field) || hasSteppedSingleValueRange(field)) || @@ -244,7 +245,8 @@ function replaceNames(field: string, names: string[], offset: number, dialect: C }); } -// `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)); } diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index e01044edbf5a..98482c853571 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -111,6 +111,9 @@ describe('cronExpressionToMonitorConfig with cron day matching', () => { '0 9 15 * 1-7', '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 * 0-3,4-6', '0 9 * * sunday', @@ -159,6 +162,9 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { '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', From a841b50bd2c85ade0958aa5f55a3f7b9887b1f9d Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:05:39 -0800 Subject: [PATCH 10/19] feat(server-utils): Read L and # in cron-parser expressions cron-parser and Sentry read `L` in the day of month and `5L` and `5#2` in the day of week the same way, so send those as monitor config. Forms they read differently, like `#` with a restricted day of month, still send none. Co-Authored-By: Claude --- .../server-utils/src/utils/cronMonitoring.ts | 24 ++++++++++++++-- .../test/utils/cronMonitoring.test.ts | 28 +++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index 407a9960c7d8..ec8ff4ee60e9 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -133,7 +133,7 @@ export function cronExpressionToMonitorConfig( 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))) { + if (fields.length !== 5 || !fields.every(field => /^[\d*,/a-z#-]+$/i.test(field))) { return undefined; } @@ -143,7 +143,12 @@ export function cronExpressionToMonitorConfig( const weekdayNumbers = dialect === 'node-cron' ? endRangesOnSundayAsSeven(weekdayNames) : weekdayNames; const crontab = [minute, hour, dayOfMonth, monthNumbers, weekdayNumbers]; if ( - crontab.some(field => /[a-z]/i.test(field) || hasReversedRange(field) || hasSteppedSingleValueRange(field)) || + crontab.some( + (field, index) => + hasUnsupportedCharacter(field, dialect === 'cron-parser' ? CRON_PARSER_DAY_TOKENS[index] : undefined) || + hasReversedRange(field) || + hasSteppedSingleValueRange(field), + ) || !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) ) { return undefined; @@ -157,6 +162,13 @@ export function cronExpressionToMonitorConfig( return { schedule: { type: 'crontab', value: crontab.join(' ') }, timezone: sentryTimezone }; } +// `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); @@ -184,7 +196,8 @@ function isSameDayMatchingInCronParser( weekdays: DayField, sentryNeedsBoth: boolean, ): boolean { - if (weekdays.cronParserAddsSunday) { + // `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 === '*') { @@ -207,6 +220,11 @@ function parseDayField(field: string, low: number, high: number): DayField | und let cronParserValues = 0; let cronParserListsSunday = false; for (const part of field.split(',')) { + // `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 match = /^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part); if (!match) { return undefined; diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 98482c853571..41226e34405a 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -122,6 +122,9 @@ describe('cronExpressionToMonitorConfig with cron day matching', () => { '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', 'cron')).toBeUndefined(); }); @@ -141,6 +144,17 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { ['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', @@ -174,6 +188,20 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { '@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(); }); From ce81576d5cd48055af0c0d136fa7f60b71d307ac Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:18:34 -0800 Subject: [PATCH 11/19] fix(server-utils): Match Sunday ranges per list item Anchoring the regex keeps it linear on long digit runs (CodeQL js/polynomial-redos). --- packages/server-utils/src/utils/cronMonitoring.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index ec8ff4ee60e9..f32eda5a9cd6 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -266,7 +266,10 @@ function replaceNames(field: string, names: string[], offset: number, dialect: C // `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, From ecfa6fc4e9bbc5fb709e976a1991cd10a8f8d3ab Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 14:44:52 -0800 Subject: [PATCH 12/19] fix(server-utils): Send a 2-minute check-in margin for dropped seconds A dropped seconds value like 59 in '59 0 9 * * *' leaves about a second of slack against Sentry's default 1-minute margin. @SentryCron keeps a larger margin set by the user. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- packages/nestjs/src/decorators.ts | 3 ++- packages/nestjs/test/decorators.test.ts | 16 ++++++++++++++++ .../server-utils/src/utils/cronMonitoring.ts | 11 +++++++---- .../test/utils/cronMonitoring.test.ts | 14 ++++++++++++++ 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e979631426a0..117c2be292aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Work in this release was contributed by @kunal649. Thank you for your contributi - **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` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field. `instrumentNodeSchedule` also sends `L` and `#`, where Sentry reads them the same way. + `Sentry.cron.instrumentCron`, `instrumentNodeCron` and `instrumentNodeSchedule` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field, with a 2-minute check-in margin when the seconds aren't 0. `instrumentNodeSchedule` also sends `L` and `#`, where Sentry reads them the same way. ## 11.12.0 diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index c38400434dc5..c66ccca12d7b 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -94,7 +94,8 @@ function resolveMonitorConfig( return undefined; } - return { ...monitorSettings, ...cronConfig }; + const checkinMargin = Math.max(monitorSettings.checkinMargin ?? 0, cronConfig.checkinMargin ?? 0); + return { ...monitorSettings, ...cronConfig, ...(checkinMargin > 0 && { checkinMargin }) }; } const SCHEDULE_CRON_OPTIONS = 'SCHEDULE_CRON_OPTIONS'; diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 5a4c41d797c0..14caae1a652c 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -504,6 +504,22 @@ describe('SentryCron decorator with @Cron', () => { }); }); + it.each([ + [undefined, 2], + [1, 2], + [5, 5], + ])('sends a checkinMargin of at least 2 for a dropped seconds value, given %s', async (configured, expected) => { + const withMonitorSpy = vi.spyOn(core, 'withMonitor'); + const service = decorate(SentryCron('my-job', { checkinMargin: configured }), 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: expected, + }); + }); + 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/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index f32eda5a9cd6..d0f35670fac0 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -130,9 +130,7 @@ export function cronExpressionToMonitorConfig( 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(); - } + const droppedSecond = fields.length === 6 && /^\d+$/.test(fields[0] as string) ? Number(fields.shift()) : 0; if (fields.length !== 5 || !fields.every(field => /^[\d*,/a-z#-]+$/i.test(field))) { return undefined; } @@ -159,7 +157,12 @@ export function cronExpressionToMonitorConfig( return undefined; } - return { schedule: { type: 'crontab', value: crontab.join(' ') }, timezone: sentryTimezone }; + return { + schedule: { type: 'crontab', value: crontab.join(' ') }, + timezone: sentryTimezone, + // The job runs up to 59 seconds after the minute Sentry expects, which nearly uses up its default 1-minute margin. + ...(droppedSecond > 0 && { checkinMargin: 2 }), + }; } // `cron-parser` reads these like Sentry: `L` is the last day of the month, `5L` the last Friday, `5#2` the second Friday. diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 41226e34405a..442c73cec467 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -207,6 +207,20 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { }); }); +describe('cronExpressionToMonitorConfig with a dropped seconds value', () => { + it.each(['node-cron', 'cron', 'cron-parser'] as const)('sends a 2-minute checkinMargin with %s', dialect => { + expect(cronExpressionToMonitorConfig('59 0 9 * * *', 'UTC', dialect)).toEqual({ + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'UTC', + checkinMargin: 2, + }); + expect(cronExpressionToMonitorConfig('0 0 9 * * *', 'UTC', dialect)).toEqual({ + schedule: { type: 'crontab', value: '0 9 * * *' }, + timezone: 'UTC', + }); + }); +}); + describe('shouldMonitorJob', () => { const job = (): void => {}; From 7c966f109feeb7addd1d481c8d99f946aa0d6729 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 14:59:12 -0800 Subject: [PATCH 13/19] fix(server-utils): Send no config for a day of month the months don't have Sentry rejects schedules like '0 9 31 2,4 *', which cron-parser runs on the day of week. A fuzz of cron-parser 4 and 5 against cronsim found no other differences, so the cron-parser dialect covers both. Co-Authored-By: Claude Opus 5.5 --- .../server-utils/src/utils/cronMonitoring.ts | 20 +++++++++++++++-- .../test/utils/cronMonitoring.test.ts | 22 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index d0f35670fac0..bf7c96058bb8 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -83,7 +83,7 @@ export function shouldMonitorJob( /** * The library that parses a scheduler's cron expressions: `node-cron`, `cron` (also behind `@nestjs/schedule`), or - * `cron-parser` (behind `node-schedule`). + * `cron-parser` 4 or 5 (behind `node-schedule` and BullMQ). */ export type CronDialect = 'node-cron' | 'cron' | 'cron-parser'; @@ -147,7 +147,8 @@ export function cronExpressionToMonitorConfig( hasReversedRange(field) || hasSteppedSingleValueRange(field), ) || - !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) + !isSameDayMatching(dayOfMonth, weekdayNumbers, dialect) || + !hasDayInSelectedMonths(dayOfMonth, monthNumbers) ) { return undefined; } @@ -212,7 +213,21 @@ function isSameDayMatchingInCronParser( return !sentryNeedsBoth && monthDays.cronParserValues < 29 && weekdays.cronParserValues !== 8; } +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; @@ -250,6 +265,7 @@ function parseDayField(field: string, low: number, high: number): DayField | und } } return { + values: days, days: days.size, cronParserValues, cronParserAddsSunday: cronParserListsSunday && !days.has(0), diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index 442c73cec467..f66fa4a2f46e 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -207,6 +207,28 @@ describe('cronExpressionToMonitorConfig with cron-parser day matching', () => { }); }); +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 a 2-minute checkinMargin with %s', dialect => { expect(cronExpressionToMonitorConfig('59 0 9 * * *', 'UTC', dialect)).toEqual({ From 28da7c96df845d4b0bbcfd68b5a4d13b864acdd2 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 15:54:41 -0800 Subject: [PATCH 14/19] docs: Note that the dropped-seconds margin replaces one set in Sentry Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 117c2be292aa..1b5793cc9df3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Work in this release was contributed by @kunal649. Thank you for your contributi - **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` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field, with a 2-minute check-in margin when the seconds aren't 0. `instrumentNodeSchedule` also sends `L` and `#`, where Sentry reads them the same way. + `Sentry.cron.instrumentCron`, `instrumentNodeCron` and `instrumentNodeSchedule` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field. If the seconds field isn't `0`, a check-in margin of 2 minutes is sent too, since the job checks in up to 59 seconds after the minute Sentry expects. This replaces a margin set in Sentry. Expressions with a day of month that none of their months have, like `0 9 31 2,4 *`, send no monitor config. `instrumentNodeSchedule` also sends `L` and `#`, where Sentry reads them the same way. ## 11.12.0 From 25c5ed55a9c175dea8f4a33a47548929f501423a Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 12 Nov 2026 13:43:07 -0800 Subject: [PATCH 15/19] fix(server-utils): Send no check-in margin for dropped seconds Sentry's upsert overwrites every field a check-in sends, so an automatic margin would replace one set in Sentry. @SentryCron sends only the margin passed to it. Co-Authored-By: Claude Opus 5.5 --- packages/nestjs/src/decorators.ts | 3 +- packages/nestjs/test/decorators.test.ts | 29 +++++++++---------- .../server-utils/src/utils/cronMonitoring.ts | 11 +++---- .../test/utils/cronMonitoring.test.ts | 7 +---- 4 files changed, 20 insertions(+), 30 deletions(-) diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index c66ccca12d7b..c38400434dc5 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -94,8 +94,7 @@ function resolveMonitorConfig( return undefined; } - const checkinMargin = Math.max(monitorSettings.checkinMargin ?? 0, cronConfig.checkinMargin ?? 0); - return { ...monitorSettings, ...cronConfig, ...(checkinMargin > 0 && { checkinMargin }) }; + return { ...monitorSettings, ...cronConfig }; } const SCHEDULE_CRON_OPTIONS = 'SCHEDULE_CRON_OPTIONS'; diff --git a/packages/nestjs/test/decorators.test.ts b/packages/nestjs/test/decorators.test.ts index 14caae1a652c..66f75a616a28 100644 --- a/packages/nestjs/test/decorators.test.ts +++ b/packages/nestjs/test/decorators.test.ts @@ -504,21 +504,20 @@ describe('SentryCron decorator with @Cron', () => { }); }); - it.each([ - [undefined, 2], - [1, 2], - [5, 5], - ])('sends a checkinMargin of at least 2 for a dropped seconds value, given %s', async (configured, expected) => { - const withMonitorSpy = vi.spyOn(core, 'withMonitor'); - const service = decorate(SentryCron('my-job', { checkinMargin: configured }), 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: expected, - }); - }); + 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'); diff --git a/packages/server-utils/src/utils/cronMonitoring.ts b/packages/server-utils/src/utils/cronMonitoring.ts index bf7c96058bb8..e595fc010920 100644 --- a/packages/server-utils/src/utils/cronMonitoring.ts +++ b/packages/server-utils/src/utils/cronMonitoring.ts @@ -130,7 +130,9 @@ export function cronExpressionToMonitorConfig( const fields = (NICKNAMES[dialect][trimmed.toLowerCase()] || trimmed).split(/\s+/); // Sentry schedules have minute granularity, so only a fixed second can be dropped. - const droppedSecond = fields.length === 6 && /^\d+$/.test(fields[0] as string) ? Number(fields.shift()) : 0; + 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; } @@ -158,12 +160,7 @@ export function cronExpressionToMonitorConfig( return undefined; } - return { - schedule: { type: 'crontab', value: crontab.join(' ') }, - timezone: sentryTimezone, - // The job runs up to 59 seconds after the minute Sentry expects, which nearly uses up its default 1-minute margin. - ...(droppedSecond > 0 && { checkinMargin: 2 }), - }; + return { schedule: { type: 'crontab', value: crontab.join(' ') }, timezone: sentryTimezone }; } // `cron-parser` reads these like Sentry: `L` is the last day of the month, `5L` the last Friday, `5#2` the second Friday. diff --git a/packages/server-utils/test/utils/cronMonitoring.test.ts b/packages/server-utils/test/utils/cronMonitoring.test.ts index f66fa4a2f46e..cd901879de3a 100644 --- a/packages/server-utils/test/utils/cronMonitoring.test.ts +++ b/packages/server-utils/test/utils/cronMonitoring.test.ts @@ -230,15 +230,10 @@ describe('cronExpressionToMonitorConfig with days the months lack', () => { }); describe('cronExpressionToMonitorConfig with a dropped seconds value', () => { - it.each(['node-cron', 'cron', 'cron-parser'] as const)('sends a 2-minute checkinMargin with %s', dialect => { + 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', - checkinMargin: 2, - }); - expect(cronExpressionToMonitorConfig('0 0 9 * * *', 'UTC', dialect)).toEqual({ - schedule: { type: 'crontab', value: '0 9 * * *' }, - timezone: 'UTC', }); }); }); From d77be6b85f1fd66cc1956591d01ceff00dd6427a Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 12 Nov 2026 13:43:07 -0800 Subject: [PATCH 16/19] ref(server-utils): Prefix the shared cron converter exports with _INTERNAL_ Co-Authored-By: Claude Opus 5.5 --- packages/nestjs/src/decorators.ts | 2 +- packages/node/src/cron/common.ts | 4 ++-- packages/node/src/cron/node-cron.ts | 2 +- packages/server-utils/src/index.ts | 9 ++++++--- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/packages/nestjs/src/decorators.ts b/packages/nestjs/src/decorators.ts index c38400434dc5..f255e293fcb4 100644 --- a/packages/nestjs/src/decorators.ts +++ b/packages/nestjs/src/decorators.ts @@ -3,7 +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 { cronExpressionToMonitorConfig } from '@sentry/server-utils'; +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'; diff --git a/packages/node/src/cron/common.ts b/packages/node/src/cron/common.ts index 5b2bec216ab2..be0097ab7142 100644 --- a/packages/node/src/cron/common.ts +++ b/packages/node/src/cron/common.ts @@ -1,7 +1,7 @@ import type { MonitorConfig } from '@sentry/core'; import { debug } from '@sentry/core'; -import type { CronDialect } from '@sentry/server-utils'; -import { cronExpressionToMonitorConfig } from '@sentry/server-utils'; +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'; /** diff --git a/packages/node/src/cron/node-cron.ts b/packages/node/src/cron/node-cron.ts index f1d8fa789eb5..40db74004dd4 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -5,7 +5,7 @@ import { startNewTrace, withMonitor, } from '@sentry/core'; -import { isReadAlikeByNodeCron3 } from '@sentry/server-utils'; +import { _INTERNAL_isReadAlikeByNodeCron3 as isReadAlikeByNodeCron3 } from '@sentry/server-utils'; import { getCronMonitorConfig } from './common'; export interface NodeCronOptions { diff --git a/packages/server-utils/src/index.ts b/packages/server-utils/src/index.ts index 3ab5b322c212..2554c49e3901 100644 --- a/packages/server-utils/src/index.ts +++ b/packages/server-utils/src/index.ts @@ -40,12 +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 { isReadAlikeByNodeCron3, 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 } from './utils/cronMonitoring'; -export type { CronDialect } from './utils/cronMonitoring'; +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'; From 982c9a6f58d86d3ccb630019085aca6d60df4c13 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 12 Nov 2026 13:43:07 -0800 Subject: [PATCH 17/19] docs: Shorten the shared cron converter changelog entry Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b5793cc9df3..1e257cc8b07d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Work in this release was contributed by @kunal649. Thank you for your contributi - **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` read schedules the same way as `@SentryCron` and the cron integrations. Without a time zone, they send the server's time zone, where the scheduler runs the job, instead of letting Sentry assume UTC. For expressions Sentry would read differently than the scheduler, like per-second schedules, they send no monitor config, so existing monitors keep their schedule. They send names and nicknames like `MON` or `@daily` as numbers, and drop a fixed seconds field. If the seconds field isn't `0`, a check-in margin of 2 minutes is sent too, since the job checks in up to 59 seconds after the minute Sentry expects. This replaces a margin set in Sentry. Expressions with a day of month that none of their months have, like `0 9 31 2,4 *`, send no monitor config. `instrumentNodeSchedule` also sends `L` and `#`, where Sentry reads them the same way. + `Sentry.cron.instrumentCron`, `instrumentNodeCron` and `instrumentNodeSchedule` now send the server's time zone when the job has none, instead of letting Sentry assume UTC. Schedules Sentry would read differently than the scheduler, like per-second schedules, send no monitor config, so the monitor keeps the schedule it has in Sentry. ## 11.12.0 From c45f7c2ca854db29a0a0772d18f67cd35f00bb9b Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 12 Nov 2026 14:18:08 -0800 Subject: [PATCH 18/19] chore(changelog): Tighten the shared cron converter entry --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e257cc8b07d..edfc30f5f352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Work in this release was contributed by @kunal649. Thank you for your contributi - **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` now send the server's time zone when the job has none, instead of letting Sentry assume UTC. Schedules Sentry would read differently than the scheduler, like per-second schedules, send no monitor config, so the monitor keeps the schedule it has in Sentry. + `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. ## 11.12.0 From 084855ed625733d1db4d17f3c488ec1f761e5d20 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Mon, 16 Nov 2026 12:40:19 -0800 Subject: [PATCH 19/19] feat(node): Deprecate instrumentNodeCron in favor of nodeCronIntegration --- CHANGELOG.md | 2 +- packages/node/src/cron/index.ts | 1 + packages/node/src/cron/node-cron.ts | 5 +++++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edfc30f5f352..b2f08244db8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Work in this release was contributed by @kunal649. Thank you for your contributi - **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.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 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 40db74004dd4..f56b61b144cc 100644 --- a/packages/node/src/cron/node-cron.ts +++ b/packages/node/src/cron/node-cron.ts @@ -38,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,