Skip to content

Commit

Permalink
Initial token bucket implementation (#1314)
Browse files Browse the repository at this point in the history
  • Loading branch information
megawac committed Nov 9, 2016
1 parent 9cc01fd commit ec2a60a
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/internal/TokenBucket.js
@@ -0,0 +1,37 @@
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 when the rate limit is not exceeded.
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())();
}
}

0 comments on commit ec2a60a

Please sign in to comment.