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(node): Instrumentation for node-cron library #9904

Merged
merged 17 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
50 changes: 50 additions & 0 deletions packages/node/src/cron/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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'],
];

/**
* Replaces names in cron expressions
*/
export function replaceCronNames(cronExpression: string): string {
return replacements.reduce(
(acc, [name, replacement]) => acc.replace(new RegExp(name, 'gi'), replacement),
cronExpression,
);
}
61 changes: 61 additions & 0 deletions packages/node/src/cron/node-cron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { withMonitor } from '@sentry/core';
import { replaceCronNames } from './common';

export interface NodeCronOptions {
name?: string;
timezone?: string;
}

export interface NodeCron {
schedule: (cronExpression: string, callback: () => void, options?: NodeCronOptions) => unknown;
}

/**
* Wraps the `node-cron` library with check-in monitoring.
*
* ```ts
* import * as Sentry from "@sentry/node";
* import cron from "node-cron";
*
* const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron);
*
* cronWithCheckIn.schedule(
* "* * * * *",
* () => {
* console.log("running a task every minute");
* },
* { name: "my-cron-job" },
* );
* ```
*/
export function instrumentNodeCron<T>(lib: Partial<NodeCron> & T): T {
return new Proxy(lib, {
get(target, prop: keyof NodeCron) {
if (prop === 'schedule' && target.schedule) {
// When 'get' is called for schedule, return a proxied version of the schedule function
return new Proxy(target.schedule, {
apply(target, thisArg, argArray: Parameters<NodeCron['schedule']>) {
const [expression, _, options] = argArray;

if (!options?.name) {
throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');
}

return withMonitor(
options.name,
() => {
return target.apply(thisArg, argArray);
},
{
schedule: { type: 'crontab', value: replaceCronNames(expression) },
timezone: options?.timezone,
},
);
},
});
} else {
return target[prop];
}
},
});
}
7 changes: 7 additions & 0 deletions packages/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,10 @@ const INTEGRATIONS = {
export { INTEGRATIONS as Integrations, Handlers };

export { hapiErrorPlugin } from './integrations/hapi';

import { instrumentNodeCron } from './cron/node-cron';

/** Methods to instrument cron libraries for Sentry check-ins */
export const cron = {
timfish marked this conversation as resolved.
Show resolved Hide resolved
instrumentNodeCron,
};
61 changes: 61 additions & 0 deletions packages/node/test/cron.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import * as SentryCore from '@sentry/core';

import { cron } from '../src';
import type { NodeCron, NodeCronOptions } from '../src/cron/node-cron';

describe('cron', () => {
let withMonitorSpy: jest.SpyInstance;

beforeEach(() => {
withMonitorSpy = jest.spyOn(SentryCore, 'withMonitor');
});

afterEach(() => {
jest.restoreAllMocks();
});

describe('node-cron', () => {
test('calls withMonitor', done => {
expect.assertions(5);

const nodeCron: NodeCron = {
schedule: (expression: string, callback: () => void, options?: NodeCronOptions): unknown => {
expect(expression).toBe('* * * Jan,Sep Sun');
expect(callback).toBeInstanceOf(Function);
expect(options?.name).toBe('my-cron-job');
return callback();
timfish marked this conversation as resolved.
Show resolved Hide resolved
},
};

const cronWithCheckIn = cron.instrumentNodeCron(nodeCron);

cronWithCheckIn.schedule(
'* * * Jan,Sep Sun',
() => {
expect(withMonitorSpy).toHaveBeenCalledTimes(1);
expect(withMonitorSpy).toHaveBeenLastCalledWith('my-cron-job', expect.anything(), {
schedule: { type: 'crontab', value: '* * * 1,9 0' },
});
done();
},
{ name: 'my-cron-job' },
);
});

test('throws without supplied name', () => {
const nodeCron: NodeCron = {
schedule: (): unknown => {
return undefined;
},
};

const cronWithCheckIn = cron.instrumentNodeCron(nodeCron);

expect(() => {
cronWithCheckIn.schedule('* * * * *', () => {
//
});
}).toThrowError('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');
});
});
});