|
| 1 | +/** |
| 2 | + * Copyright (c) 2013 John Hurliman <jhurliman@jhurliman.org> |
| 3 | + * |
| 4 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 | + * of this software and associated documentation files (the "Software"), to deal |
| 6 | + * in the Software without restriction, including without limitation the rights |
| 7 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 8 | + * copies of the Software, and to permit persons to whom the Software is |
| 9 | + * furnished to do so, subject to the following conditions: |
| 10 | + * |
| 11 | + * The above copyright notice and this permission notice shall be included in |
| 12 | + * all copies or substantial portions of the Software. |
| 13 | + * |
| 14 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 19 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 20 | + * THE SOFTWARE. |
| 21 | + */ |
| 22 | + |
| 23 | + |
| 24 | +/** |
| 25 | + * A hierarchical token bucket for rate limiting. See |
| 26 | + * http://en.wikipedia.org/wiki/Token_bucket for more information. |
| 27 | + * |
| 28 | + * @param {Number} bucketSize Maximum number of tokens to hold in the bucket. |
| 29 | + * Also known as the burst rate. |
| 30 | + * @param {Number} tokensPerInterval Number of tokens to drip into the bucket |
| 31 | + * over the course of one interval. |
| 32 | + * @param {String|Number} interval The interval length in milliseconds, or as |
| 33 | + * one of the following strings: 'second', 'minute', 'hour', day'. |
| 34 | + * @param {TokenBucket} parentBucket Optional. A token bucket that will act as |
| 35 | + * the parent of this bucket. |
| 36 | + */ |
| 37 | +var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) { |
| 38 | + this.bucketSize = bucketSize; |
| 39 | + this.tokensPerInterval = tokensPerInterval; |
| 40 | + |
| 41 | + if (typeof interval === 'string') { |
| 42 | + switch (interval) { |
| 43 | + case 'sec': case 'second': |
| 44 | + this.interval = 1000; break; |
| 45 | + case 'min': case 'minute': |
| 46 | + this.interval = 1000 * 60; break; |
| 47 | + case 'hr': case 'hour': |
| 48 | + this.interval = 1000 * 60 * 60; break; |
| 49 | + case 'day': |
| 50 | + this.interval = 1000 * 60 * 60 * 24; break; |
| 51 | + } |
| 52 | + } else { |
| 53 | + this.interval = interval; |
| 54 | + } |
| 55 | + |
| 56 | + this.parentBucket = parentBucket; |
| 57 | + this.content = 0; |
| 58 | + this.lastDrip = +new Date(); |
| 59 | +}; |
| 60 | + |
| 61 | +TokenBucket.prototype = { |
| 62 | + bucketSize: 1, |
| 63 | + tokensPerInterval: 1, |
| 64 | + interval: 1000, |
| 65 | + parentBucket: null, |
| 66 | + content: 0, |
| 67 | + lastDrip: 0, |
| 68 | + |
| 69 | + /** |
| 70 | + * Remove the requested number of tokens and fire the given callback. If the |
| 71 | + * bucket (and any parent buckets) contains enough tokens this will happen |
| 72 | + * immediately. Otherwise, the removal and callback will happen when enough |
| 73 | + * tokens become available. |
| 74 | + * @param {Number} count The number of tokens to remove. |
| 75 | + * @param {Function} callback(err, remainingTokens) |
| 76 | + * @returns {Boolean} True if the callback was fired immediately, otherwise |
| 77 | + * false. |
| 78 | + */ |
| 79 | + removeTokens: function(count, callback) { |
| 80 | + var self = this; |
| 81 | + |
| 82 | + // Is this an infinite size bucket? |
| 83 | + if (!this.bucketSize) { |
| 84 | + callback(null, count, Number.POSITIVE_INFINITY); |
| 85 | + return true; |
| 86 | + } |
| 87 | + |
| 88 | + // Make sure the bucket can hold the requested number of tokens |
| 89 | + if (count > this.bucketSize) { |
| 90 | + callback('Requested tokens ' + count + ' exceeds bucket size ' + |
| 91 | + this.bucketSize, null); |
| 92 | + return false; |
| 93 | + } |
| 94 | + |
| 95 | + // Drip new tokens into this bucket |
| 96 | + this.drip(); |
| 97 | + |
| 98 | + // If we don't have enough tokens in this bucket, come back later |
| 99 | + if (count > this.content) { |
| 100 | + // How long do we need to wait to make up the difference in tokens? |
| 101 | + var waitInterval = Math.ceil( |
| 102 | + (count - this.content) * (this.interval / this.tokensPerInterval)); |
| 103 | + setTimeout(function() { self.removeTokens(count, callback); }, waitInterval); |
| 104 | + return false; |
| 105 | + } |
| 106 | + |
| 107 | + if (this.parentBucket) { |
| 108 | + // Remove the requested from the parent bucket first |
| 109 | + return this.parentBucket.removeTokens(count, function(err, remainingTokens) { |
| 110 | + if (err) return callback(err, null); |
| 111 | + |
| 112 | + // Tokens were removed from the parent bucket, now remove them from |
| 113 | + // this bucket and fire the callback. Note that we look at the current |
| 114 | + // bucket and parent bucket's remaining tokens and return the smaller |
| 115 | + // of the two values |
| 116 | + self.content -= count; |
| 117 | + callback(null, Math.min(remainingTokens, self.content)); |
| 118 | + }); |
| 119 | + } else { |
| 120 | + // Remove the requested tokens from this bucket and fire the callback |
| 121 | + this.content -= count; |
| 122 | + callback(null, this.content); |
| 123 | + return true; |
| 124 | + } |
| 125 | + }, |
| 126 | + |
| 127 | + /** |
| 128 | + * Add any new tokens to the bucket since the last drip. |
| 129 | + * @returns {Boolean} True if new tokens were added, otherwise false. |
| 130 | + */ |
| 131 | + drip: function() { |
| 132 | + if (!this.tokensPerInterval) { |
| 133 | + this.content = this.bucketSize; |
| 134 | + return; |
| 135 | + } |
| 136 | + |
| 137 | + var now = +new Date(); |
| 138 | + var deltaMS = Math.max(now - this.lastDrip, 0); |
| 139 | + this.lastDrip = now; |
| 140 | + |
| 141 | + var dripAmount = deltaMS * (this.tokensPerInterval / this.interval); |
| 142 | + this.content = Math.min(this.content + dripAmount, this.bucketSize); |
| 143 | + } |
| 144 | +}; |
| 145 | + |
| 146 | +module.exports = TokenBucket; |
0 commit comments