backoffs.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Backoffs = void 0;
  4. class Backoffs {
  5. static normalize(backoff) {
  6. if (Number.isFinite(backoff)) {
  7. return {
  8. type: 'fixed',
  9. delay: backoff,
  10. };
  11. }
  12. else if (backoff) {
  13. return backoff;
  14. }
  15. }
  16. static calculate(backoff, attemptsMade, err, job, customStrategy) {
  17. if (backoff) {
  18. const strategy = lookupStrategy(backoff, customStrategy);
  19. return strategy(attemptsMade, backoff.type, err, job);
  20. }
  21. }
  22. }
  23. exports.Backoffs = Backoffs;
  24. Backoffs.builtinStrategies = {
  25. fixed: function (delay, jitter = 0) {
  26. return function () {
  27. if (jitter > 0) {
  28. const minDelay = delay * (1 - jitter);
  29. return Math.floor(Math.random() * delay * jitter + minDelay);
  30. }
  31. else {
  32. return delay;
  33. }
  34. };
  35. },
  36. exponential: function (delay, jitter = 0) {
  37. return function (attemptsMade) {
  38. if (jitter > 0) {
  39. const maxDelay = Math.round(Math.pow(2, attemptsMade - 1) * delay);
  40. const minDelay = maxDelay * (1 - jitter);
  41. return Math.floor(Math.random() * maxDelay * jitter + minDelay);
  42. }
  43. else {
  44. return Math.round(Math.pow(2, attemptsMade - 1) * delay);
  45. }
  46. };
  47. },
  48. };
  49. function lookupStrategy(backoff, customStrategy) {
  50. if (backoff.type in Backoffs.builtinStrategies) {
  51. return Backoffs.builtinStrategies[backoff.type](backoff.delay, backoff.jitter);
  52. }
  53. else if (customStrategy) {
  54. return customStrategy;
  55. }
  56. else {
  57. throw new Error(`Unknown backoff strategy ${backoff.type}.
  58. If a custom backoff strategy is used, specify it when the queue is created.`);
  59. }
  60. }
  61. //# sourceMappingURL=backoffs.js.map