rack-attack/lib/rack/attack/throttle.rb
Aaron Suggs e7aa5f4abe Use rotating cache keys for throttle (instead of expiring)
Throttles use a cache key with a timestamp (Time.now.to_i/period), so a
new cache key is used for each period.

No longer set an explicit expiry on each cache key (though it may
inherit a default expiry from the cache store).

Also, set env['rack.attack.throttle_data'] with info about incremented
(but not necessarily exceeded) throttles.
2012-08-08 14:59:42 -04:00

43 lines
1.1 KiB
Ruby

module Rack
module Attack
class Throttle
attr_reader :name, :limit, :period, :block
def initialize(name, options, block)
@name, @block = name, block
[:limit, :period].each do |opt|
raise ArgumentError.new("Must pass #{opt.inspect} option") unless options[opt]
end
@limit = options[:limit]
@period = options[:period]
end
def cache
Rack::Attack.cache
end
def [](req)
discriminator = block[req]
return false unless discriminator
key = "#{name}:#{discriminator}"
count = cache.count(key, period)
data = {
:count => count,
:period => period,
:limit => limit
}
(req.env['rack.attack.throttle_data'] ||= {})[name] = data
(count > limit).tap do |throttled|
if throttled
req.env['rack.attack.matched'] = name
req.env['rack.attack.match_type'] = :throttle
req.env['rack.attack.match_data'] = data
Rack::Attack.instrument(req)
end
end
end
end
end
end