forked from peterkhayes/rolling-rate-limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
129 lines (104 loc) · 4.1 KB
/
Copy pathindex.js
File metadata and controls
129 lines (104 loc) · 4.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
var assert = require("assert");
var microtime = require("microtime-nodejs");
function RateLimiter (options) {
var redis = options.redis,
interval = options.interval * 1000, // in microseconds
maxInInterval = options.maxInInterval,
minDifference = options.minDifference ? 1000 * options.minDifference : null, // also in microseconds
namespace = options.namespace || (options.redis && (`rate-limiter-${ Math.random().toString(36).slice(2)}`)) || null;
assert(interval > 0, "Must pass a positive integer for `options.interval`");
assert(maxInInterval > 0, "Must pass a positive integer for `options.maxInInterval`");
assert(!(minDifference < 0), "`options.minDifference` cannot be negative");
if (!options.redis) {
var storage = {};
var timeouts = {};
}
if (redis) {
// If redis is going to be potentially returning buffers OR an array from
// ZRANGE, need a way to safely convert either of these types to an array
// of numbers. Otherwise, we can just assume that the result is an array
// and safely map over it.
var zrangeToUserSet;
if (redis.options.return_buffers || redis.options.detect_buffers) {
zrangeToUserSet = function(str) {
return String(str).split(",").map(Number);
};
} else {
zrangeToUserSet = function(arr) {
return arr.map(Number);
};
}
return function(id, cb) {
if (!cb) {
cb = id;
id = "";
}
assert.equal(typeof cb, "function", "Callback must be a function.");
var now = microtime.now();
var key = namespace + id;
var clearBefore = now - interval;
var batch = redis.multi();
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 = zrangeToUserSet(resultArr[1]);
var tooManyInInterval = userSet.length >= maxInInterval;
var timeSinceLastRequest = now - userSet[userSet.length - 1];
var result;
var remaining = maxInInterval - userSet.length - 1;
if (tooManyInInterval || timeSinceLastRequest < minDifference) {
result = Math.max(tooManyInInterval ? userSet[userSet.length - maxInInterval] - now + interval : 0, minDifference ? minDifference : 0);
result = Math.floor(result / 1000); // convert to miliseconds for user readability.
} else {
result = 0;
}
return cb(null, result, remaining);
});
};
} else {
return function() {
var args = Array.prototype.slice.call(arguments);
var cb = args.pop();
var id;
if (typeof cb === "function") {
id = args[0] || "";
} else {
id = cb || "";
cb = null;
}
var now = microtime.now();
var clearBefore = now - interval;
clearTimeout(timeouts[id]);
delete timeouts[id];
var userSet = storage[id] = (storage[id] || []).filter(function(timestamp) {
return timestamp > clearBefore;
});
var tooManyInInterval = userSet.length >= maxInInterval;
var timeSinceLastRequest = now - userSet[userSet.length - 1];
var result;
var remaining = maxInInterval - userSet.length - 1;
if (tooManyInInterval || timeSinceLastRequest < minDifference) {
result = Math.max(tooManyInInterval ? userSet[userSet.length - maxInInterval] - now + interval : 0, minDifference ? minDifference : 0);
result = Math.floor(result / 1000); // convert from microseconds for user readability.
} else {
result = 0;
}
userSet.push(now);
timeouts[id] = setTimeout(function() {
delete storage[id];
delete timeouts[id];
}, interval / 1000); // convert to miliseconds for javascript timeout
if (cb) {
return process.nextTick(function() {
cb(null, result, remaining);
});
} else {
return result;
}
};
}
}
module.exports = RateLimiter;