diff --git a/src/network/requestQueue/index.js b/src/network/requestQueue/index.js index 8556667a4..076c19504 100644 --- a/src/network/requestQueue/index.js +++ b/src/network/requestQueue/index.js @@ -9,7 +9,6 @@ const PRIVATE = { } const REQUEST_QUEUE_EMPTY = 'requestQueueEmpty' -const CHECK_PENDING_REQUESTS_INTERVAL = 10 module.exports = class RequestQueue extends EventEmitter { /** @@ -56,6 +55,13 @@ module.exports = class RequestQueue extends EventEmitter { */ this.throttledUntil = -1 + /** + * Current timestamp when the throttling was set + * + * @type {number} + */ + this.throttleCurrentTimestamp = 0 + /** * Timeout id if we have scheduled a check for pending requests due to client-side throttling * @@ -105,7 +111,8 @@ module.exports = class RequestQueue extends EventEmitter { maybeThrottle(clientSideThrottleTime) { if (clientSideThrottleTime !== null && clientSideThrottleTime > 0) { this.logger.debug(`Client side throttling in effect for ${clientSideThrottleTime}ms`) - const minimumThrottledUntil = Date.now() + clientSideThrottleTime + this.throttleCurrentTimestamp = Date.now() + const minimumThrottledUntil = this.throttleCurrentTimestamp + clientSideThrottleTime this.throttledUntil = Math.max(minimumThrottledUntil, this.throttledUntil) } } @@ -309,12 +316,14 @@ module.exports = class RequestQueue extends EventEmitter { // will be fine, and potentially fix up a new timeout if needed at that time. // Note that if we're merely "overloaded" by having too many inflight requests // we will anyways check the queue when one of them gets fulfilled. - const timeUntilUnthrottled = this.throttledUntil - Date.now() - if (timeUntilUnthrottled >= 0 && !this.throttleCheckTimeoutId) { + const timeUntilUnthrottled = this.throttledUntil - this.throttleCurrentTimestamp + + if (timeUntilUnthrottled > 0 && !this.throttleCheckTimeoutId) { this.throttleCheckTimeoutId = setTimeout(() => { this.throttleCheckTimeoutId = null + this.throttleCurrentTimestamp = Date.now() this.checkPendingRequests() - }, Math.max(timeUntilUnthrottled, CHECK_PENDING_REQUESTS_INTERVAL)) + }, 0) } } } diff --git a/src/network/requestQueue/index.spec.js b/src/network/requestQueue/index.spec.js index b6e924183..dbfe0e28e 100644 --- a/src/network/requestQueue/index.spec.js +++ b/src/network/requestQueue/index.spec.js @@ -225,8 +225,7 @@ describe('Network > RequestQueue', () => { const before = Date.now() const clientSideThrottleTime = 1 requestQueue.maybeThrottle(clientSideThrottleTime) - - requestQueue.throttledUntil = Date.now() + clientSideThrottleTime + await sleep(clientSideThrottleTime) requestQueue.scheduleCheckPendingRequests() const sentAt = await sendDone