Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial token bucket implementation (#1314)
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import DLL from './DoublyLinkedList'; | ||
|
||
/** | ||
* An internal implementation of [Token Bucket](https://en.wikipedia.org/wiki/Token_bucket) | ||
* for rate-limiting/traffic shaping. | ||
* | ||
* @param {Number} bucketSize - the maximum number of items (inclusive) which can be queued in | ||
* a interval of time. | ||
* @param {Number} interval - the period in miliseconds to stop tracking a sent item | ||
*/ | ||
export function TokenBucket(bucketSize, interval) { | ||
this.bucketSize = bucketSize; | ||
this.interval = interval; | ||
this.queue = new DLL(); | ||
this.queued = 0; // Number of items sent + size of queue | ||
} | ||
|
||
/** | ||
* Enqueue an operation to be executed | ||
*/ | ||
TokenBucket.prototype.enqueue = function(operation) { | ||
this.queued++; | ||
if (this.queued <= this.bucketSize) { | ||
operation(); | ||
} else { | ||
this.queue.push(operation); | ||
} | ||
|
||
// after interval, decrement the queued count and call a queued operation (if bucket is full) | ||
setTimeout(onIntervalComplete, this.interval, this); | ||
} | ||
|
||
function onIntervalComplete(bucket) { | ||
bucket.queued--; | ||
if (bucket.queue.length > 0) { | ||
// call first queued operation | ||
(bucket.queue.shift())(); | ||
} | ||
} |
247b892
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@aearly thoughts on something like this for rate limiting?
/cc @hargasinski
247b892
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, I completely lost this notification in a slew of emails. LGTM. 👍
247b892
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this makes sense to implement in async proper any more.