Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Promise = require 'bluebird'
- redis = require 'connect-redis/node_modules/redis'
- redback = require('redback').use redis.createClient()
- pkgman = require 'pkgman'
- limiter = redback.createRateLimit 'limiter'
- exports.Limiter = class Limiter
- constructor: (@req) ->
- add: (key) ->
- add = Promise.promisify limiter.add, limiter
- Promise.all(add key for key in @_keys key)
- addAndCheckThreshold: (key, threshold) ->
- unless threshold instanceof ThresholdTime
- return Promise.reject new TypeError "The second parameter to Limiter::addAndCheckThreshold must be a valid threshold!"
- @add(key).then => @checkThreshold key, threshold
- count: (key, seconds) ->
- count = Promise.promisify limiter.count, limiter
- Promise.all(count key, seconds for key in @_keys key).then(
- (counts) -> counts.reduce(
- (l, r) -> if l > r then l else r
- -Infinity
- )
- (error) -> reject error
- )
- checkThreshold: (key, threshold) ->
- unless threshold instanceof ThresholdTime
- return Promise.reject new TypeError "The second parameter to Limiter::checkThreshold must be a valid threshold!"
- @count(key, threshold.calculateSeconds()).then (count) ->
- count > threshold.count()
- _keys: (root) ->
- auditKeys = {}
- pkgman.invoke 'auditKeys', (path, fn) => auditKeys[path] = fn @req
- keys = []
- for path, suffixes of auditKeys
- keys.push "#{root}:#{path}:#{suffix}" for suffix in suffixes
- keys
- exports.threshold = (count) -> new Threshold count
- class Threshold
- constructor: (@_count) ->
- every: (amount) -> new ThresholdTime @_count, amount
- class ThresholdTime
- constructor: (@_count, @_amount) ->
- @_multiplier = 1
- calculateSeconds: -> @_amount * @_multiplier
- count: -> @_count
- multipliers =
- ms: 1 / 1000
- seconds: 1
- minutes: 60
- for key, multiplier of multipliers
- do (key, multiplier) =>
- @::[key] = ->
- @_multiplier = multiplier
- this
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement