From d807128800549d16eab9fd73e276a0305594a40d Mon Sep 17 00:00:00 2001 From: Oj Date: Sat, 12 Feb 2022 11:17:04 +0000 Subject: [PATCH] [Backoff] Rewrite to clean up a lot --- src/utils/Backoff.js | 45 ++++++++++++++++++-------------------------- 1 file changed, 18 insertions(+), 27 deletions(-) diff --git a/src/utils/Backoff.js b/src/utils/Backoff.js index 460f244..f81087f 100644 --- a/src/utils/Backoff.js +++ b/src/utils/Backoff.js @@ -1,34 +1,18 @@ module.exports = class Backoff { // Internal library / utility for a class to retry a callback with delays, etc. - constructor(min = 500, max = null) { - this._timeoutId = null; // Setup internal vars - this.fails = 0; - - this.min = min; // Setup args - this.max = max ?? (min * 10); - - this.current = min; - } - - get pending() { // If timeout currently set / waiting - return this._timeoutId !== null; - } - - succeed() { // Reset state on succeed - this.current = this.min; - this.fails = 0; - - this.cancel(); + constructor(min = 500, max = (min * 10)) { + Object.assign(this, { min, max }); + this.reset(); + + this.pending = () => this._timeoutId != null; // If timeout currently set / waiting } fail(callback) { // On fail, wait and callback - const delay = this.current * 2; - - this.current = Math.min(this.current + delay, this.max); + this.current = Math.min(this.current + (this.current * 2), this.max); - this.fails += 1; // Bump fails + this.fails++; // Bump fails if (!callback) return this.current; // No callback given, skip rest of this - if (this._timeoutId !== null) throw new Error('Callback already pending call'); // Timeout already set as waiting for another callback to call, throw error + if (this._timeoutId != null) throw new Error(); // Timeout already set as waiting for another callback to call, throw error this._timeoutId = setTimeout(() => { // Set new timeout try { @@ -41,10 +25,17 @@ module.exports = class Backoff { // Internal library / utility for a class to re return this.current; } + succeed() { // Reset and cancel + this.reset(); + this.cancel(); + } + cancel() { // Cancel current timeout - if (this._timeoutId === null) return; // If no timeout already, do nothing + this._timeoutId = clearTimeout(this._timeoutId); // Stop timeout + } - clearTimeout(this._timeoutId); // Stop timeout - this_timeoutId = null; // Stop tracking timeout internally as it's been executed + reset() { // Reset internal state + this.current = this.min; + this.fails = 0; } }; \ No newline at end of file