backoffs.js 1.8 KB

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