forked from clientIO/quota
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackexchange.js
75 lines (61 loc) · 1.97 KB
/
stackexchange.js
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
'use strict';
var Manager = require('../manager.js');
var Rule = require('../rule.js');
var _ = require('lodash');
var generalRuleRPS = null;
/**
* Quota Preset for StackExchange
*
* Quota rules based on: https://api.stackexchange.com/docs/throttle
* Bitly API docs: https://api.stackexchange.com
*
* In a cluster environment a local Server can be used if each node.js instance
* is reached via a different IP address from the internet and also if all
* requests on behalf a particular user are only made by a single node.js
* instance.
*
* @param options
* @returns {Manager}
*/
module.exports = function (options) {
_.defaults(options, {
requestsPerSecond: 30,
authenticated: true,
sharedIPAddress: false
});
var manager = new Manager({
backoff: 'timeout' // TODO: If an application receives a response with the backoff field set, it must wait that many seconds before hitting the same method again.
});
// If a single IP is making more than 30 requests a second, new requests will be dropped.
if (generalRuleRPS === null) {
generalRuleRPS = new Rule({
limit: options.requestsPerSecond,
window: 1000,
throttling: 'window-sliding',
queueing: 'fifo',
scope: options.sharedIPAddress ? 'ipAddress' : [],
resource: 'requests'
});
}
manager.addRule(generalRuleRPS);
if (options.authenticated) {
manager.addRule({
limit: 10000,
window: 24*60*60*1000,
throttling: 'window-sliding',
queueing: 'fifo',
scope: 'userId',
resource: 'requests'
});
} else {
manager.addRule({
limit: 10000,
window: 24*60*60*1000,
throttling: 'window-sliding',
queueing: 'fifo',
scope: options.sharedIPAddress ? 'ipAddress' : [],
resource: 'requests'
});
}
return manager;
};