2014-03-03 06:46:40 -05:00
|
|
|
settings = require("settings-sharelatex")
|
2016-12-19 07:17:02 -05:00
|
|
|
RedisWrapper = require('./RedisWrapper')
|
|
|
|
rclient = RedisWrapper.client('ratelimiter')
|
2014-02-28 12:59:54 -05:00
|
|
|
|
2016-12-19 07:17:02 -05:00
|
|
|
|
|
|
|
module.exports = RateLimiter =
|
|
|
|
|
|
|
|
_buildKey: (endpoint, subject) ->
|
|
|
|
return "RateLimiter:#{endpoint}:{#{subject}}"
|
2014-02-28 12:59:54 -05:00
|
|
|
|
|
|
|
addCount: (opts, callback = (opts, shouldProcess)->)->
|
2016-12-19 07:17:02 -05:00
|
|
|
k = RateLimiter._buildKey(opts.endpointName, opts.subjectName)
|
|
|
|
multi = rclient.multi()
|
|
|
|
multi.incr(k)
|
|
|
|
multi.get(k)
|
|
|
|
multi.expire(k, opts.timeInterval)
|
|
|
|
multi.exec (err, results)->
|
|
|
|
console.log ">> results", results
|
|
|
|
count = results[1]
|
|
|
|
# account for the different results from `multi` when using cluster
|
|
|
|
if count instanceof Object
|
|
|
|
count = count[1]
|
|
|
|
allow = count < opts.throttle
|
|
|
|
callback err, allow
|
|
|
|
|
2015-02-05 05:18:18 -05:00
|
|
|
clearRateLimit: (endpointName, subject, callback) ->
|
2016-12-19 07:17:02 -05:00
|
|
|
k = RateLimiter._buildKey(endpointName, subject)
|
|
|
|
rclient.del k, callback
|