cron.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { withMonitor } from '@sentry/core';
  2. import { replaceCronNames } from './common.js';
  3. const ERROR_TEXT = 'Automatic instrumentation of CronJob only supports crontab string';
  4. /**
  5. * Instruments the `cron` library to send a check-in event to Sentry for each job execution.
  6. *
  7. * ```ts
  8. * import * as Sentry from '@sentry/node';
  9. * import { CronJob } from 'cron';
  10. *
  11. * const CronJobWithCheckIn = Sentry.cron.instrumentCron(CronJob, 'my-cron-job');
  12. *
  13. * // use the constructor
  14. * const job = new CronJobWithCheckIn('* * * * *', () => {
  15. * console.log('You will see this message every minute');
  16. * });
  17. *
  18. * // or from
  19. * const job = CronJobWithCheckIn.from({ cronTime: '* * * * *', onTick: () => {
  20. * console.log('You will see this message every minute');
  21. * });
  22. * ```
  23. */
  24. function instrumentCron(lib, monitorSlug) {
  25. let jobScheduled = false;
  26. return new Proxy(lib, {
  27. construct(target, args) {
  28. const [cronTime, onTick, onComplete, start, timeZone, ...rest] = args;
  29. if (typeof cronTime !== 'string') {
  30. throw new Error(ERROR_TEXT);
  31. }
  32. if (jobScheduled) {
  33. throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
  34. }
  35. jobScheduled = true;
  36. const cronString = replaceCronNames(cronTime);
  37. function monitoredTick(context, onComplete) {
  38. return withMonitor(
  39. monitorSlug,
  40. () => {
  41. return onTick(context, onComplete);
  42. },
  43. {
  44. schedule: { type: 'crontab', value: cronString },
  45. ...(timeZone ? { timeZone } : {}),
  46. },
  47. );
  48. }
  49. return new target(cronTime, monitoredTick, onComplete, start, timeZone, ...rest);
  50. },
  51. get(target, prop) {
  52. if (prop === 'from') {
  53. return (param) => {
  54. const { cronTime, onTick, timeZone } = param;
  55. if (typeof cronTime !== 'string') {
  56. throw new Error(ERROR_TEXT);
  57. }
  58. if (jobScheduled) {
  59. throw new Error(`A job named '${monitorSlug}' has already been scheduled`);
  60. }
  61. jobScheduled = true;
  62. const cronString = replaceCronNames(cronTime);
  63. param.onTick = (context, onComplete) => {
  64. return withMonitor(
  65. monitorSlug,
  66. () => {
  67. return onTick(context, onComplete);
  68. },
  69. {
  70. schedule: { type: 'crontab', value: cronString },
  71. ...(timeZone ? { timeZone } : {}),
  72. },
  73. );
  74. };
  75. return target.from(param);
  76. };
  77. } else {
  78. return target[prop];
  79. }
  80. },
  81. });
  82. }
  83. export { instrumentCron };
  84. //# sourceMappingURL=cron.js.map