retry-busy.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. // note: max backoff is the maximum that any *single* backoff will do
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.retryBusySync = exports.retryBusy = exports.codes = exports.MAXRETRIES = exports.RATE = exports.MAXBACKOFF = void 0;
  5. exports.MAXBACKOFF = 200;
  6. exports.RATE = 1.2;
  7. exports.MAXRETRIES = 10;
  8. exports.codes = new Set(['EMFILE', 'ENFILE', 'EBUSY']);
  9. const retryBusy = (fn) => {
  10. const method = async (path, opt, backoff = 1, total = 0) => {
  11. const mbo = opt.maxBackoff || exports.MAXBACKOFF;
  12. const rate = opt.backoff || exports.RATE;
  13. const max = opt.maxRetries || exports.MAXRETRIES;
  14. let retries = 0;
  15. while (true) {
  16. try {
  17. return await fn(path);
  18. }
  19. catch (er) {
  20. const fer = er;
  21. if (fer?.path === path && fer?.code && exports.codes.has(fer.code)) {
  22. backoff = Math.ceil(backoff * rate);
  23. total = backoff + total;
  24. if (total < mbo) {
  25. return new Promise((res, rej) => {
  26. setTimeout(() => {
  27. method(path, opt, backoff, total).then(res, rej);
  28. }, backoff);
  29. });
  30. }
  31. if (retries < max) {
  32. retries++;
  33. continue;
  34. }
  35. }
  36. throw er;
  37. }
  38. }
  39. };
  40. return method;
  41. };
  42. exports.retryBusy = retryBusy;
  43. // just retries, no async so no backoff
  44. const retryBusySync = (fn) => {
  45. const method = (path, opt) => {
  46. const max = opt.maxRetries || exports.MAXRETRIES;
  47. let retries = 0;
  48. while (true) {
  49. try {
  50. return fn(path);
  51. }
  52. catch (er) {
  53. const fer = er;
  54. if (fer?.path === path &&
  55. fer?.code &&
  56. exports.codes.has(fer.code) &&
  57. retries < max) {
  58. retries++;
  59. continue;
  60. }
  61. throw er;
  62. }
  63. }
  64. };
  65. return method;
  66. };
  67. exports.retryBusySync = retryBusySync;
  68. //# sourceMappingURL=retry-busy.js.map