Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
d492b2f
ref(server-utils): Share one cron converter across cron integrations
wedamija Oct 29, 2026
90352f2
Merge remote-tracking branch 'origin/develop' into danf/shared-cron-c…
wedamija Nov 3, 2026
dff7c02
fix(server-utils): Read day fields like cron and cron-parser do
wedamija Nov 3, 2026
01e9e6f
fix(server-utils): Send no monitor config for stepped single-value ra…
wedamija Nov 3, 2026
cdd715b
fix(server-utils): Accept only the names and nicknames each scheduler…
wedamija Nov 3, 2026
16fedb5
fix(node): Check node-cron 3 quirks in instrumentNodeCron
wedamija Nov 3, 2026
df6c133
test(node): Check the monitor config in the cron instrumentation suites
wedamija Nov 3, 2026
e0d55ef
docs: Add a changelog entry for the shared cron converter
wedamija Nov 3, 2026
d04b07f
fix(server-utils): Send no monitor config for unranged steps before n…
wedamija Nov 3, 2026
4fb2d9f
Merge commit 'refs/sync/develop' into danf/shared-cron-converter
wedamija Nov 9, 2026
58e0168
fix(server-utils): Only end Sunday ranges on 7 for node-cron
wedamija Nov 9, 2026
a841b50
feat(server-utils): Read L and # in cron-parser expressions
wedamija Nov 11, 2026
a91dd40
Merge remote-tracking branch 'origin/develop' into danf/shared-cron-c…
wedamija Nov 11, 2026
ce81576
fix(server-utils): Match Sunday ranges per list item
wedamija Nov 11, 2026
ecfa6fc
fix(server-utils): Send a 2-minute check-in margin for dropped seconds
wedamija Nov 11, 2026
7c966f1
fix(server-utils): Send no config for a day of month the months don't…
wedamija Nov 11, 2026
28da7c9
docs: Note that the dropped-seconds margin replaces one set in Sentry
wedamija Nov 11, 2026
25c5ed5
fix(server-utils): Send no check-in margin for dropped seconds
wedamija Nov 12, 2026
d77be6b
ref(server-utils): Prefix the shared cron converter exports with _INT…
wedamija Nov 12, 2026
982c9a6
docs: Shorten the shared cron converter changelog entry
wedamija Nov 12, 2026
c45f7c2
chore(changelog): Tighten the shared cron converter entry
wedamija Nov 12, 2026
084855e
feat(node): Deprecate instrumentNodeCron in favor of nodeCronIntegration
wedamija Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@

Work in this release was contributed by @kunal649. Thank you for your contribution!

### Important Changes

