backoff.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. "use strict";
  2. /*!
  3. * Copyright 2017 Google Inc. All Rights Reserved.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. Object.defineProperty(exports, "__esModule", { value: true });
  18. exports.ExponentialBackoff = exports.delayExecution = exports.MAX_RETRY_ATTEMPTS = exports.DEFAULT_BACKOFF_FACTOR = exports.DEFAULT_BACKOFF_MAX_DELAY_MS = exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS = void 0;
  19. exports.setTimeoutHandler = setTimeoutHandler;
  20. const logger_1 = require("./logger");
  21. /*
  22. * @module firestore/backoff
  23. * @private
  24. * @internal
  25. *
  26. * Contains backoff logic to facilitate RPC error handling. This class derives
  27. * its implementation from the Firestore Mobile Web Client.
  28. *
  29. * @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts
  30. */
  31. /*!
  32. * The default initial backoff time in milliseconds after an error.
  33. * Set to 1s according to https://cloud.google.com/apis/design/errors.
  34. */
  35. exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
  36. /*!
  37. * The default maximum backoff time in milliseconds.
  38. */
  39. exports.DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
  40. /*!
  41. * The default factor to increase the backup by after each failed attempt.
  42. */
  43. exports.DEFAULT_BACKOFF_FACTOR = 1.5;
  44. /*!
  45. * The default jitter to distribute the backoff attempts by (0 means no
  46. * randomization, 1.0 means +/-50% randomization).
  47. */
  48. const DEFAULT_JITTER_FACTOR = 1.0;
  49. /*!
  50. * The maximum number of retries that will be attempted by backoff
  51. * before stopping all retry attempts.
  52. */
  53. exports.MAX_RETRY_ATTEMPTS = 10;
  54. /*!
  55. * The timeout handler used by `ExponentialBackoff` and `BulkWriter`.
  56. */
  57. exports.delayExecution = setTimeout;
  58. /**
  59. * Allows overriding of the timeout handler used by the exponential backoff
  60. * implementation. If not invoked, we default to `setTimeout()`.
  61. *
  62. * Used only in testing.
  63. *
  64. * @private
  65. * @internal
  66. * @param {function} handler A handler than matches the API of `setTimeout()`.
  67. */
  68. function setTimeoutHandler(handler) {
  69. exports.delayExecution = (f, ms) => {
  70. handler(f, ms);
  71. const timeout = {
  72. hasRef: () => {
  73. throw new Error('For tests only. Not Implemented');
  74. },
  75. ref: () => {
  76. throw new Error('For tests only. Not Implemented');
  77. },
  78. refresh: () => {
  79. throw new Error('For tests only. Not Implemented');
  80. },
  81. unref: () => {
  82. throw new Error('For tests only. Not Implemented');
  83. },
  84. [Symbol.toPrimitive]: () => {
  85. throw new Error('For tests only. Not Implemented');
  86. },
  87. };
  88. // `NodeJS.Timeout` type signature change:
  89. // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/66176/files#diff-e838d0ace9cd5f6516bacfbd3ad00d02cd37bd60f9993ce6223f52d889a1fdbaR122-R126
  90. //
  91. // Adding `[Symbol.dispose](): void;` cannot be done on older versions of
  92. // NodeJS. So we simply cast to `NodeJS.Timeout`.
  93. return timeout;
  94. };
  95. }
  96. /**
  97. * A helper for running delayed tasks following an exponential backoff curve
  98. * between attempts.
  99. *
  100. * Each delay is made up of a "base" delay which follows the exponential
  101. * backoff curve, and a "jitter" (+/- 50% by default) that is calculated and
  102. * added to the base delay. This prevents clients from accidentally
  103. * synchronizing their delays causing spikes of load to the backend.
  104. *
  105. * @private
  106. * @internal
  107. */
  108. class ExponentialBackoff {
  109. constructor(options = {}) {
  110. /**
  111. * The number of retries that has been attempted.
  112. *
  113. * @private
  114. * @internal
  115. */
  116. this._retryCount = 0;
  117. /**
  118. * The backoff delay of the current attempt.
  119. *
  120. * @private
  121. * @internal
  122. */
  123. this.currentBaseMs = 0;
  124. /**
  125. * Whether we are currently waiting for backoff to complete.
  126. *
  127. * @private
  128. * @internal
  129. */
  130. this.awaitingBackoffCompletion = false;
  131. this.initialDelayMs =
  132. options.initialDelayMs !== undefined
  133. ? options.initialDelayMs
  134. : exports.DEFAULT_BACKOFF_INITIAL_DELAY_MS;
  135. this.backoffFactor =
  136. options.backoffFactor !== undefined
  137. ? options.backoffFactor
  138. : exports.DEFAULT_BACKOFF_FACTOR;
  139. this.maxDelayMs =
  140. options.maxDelayMs !== undefined
  141. ? options.maxDelayMs
  142. : exports.DEFAULT_BACKOFF_MAX_DELAY_MS;
  143. this.jitterFactor =
  144. options.jitterFactor !== undefined
  145. ? options.jitterFactor
  146. : DEFAULT_JITTER_FACTOR;
  147. }
  148. /**
  149. * Resets the backoff delay and retry count.
  150. *
  151. * The very next backoffAndWait() will have no delay. If it is called again
  152. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  153. * subsequent ones will increase according to the backoffFactor.
  154. *
  155. * @private
  156. * @internal
  157. */
  158. reset() {
  159. this._retryCount = 0;
  160. this.currentBaseMs = 0;
  161. }
  162. /**
  163. * Resets the backoff delay to the maximum delay (e.g. for use after a
  164. * RESOURCE_EXHAUSTED error).
  165. *
  166. * @private
  167. * @internal
  168. */
  169. resetToMax() {
  170. this.currentBaseMs = this.maxDelayMs;
  171. }
  172. /**
  173. * Returns a promise that resolves after currentDelayMs, and increases the
  174. * delay for any subsequent attempts.
  175. *
  176. * @return A Promise that resolves when the current delay elapsed.
  177. * @private
  178. * @internal
  179. */
  180. backoffAndWait() {
  181. if (this.awaitingBackoffCompletion) {
  182. return Promise.reject(new Error('A backoff operation is already in progress.'));
  183. }
  184. if (this.retryCount > exports.MAX_RETRY_ATTEMPTS) {
  185. return Promise.reject(new Error('Exceeded maximum number of retries allowed.'));
  186. }
  187. // First schedule using the current base (which may be 0 and should be
  188. // honored as such).
  189. const delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();
  190. if (this.currentBaseMs > 0) {
  191. (0, logger_1.logger)('ExponentialBackoff.backoffAndWait', null, `Backing off for ${delayWithJitterMs} ms ` +
  192. `(base delay: ${this.currentBaseMs} ms)`);
  193. }
  194. // Apply backoff factor to determine next delay and ensure it is within
  195. // bounds.
  196. this.currentBaseMs *= this.backoffFactor;
  197. this.currentBaseMs = Math.max(this.currentBaseMs, this.initialDelayMs);
  198. this.currentBaseMs = Math.min(this.currentBaseMs, this.maxDelayMs);
  199. this._retryCount += 1;
  200. return new Promise(resolve => {
  201. this.awaitingBackoffCompletion = true;
  202. (0, exports.delayExecution)(() => {
  203. this.awaitingBackoffCompletion = false;
  204. resolve();
  205. }, delayWithJitterMs);
  206. });
  207. }
  208. // Visible for testing.
  209. get retryCount() {
  210. return this._retryCount;
  211. }
  212. /**
  213. * Returns a randomized "jitter" delay based on the current base and jitter
  214. * factor.
  215. *
  216. * @returns {number} The jitter to apply based on the current delay.
  217. * @private
  218. * @internal
  219. */
  220. jitterDelayMs() {
  221. return (Math.random() - 0.5) * this.jitterFactor * this.currentBaseMs;
  222. }
  223. }
  224. exports.ExponentialBackoff = ExponentialBackoff;
  225. //# sourceMappingURL=backoff.js.map