overleaf/services/web/app/coffee/infrastructure/RateLimiter.coffee

28 lines
852 B
CoffeeScript
Raw Normal View History

settings = require("settings-sharelatex")
RedisWrapper = require('./RedisWrapper')
rclient = RedisWrapper.client('ratelimiter')
RollingRateLimiter = require('rolling-rate-limiter')
module.exports = RateLimiter =
2016-12-19 14:10:27 +00:00
addCount: (opts, callback = (err, shouldProcess)->)->
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
callback(null, allowed)
2015-02-05 10:18:18 +00:00
clearRateLimit: (endpointName, subject, callback) ->
# same as the key which will be built by RollingRateLimiter (namespace+k)
keyName = "RateLimit:#{endpointName}:{#{subject}}"
rclient.del keyName, callback