2014-03-03 06:46:40 -05:00
|
|
|
settings = require("settings-sharelatex")
|
2019-01-18 05:10:09 -05:00
|
|
|
Metrics = require('metrics-sharelatex')
|
2016-12-19 07:17:02 -05:00
|
|
|
RedisWrapper = require('./RedisWrapper')
|
|
|
|
rclient = RedisWrapper.client('ratelimiter')
|
2017-01-12 04:25:18 -05:00
|
|
|
RollingRateLimiter = require('rolling-rate-limiter')
|
2014-02-28 12:59:54 -05:00
|
|
|
|
2016-12-19 07:17:02 -05:00
|
|
|
|
|
|
|
module.exports = RateLimiter =
|
|
|
|
|
2016-12-19 09:10:27 -05:00
|
|
|
addCount: (opts, callback = (err, shouldProcess)->)->
|
2017-01-12 04:25:18 -05:00
|
|
|
namespace = "RateLimit:#{opts.endpointName}:"
|
|
|
|
k = "{#{opts.subjectName}}"
|
|
|
|
limiter = RollingRateLimiter({
|
|
|
|
redis: rclient,
|
|
|
|
namespace: namespace,
|
|
|
|
interval: opts.timeInterval * 1000,
|
|
|
|
maxInInterval: opts.throttle
|
|
|
|
})
|
|
|
|
limiter k, (err, timeLeft, actionsLeft) ->
|
|
|
|
if err?
|
|
|
|
return callback(err)
|
|
|
|
allowed = timeLeft == 0
|
2019-01-18 05:10:09 -05:00
|
|
|
Metrics.inc "rate-limit-hit.#{opts.endpointName}", 1, {path: opts.endpointName} unless allowed
|
2017-01-12 04:25:18 -05:00
|
|
|
callback(null, allowed)
|
2016-12-19 07:17:02 -05:00
|
|
|
|
2015-02-05 05:18:18 -05:00
|
|
|
clearRateLimit: (endpointName, subject, callback) ->
|
2017-01-12 04:25:18 -05:00
|
|
|
# same as the key which will be built by RollingRateLimiter (namespace+k)
|
|
|
|
keyName = "RateLimit:#{endpointName}:{#{subject}}"
|
|
|
|
rclient.del keyName, callback
|