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

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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 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
27 changes: 27 additions & 0 deletions lib/config/migrations/custom/schedule-migration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,31 @@ describe('config/migrations/custom/schedule-migration', () => {
false,
);
});

it('migrate cron schdeule with 4 space separated parts', () => {
expect(ScheduleMigration).toMigrate(
{
schedule: [
'* * * *',
'* * * 6#1',
'* * * 11',
'* 2 31 11',
'2 3 1 11',
'* * 2 5',
'* * * 59',
],
} as any,
{
schedule: [
'* * * * *',
'* * * * 6#1',
'* * * 11 *',
'* 2 31 11 *',
'2 3 1 11',
'* * 2 5 *',
'* * * 59',
],
} as any,
);
});
});
28 changes: 28 additions & 0 deletions lib/config/migrations/custom/schedule-migration.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import later from '@breejs/later';
import is from '@sindresorhus/is';
import { CronPattern } from 'croner';
import { regEx } from '../../../util/regex';
import { AbstractMigration } from '../base/abstract-migration';

Expand Down Expand Up @@ -85,6 +86,7 @@ export class ScheduleMigration extends AbstractMigration {
if (schedules[i].endsWith('days')) {
schedules[i] = schedules[i].replace('days', 'day');
}
schedules[i] = massageCronSchedule(schedules[i]);
RahulGautamSingh marked this conversation as resolved.
Show resolved Hide resolved
}
if (is.string(value) && schedules.length === 1) {
this.rewrite(schedules[0]);
Expand All @@ -94,3 +96,29 @@ export class ScheduleMigration extends AbstractMigration {
}
}
}

function massageCronSchedule(schedule: string): string {
const parts = schedule.split(' ');
if (parts.length === 4 && parts[0] === '*') {
const addAtBack = parts.join(' ') + ' *';
const addAtFront = '* ' + parts.join(' ');
if (parseCron(addAtBack)) {
return addAtBack;
} else if (parseCron(addAtFront)) {
return addAtFront;
} else {
return schedule;
}
}

return schedule;
}

function parseCron(sch: string): boolean {
try {
new CronPattern(sch);
return true;
} catch {
return false;
}
}
78 changes: 77 additions & 1 deletion lib/workers/repository/update/branch/schedule.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import cronstrue from 'cronstrue';
import { logger } from '../../../../../test/util';
import type { RenovateConfig } from '../../../../config/types';
import * as schedule from './schedule';

Expand Down Expand Up @@ -109,7 +110,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 +270,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 +329,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 Expand Up @@ -407,6 +472,17 @@ describe('workers/repository/update/branch/schedule', () => {
expect(schedule.isScheduledNow(config)).toBe(expected);
});
});

it('logs warning if cron schedule is invalid', () => {
config.schedule = ['* * * *'];
expect(schedule.isScheduledNow(config)).toBeTrue();
expect(logger.logger.warn).toHaveBeenCalledWith(
{
message: `CronPattern: invalid configuration format ('* * * *'), exactly five or six space separated parts are required.`,
},
'Cron schedule * * * * is invalid.',
);
});
});

describe('log cron schedules', () => {
Expand Down
75 changes: 32 additions & 43 deletions lib/workers/repository/update/branch/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,27 @@
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 });
} catch {
return new CronPattern(scheduleText);
} catch (err) {
logger.warn(
{ message: err.message },
`Cron schedule ${scheduleText} is invalid.`,
);
return undefined;
}
}
Expand Down Expand Up @@ -55,7 +49,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 +93,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 false;
}

if (
!parsedCron.fields.dayOfWeek.includes(
(now.weekday % 7) as DayOfTheWeekRange,
)
) {
// Weekdays 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.month.indexOf(now.month as MonthRange) === -1) {
// Months mismatch
return false;
let nextDate: DateTime = DateTime.fromJSDate(nextRun);
if (timezone) {
nextDate = nextDate.setZone(timezone);
RahulGautamSingh marked this conversation as resolved.
Show resolved Hide resolved
}

// 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.