- **ref(server-utils): Share one cron converter across cron integrations ([#25918](https://github.com/getsentry/sentry-javascript/pull/25918))**

`Sentry.cron.instrumentCron`, `instrumentNodeCron` and `instrumentNodeSchedule` send the server's time zone when a job has none, so monitors don't report false misses on servers that aren't on UTC. Schedules Sentry can't express exactly, such as per-second schedules, send no monitor config, so the monitor keeps the schedule set in Sentry. `Sentry.cron.instrumentNodeCron` is deprecated; use `nodeCronIntegration` instead.

## 11.12.0

### Important Changes
Expand Down
46 changes: 20 additions & 26 deletions dev-packages/node-integration-tests/suites/cron/cron/scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
9 changes: 7 additions & 2 deletions dev-packages/node-integration-tests/suites/cron/cron/test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
Expand All @@ -17,7 +22,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down Expand Up @@ -47,7 +52,7 @@ test('cron instrumentation', { timeout: 60_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Original file line number Diff line number Diff line change
@@ -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();
});
Expand All @@ -13,7 +18,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down Expand Up @@ -43,7 +48,7 @@ test('node-cron instrumentation', { timeout: 30_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Original file line number Diff line number Diff line change
@@ -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();
});
Expand All @@ -13,7 +18,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down Expand Up @@ -43,7 +48,7 @@ test('node-schedule instrumentation', { timeout: 30_000 }, async () => {
monitor_slug: 'my-cron-job',
status: 'in_progress',
release: '1.0',
monitor_config: { schedule: { type: 'crontab', value: '* * * * * *' } },
monitor_config: MONITOR_CONFIG,
contexts: {
trace: {
trace_id: expect.stringMatching(/[a-f\d]{32}/),
Expand Down
122 changes: 4 additions & 118 deletions packages/nestjs/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CODE_FUNCTION_NAME, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/convention
import { captureException, debug } from '@sentry/core';
import * as Sentry from '@sentry/node';
import { startSpan } from '@sentry/node';
import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils';
import { DEBUG_BUILD } from './debug-build';
import { isExpectedError } from './helpers';
import type { ReflectWithMetadata } from './integrations/helpers';
Expand Down Expand Up @@ -98,18 +99,6 @@ function resolveMonitorConfig(

const SCHEDULE_CRON_OPTIONS = 'SCHEDULE_CRON_OPTIONS';

// `cron` presets (case-insensitive). Sentry accepts only the first five, so the others are sent as crontabs.
const CRON_PRESETS: Record<string, string | undefined> = {
'@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;
Expand Down Expand Up @@ -150,118 +139,15 @@ export function nestCronOptionsToMonitorConfig(
return undefined;
}

// `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps and names don't depend on that.
const fields = cronTime.trim().split(/\s+/);
let crontab: string | undefined;
if (fields.length === 1) {
crontab = CRON_PRESETS[(fields[0] as string).toLowerCase()];
} else if (fields.length === 5) {
crontab = isSupportedCrontab(fields, scheduleVersion) ? fields.join(' ') : undefined;
} else if (fields.length === 6 && /^\d+$/.test(fields[0] as string)) {
// Sentry schedules have minute granularity, so only a fixed second can be dropped.
crontab = isSupportedCrontab(fields.slice(1), scheduleVersion) ? fields.slice(1).join(' ') : undefined;
}

if (!crontab) {
return undefined;
}

// Without a `timeZone`, `cron` uses the server's time zone, but Sentry would assume UTC.
const timezone = toSentryTimeZone(typeof timeZone === 'string' && timeZone ? timeZone : getLocalTimeZone());
if (!timezone) {
return undefined;
}

return {
schedule: { type: 'crontab', value: crontab },
timezone,
};
}

/**
* Whether Sentry reads the 5 crontab fields the same way `cron` (used by `@nestjs/schedule`) runs them.
*/
function isSupportedCrontab(
[, , dayOfMonth = '', month = '', dayOfWeek = '']: string[],
scheduleVersion: string | undefined,
): boolean {
// `cron` 2.x (`@nestjs/schedule` 2 and 3) counts months from 0. Steps don't depend on that.
const month = fields.length >= 5 ? (fields[fields.length - 2] as string) : '';
const countsMonthsFromOne = parseInt(scheduleVersion ?? '', 10) >= 4;
if (!countsMonthsFromOne && /\d/.test(month.replace(/\/\d+/g, ''))) {
return false;
}

const daysOfMonth = countCronValues(dayOfMonth, 1, 31);
const daysOfWeek = countCronValues(dayOfWeek, 0, 7);
if (daysOfMonth === undefined || daysOfWeek === undefined) {
return false;
}

// `cron` ignores a day field that covers every day (like `1-31` or `sun-sat`) and runs on either day field
// otherwise. Sentry reads full ranges as they are and needs both day fields when one starts with `*` (like `*/2`).
const allDaysOfMonth = daysOfMonth === 31;
const allDaysOfWeek = daysOfWeek === 7;
const cronRunsOnEither = !allDaysOfMonth && !allDaysOfWeek;
const sentryRunsOnEither = !dayOfMonth.startsWith('*') && !dayOfWeek.startsWith('*');
return (allDaysOfMonth && allDaysOfWeek) || cronRunsOnEither === sentryRunsOnEither;
}

const DAY_NAMES: Record<string, number | undefined> = { 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<number>();
for (const part of numericField.split(',')) {
const match = part.match(/^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/);
if (!match) {
return undefined;
}
const [, wildcard, from, to, step] = match;
const lower = wildcard ? low : Number(from);
const upper = wildcard || (step && !to) ? high : Number(to ?? from);
const increment = Number(step ?? 1);
if (!increment || lower < low || upper > high || lower > upper) {
return undefined;
}
for (let value = lower; value <= upper; value += increment) {
values.add(high === 7 && value === 7 ? 0 : value);
}
}
return values.size;
}

/**
* The canonical IANA name of the time zone, or `undefined` if Sentry won't accept it (like `UTC+3`).
*/
function toSentryTimeZone(timezone: string | undefined): string | undefined {
if (!timezone || timezone === 'Etc/Unknown' || /^(?:utc|gmt)?[+-]/i.test(timezone)) {
return undefined;
}
try {
return new Intl.DateTimeFormat('en-US', { timeZone: timezone }).resolvedOptions().timeZone || undefined;
} catch {
return undefined;
}
}

function getLocalTimeZone(): string | undefined {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
} catch {
return undefined;
}
return cronExpressionToMonitorConfig(cronTime, timeZone, 'cron');
}

/**
Expand Down
Loading
Loading