cron.js 2.7 KB

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