index.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. 'use strict';
  2. export class TimeoutError extends Error {
  3. previous: Error | undefined;
  4. constructor(message: string, previousError?: Error) {
  5. super(message);
  6. this.name = "TimeoutError";
  7. this.previous = previousError;
  8. }
  9. }
  10. export type MatchOption =
  11. | string
  12. | RegExp
  13. | Error
  14. | Function;
  15. export interface Options {
  16. max: number;
  17. timeout?: number | undefined;
  18. match?: MatchOption[] | MatchOption | undefined;
  19. backoffBase?: number | undefined;
  20. backoffExponent?: number | undefined;
  21. report?: ((message: string, obj: CoercedOptions, err?: any) => void) | undefined;
  22. name?: string | undefined;
  23. }
  24. type CoercedOptions = {
  25. $current: number;
  26. max: number;
  27. timeout?: number | undefined;
  28. match: MatchOption[];
  29. backoffBase: number;
  30. backoffExponent: number;
  31. report?: ((message: string, obj: CoercedOptions, err?: any) => void) | undefined;
  32. name?: string | undefined;
  33. }
  34. type MaybePromise<T> = PromiseLike<T> | T;
  35. type RetryCallback<T> = ({ current }: { current: CoercedOptions['$current'] }) => MaybePromise<T>;
  36. function matches(match : MatchOption, err: Error) {
  37. if (typeof match === 'function') {
  38. try {
  39. if (err instanceof match) return true;
  40. } catch (_) {
  41. return !!match(err);
  42. }
  43. }
  44. if (match === err.toString()) return true;
  45. if (match === err.message) return true;
  46. return match instanceof RegExp
  47. && (match.test(err.message) || match.test(err.toString()));
  48. }
  49. export function retryAsPromised<T>(callback : RetryCallback<T>, optionsInput : Options | number | CoercedOptions) : Promise<T> {
  50. if (!callback || !optionsInput) {
  51. throw new Error(
  52. 'retry-as-promised must be passed a callback and a options set'
  53. );
  54. }
  55. optionsInput = (typeof optionsInput === "number" ? {max: optionsInput} : optionsInput) as Options | CoercedOptions;
  56. const options : CoercedOptions = {
  57. $current: "$current" in optionsInput ? optionsInput.$current : 1,
  58. max: optionsInput.max,
  59. timeout: optionsInput.timeout || undefined,
  60. match: optionsInput.match ? Array.isArray(optionsInput.match) ? optionsInput.match : [optionsInput.match] : [],
  61. backoffBase: optionsInput.backoffBase === undefined ? 100 : optionsInput.backoffBase,
  62. backoffExponent: optionsInput.backoffExponent || 1.1,
  63. report: optionsInput.report,
  64. name: optionsInput.name || callback.name || 'unknown'
  65. };
  66. if (options.match && !Array.isArray(options.match)) options.match = [options.match];
  67. if (options.report) options.report('Trying ' + options.name + ' #' + options.$current + ' at ' + new Date().toLocaleTimeString(), options);
  68. return new Promise(function(resolve, reject) {
  69. let timeout : NodeJS.Timeout | undefined;
  70. let backoffTimeout : NodeJS.Timeout | undefined;
  71. let lastError : Error | undefined;
  72. if (options.timeout) {
  73. timeout = setTimeout(function() {
  74. if (backoffTimeout) clearTimeout(backoffTimeout);
  75. reject(new TimeoutError(options.name + ' timed out', lastError));
  76. }, options.timeout);
  77. }
  78. Promise.resolve(callback({ current: options.$current }))
  79. .then(resolve)
  80. .then(function() {
  81. if (timeout) clearTimeout(timeout);
  82. if (backoffTimeout) clearTimeout(backoffTimeout);
  83. })
  84. .catch(function(err) {
  85. if (timeout) clearTimeout(timeout);
  86. if (backoffTimeout) clearTimeout(backoffTimeout);
  87. lastError = err;
  88. if (options.report) options.report((err && err.toString()) || err, options, err);
  89. // Should not retry if max has been reached
  90. var shouldRetry = options.$current! < options.max;
  91. if (!shouldRetry) return reject(err);
  92. shouldRetry = options.match.length === 0 || options.match.some(function (match) {
  93. return matches(match, err)
  94. });
  95. if (!shouldRetry) return reject(err);
  96. var retryDelay = options.backoffBase * Math.pow(options.backoffExponent, options.$current - 1);
  97. // Do some accounting
  98. options.$current++;
  99. if (options.report) options.report(`Retrying ${options.name} (${options.$current})`, options);
  100. if (retryDelay) {
  101. // Use backoff function to ease retry rate
  102. if (options.report) options.report(`Delaying retry of ${options.name} by ${retryDelay}`, options);
  103. backoffTimeout = setTimeout(function() {
  104. retryAsPromised(callback, options)
  105. .then(resolve)
  106. .catch(reject);
  107. }, retryDelay);
  108. } else {
  109. retryAsPromised(callback, options)
  110. .then(resolve)
  111. .catch(reject);
  112. }
  113. });
  114. });
  115. };
  116. export default retryAsPromised;