rolling-rate-limiter
Advanced tools
Comparing version 0.1.0 to 0.1.1
18
index.js
@@ -6,5 +6,5 @@ var assert = require("assert"); | ||
var redis = options.redis, | ||
interval = options.interval, | ||
interval = options.interval * 1000, // in microseconds | ||
maxInInterval = options.maxInInterval, | ||
minDifference = options.minDifference, | ||
minDifference = options.minDifference ? 1000*options.minDifference : null, // also in microseconds | ||
namespace = options.namespace || (options.redis && ("rate-limiter-" + Math.random().toString(36).slice(2))) || null; | ||
@@ -16,6 +16,2 @@ | ||
// Since we're working in microtime. | ||
interval *= 1000; | ||
minDifference = minDifference ? 1000*minDifference : null; | ||
if (!options.redis) { | ||
@@ -40,10 +36,10 @@ var storage = {}; | ||
var batch = redis.multi(); | ||
batch.expire(key, interval); | ||
batch.zremrangebyscore(key, 0, clearBefore); | ||
batch.zrange(key, 0, -1); | ||
batch.zadd(key, now, now); | ||
batch.expire(key, Math.ceil(interval/1000000)); // convert to seconds, as used by redis ttl. | ||
batch.exec(function (err, resultArr) { | ||
if (err) return cb(err); | ||
var userSet = resultArr[2].map(Number); | ||
var userSet = resultArr[1].map(Number); | ||
@@ -56,3 +52,3 @@ var tooManyInInterval = userSet.length >= maxInInterval; | ||
result = Math.min(userSet[0] - now + interval, minDifference ? minDifference - timeSinceLastRequest : Infinity); | ||
result = Math.floor(result/1000); // convert from microseconds. | ||
result = Math.floor(result/1000); // convert to miliseconds for user readability. | ||
} else { | ||
@@ -92,3 +88,3 @@ result = 0; | ||
result = Math.min(userSet[0] - now + interval, minDifference ? minDifference - timeSinceLastRequest : Infinity); | ||
result = Math.floor(result/1000); // convert from microseconds. | ||
result = Math.floor(result/1000); // convert from microseconds for user readability. | ||
} else { | ||
@@ -100,3 +96,3 @@ result = 0; | ||
delete storage[id]; | ||
}, interval); | ||
}, 1000*interval); // convert to miliseconds for javascript timeout | ||
@@ -103,0 +99,0 @@ if (cb) { |
{ | ||
"name": "rolling-rate-limiter", | ||
"version": "0.1.0", | ||
"version": "0.1.1", | ||
"description": "Rate limiter that supports a rolling window, either in-memory or backed by redis", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -454,3 +454,21 @@ var sinon = require("sinon"); | ||
}); | ||
it("ttl functions properly", function(done) { | ||
var client = redis.createClient(); | ||
var namespace = Math.random().toString(36).slice(2); | ||
var limiter = RateLimiter({ | ||
redis: client, | ||
interval: 10000, | ||
maxInInterval: 5, | ||
namespace: namespace | ||
}); | ||
limiter("1", function(err, result) { | ||
var key = namespace + "1"; | ||
client.ttl(key, function(err, result) { | ||
expect(result).to.equal(10); | ||
done(); | ||
}) | ||
}); | ||
}); | ||
}); | ||
}); |
22919
498