Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1556: Reduce CPU usage on idle consumers (avoid infinite setTimeout loop with no inflight requests) #1667

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions src/network/requestQueue/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const PRIVATE = {
}

const REQUEST_QUEUE_EMPTY = 'requestQueueEmpty'
const CHECK_PENDING_REQUESTS_INTERVAL = 10

module.exports = class RequestQueue extends EventEmitter {
/**
Expand Down Expand Up @@ -304,20 +303,26 @@ module.exports = class RequestQueue extends EventEmitter {
* the pending request queue eventually.
*/
scheduleCheckPendingRequests() {
// If we're throttled: Schedule checkPendingRequests when the throttle
// should be resolved. If there is already something scheduled we assume that that
// If there is already something scheduled we assume that that
// will be fine, and potentially fix up a new timeout if needed at that time.
if (this.throttleCheckTimeoutId) {
return
}

if (this.pending.length === 0) {
return
}

// If we're throttled: Schedule checkPendingRequests when the throttle
// should be resolved.
const timeUntilUnthrottled = this.throttledUntil - Date.now()
// 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.
let scheduleAt = this.throttledUntil - Date.now()
if (!this.throttleCheckTimeoutId) {
if (this.pending.length > 0) {
scheduleAt = scheduleAt > 0 ? scheduleAt : CHECK_PENDING_REQUESTS_INTERVAL
}
this.throttleCheckTimeoutId = setTimeout(() => {
this.throttleCheckTimeoutId = null
this.checkPendingRequests()
}, scheduleAt)
}
const scheduleAt = Math.max(timeUntilUnthrottled, 0)

this.throttleCheckTimeoutId = setTimeout(() => {
this.throttleCheckTimeoutId = null
this.checkPendingRequests()
}, scheduleAt)
}
}