Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schedule): use croner library to check schedule #32573

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions docs/usage/configuration-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -3836,6 +3836,7 @@ Here are some example schedules and their Cron equivalent:
<!-- prettier-ignore -->
!!! note
For Cron schedules, you _must_ use the `*` wildcard for the minutes value, as Renovate doesn't support minute granularity.
And the cron schedule must have five comma separated parts.

One example might be that you don't want Renovate to run during your typical business hours, so that your build machines don't get clogged up testing `package.json` updates.
You could then configure a schedule like this at the repository level:
Expand Down
66 changes: 65 additions & 1 deletion lib/workers/repository/update/branch/schedule.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ describe('workers/repository/update/branch/schedule', () => {
it('returns true if schedule uses cron syntax', () => {
expect(schedule.hasValidSchedule(['* 5 * * *'])[0]).toBeTrue();
expect(schedule.hasValidSchedule(['* * * * * 6L'])[0]).toBeTrue();
expect(schedule.hasValidSchedule(['* * */2 6#1'])[0]).toBeTrue();
expect(schedule.hasValidSchedule(['* * * */2 6#1'])[0]).toBeTrue();
RahulGautamSingh marked this conversation as resolved.
Show resolved Hide resolved
expect(schedule.hasValidSchedule(['2 3 5 11 *'])[0]).toBeFalse();
expect(schedule.hasValidSchedule(['2 3 5 11'])[0]).toBeFalse();
});

it('massages schedules', () => {
Expand Down Expand Up @@ -267,6 +269,50 @@ describe('workers/repository/update/branch/schedule', () => {
});
});

describe('supports L syntax in cron schedules', () => {
beforeEach(() => {
jest.setSystemTime(new Date('2024-10-31T10:50:00.000'));
viceice marked this conversation as resolved.
Show resolved Hide resolved
});

it('supports last day of month', () => {
config.schedule = ['* * * L *'];
const res = schedule.isScheduledNow(config);
expect(res).toBeTrue();
});

it('supports last day of week', () => {
config.schedule = ['* * * * 4L'];
expect(schedule.isScheduledNow(config)).toBeTrue();

config.schedule = ['* * * * 5L'];
expect(schedule.isScheduledNow(config)).toBeFalse();
});
});

describe('supports # syntax in cron schedules', () => {
it('supports first Monday of month', () => {
jest.setSystemTime(new Date('2024-10-07T10:50:00.000'));
config.schedule = ['* * * * 1#1'];
expect(schedule.isScheduledNow(config)).toBeTrue();
config.schedule = ['* * * * 1#2'];
expect(schedule.isScheduledNow(config)).toBeFalse();
});
});

describe('complex cron schedules', () => {
it.each`
viceice marked this conversation as resolved.
Show resolved Hide resolved
sched | datetime | expected
${'* * 1-7 * 0'} | ${'2024-10-04T10:50:00.000+0900'} | ${true}
${'* * 1-7 * 0'} | ${'2024-10-13T10:50:00.000+0900'} | ${true}
${'* * 1-7 * 0'} | ${'2024-10-16T10:50:00.000+0900'} | ${false}
`('$sched, $tz, $datetime', ({ sched, tz, datetime, expected }) => {
config.schedule = [sched];
config.timezone = 'Asia/Tokyo';
jest.setSystemTime(new Date(datetime));
RahulGautamSingh marked this conversation as resolved.
Show resolved Hide resolved
expect(schedule.isScheduledNow(config)).toBe(expected);
});
});

describe('supports timezone', () => {
it.each`
sched | tz | datetime | expected
Expand All @@ -282,6 +328,24 @@ describe('workers/repository/update/branch/schedule', () => {
});
});

it('reject if day mismatch', () => {
config.schedule = ['* 10 21 * *'];
const res = schedule.isScheduledNow(config);
expect(res).toBeFalse();
});

it('reject if month mismatch', () => {
config.schedule = ['* 10 30 1 *'];
const res = schedule.isScheduledNow(config);
expect(res).toBeFalse();
});

it('reject if no schedule available', () => {
config.schedule = ['* * * 1 *'];
const res = schedule.isScheduledNow(config);
expect(res).toBeFalse();
});

it('supports multiple schedules', () => {
config.schedule = ['after 4:00pm', 'before 11:00am'];
const res = schedule.isScheduledNow(config);
Expand Down
69 changes: 27 additions & 42 deletions lib/workers/repository/update/branch/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,22 @@
import later from '@breejs/later';
import is from '@sindresorhus/is';
import type {
CronExpression,
DayOfTheMonthRange,
DayOfTheWeekRange,
HourRange,
MonthRange,
} from 'cron-parser';
import { parseExpression } from 'cron-parser';
import { Cron, CronPattern } from 'croner';
import cronstrue from 'cronstrue';
import { DateTime } from 'luxon';
import { fixShortHours } from '../../../../config/migration';
import type { RenovateConfig } from '../../../../config/types';
import { logger } from '../../../../logger';

const minutesChar = '*';

const scheduleMappings: Record<string, string> = {
'every month': 'before 5am on the first day of the month',
monthly: 'before 5am on the first day of the month',
};

function parseCron(
scheduleText: string,
timezone?: string,
): CronExpression | undefined {
const minutesChar = '*';

function parseCron(scheduleText: string): CronPattern | undefined {
try {
return parseExpression(scheduleText, { tz: timezone });
return new CronPattern(scheduleText);
} catch {
return undefined;
}
Expand Down Expand Up @@ -55,7 +45,7 @@ export function hasValidSchedule(
const parsedCron = parseCron(scheduleText);
if (parsedCron !== undefined) {
if (
parsedCron.fields.minute.length !== 60 ||
parsedCron.minute.filter((v) => v !== 1).length !== 0 ||
scheduleText.indexOf(minutesChar) !== 0
) {
message = `Invalid schedule: "${scheduleText}" has cron syntax, but doesn't have * as minutes`;
Expand Down Expand Up @@ -99,43 +89,38 @@ export function hasValidSchedule(
return [true];
}

function cronMatches(cron: string, now: DateTime, timezone?: string): boolean {
const parsedCron = parseCron(cron, timezone);

export function cronMatches(
cron: string,
now: DateTime,
timezone?: string,
): boolean {
const parsedCron: Cron = new Cron(cron, {
...(timezone && { timezone }),
});
// it will always parse because it is checked beforehand
// istanbul ignore if
if (!parsedCron) {
return false;
}

if (parsedCron.fields.hour.indexOf(now.hour as HourRange) === -1) {
// Hours mismatch
return false;
}

if (
parsedCron.fields.dayOfMonth.indexOf(now.day as DayOfTheMonthRange) === -1
) {
// Days mismatch
// return the next date which matches the cron schedule
const nextRun = parsedCron.nextRun();
// istanbul ignore if: should not happen
if (!nextRun) {
logger.warn(`Invalid cron schedule ${cron}. No next run is possible`);
return false;
}

if (
!parsedCron.fields.dayOfWeek.includes(
(now.weekday % 7) as DayOfTheWeekRange,
)
) {
// Weekdays mismatch
return false;
let nextDate = DateTime.fromJSDate(nextRun);
if (timezone) {
nextDate = nextDate.setZone(timezone);
RahulGautamSingh marked this conversation as resolved.
Show resolved Hide resolved
}

if (parsedCron.fields.month.indexOf(now.month as MonthRange) === -1) {
// Months mismatch
return false;
}

// Match
return true;
return (
nextDate.hour === now.hour &&
nextDate.day === now.day &&
nextDate.month === now.month
);
}

export function isScheduledNow(
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@
"clean-git-ref": "2.0.1",
"commander": "12.1.0",
"conventional-commits-detector": "1.0.3",
"cron-parser": "4.9.0",
"croner": "9.0.0",
"cronstrue": "2.51.0",
"deepmerge": "4.3.1",
"dequal": "2.0.3",
Expand Down
17 changes: 7 additions & 10 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.