diff --git a/changelog b/changelog index 89daae4f..05fa7722 100644 --- a/changelog +++ b/changelog @@ -1,3 +1,10 @@ +Fri Sep 6 15:51 2013 CDT + * lib/utilities.js: Tweak the throttle code for rate limiters to fix + incorrect behavior of the burst cap after the cooldown period has + been passed + * tests/rateLimiter.js: Write a couple quick test cases to ensure that + rate limiting is handled properly + Thu Sep 5 22:52 2013 CDT * www/assets/js/callbacks.js: Disable the channel registration button and change its text while a registration attempt is being processed diff --git a/lib/utilities.js b/lib/utilities.js index bff14a72..6e4f3ac9 100644 --- a/lib/utilities.js +++ b/lib/utilities.js @@ -76,16 +76,16 @@ module.exports = { if (isNaN(cooldown)) cooldown = burst / sustained; - // Haven't reached burst cap yet, allow - if (this.count < burst) { - this.count++; + // Cooled down, allow and clear buffer + if (this.lastTime < Date.now() - cooldown*1000) { + this.count = 1; this.lastTime = Date.now(); return false; } - // Cooled down, allow and clear buffer - if (this.lastTime < Date.now() - cooldown*1000) { - this.count = 0; + // Haven't reached burst cap yet, allow + if (this.count < burst) { + this.count++; this.lastTime = Date.now(); return false; } diff --git a/tests/rateLimiter.js b/tests/rateLimiter.js new file mode 100644 index 00000000..5283b673 --- /dev/null +++ b/tests/rateLimiter.js @@ -0,0 +1,52 @@ +var $util = require('../lib/utilities.js'); + +function testBurst() { + var lim = $util.newRateLimiter(); + var params = { + burst: 10, + sustained: 2 + }; + + for (var i = 0; i < 10; i++) { + if (lim.throttle(params)) { + console.log("[FAIL] Burst: Unexpected throttle"); + return; + } + } + + if (!lim.throttle(params)) { + console.log("[FAIL] Burst: didn't throttle after exceeding burst amount"); + return; + } + + console.log("[PASS] Burst"); +} + +function testBurstAndWait() { + var lim = $util.newRateLimiter(); + var params = { + burst: 10, + sustained: 2 + }; + + for (var i = 0; i < 9; i++) { + if (lim.throttle(params)) { + console.log("[FAIL] Burst & Wait: Unexpected throttle"); + return; + } + } + + // Wait a while and try some more + setTimeout(function () { + for (var i = 9; i < 17; i++) { + if (lim.throttle(params)) { + console.log("[FAIL] Burst & Wait: Unexpected throttle"); + return; + } + } + console.log("[PASS] Burst & Wait"); + }, 6000); +} + +testBurst(); +testBurstAndWait();