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

29 lines
860 B
CoffeeScript
Raw Normal View History

settings = require("settings-sharelatex")
RedisWrapper = require('./RedisWrapper')
rclient = RedisWrapper.client('ratelimiter')
module.exports = RateLimiter =
_buildKey: (endpoint, subject) ->
return "RateLimiter:#{endpoint}:{#{subject}}"
addCount: (opts, callback = (opts, shouldProcess)->)->
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) ->
k = RateLimiter._buildKey(endpointName, subject)
rclient.del k, callback