class Rack::Attack::RateLimit
Constants
- RACK_ATTACK_KEY
- VERSION
Attributes
Public Class Methods
# File lib/rack/attack/rate-limit.rb, line 15 def initialize(app, options = {}) @app = app @options = default_options.merge(options) end
Public Instance Methods
Return hash of headers with Rate Limiting data
headers - Hash of headers
Returns hash
# File lib/rack/attack/rate-limit.rb, line 52 def add_rate_limit_headers!(headers, env) throttle_data = throttle_data_closest_to_limit(env) headers['X-RateLimit-Limit'] = rate_limit_limit(throttle_data).to_s headers['X-RateLimit-Remaining'] = rate_limit_remaining(throttle_data).to_s headers end
# File lib/rack/attack/rate-limit.rb, line 20 def call(env) # If env does not have necessary data to extract rate limit data for the provider, then app.call return app.call(env) unless rate_limit_available?(env) # Otherwise, add rate limit headers status, headers, body = app.call(env) add_rate_limit_headers!(headers, env) [status, headers, body] end
Default options to configure Rack::RateLimit
Returns hash
# File lib/rack/attack/rate-limit.rb, line 39 def default_options { throttle: 'throttle' } end
Returns env key used by Rack::Attack
to namespace data
Returns string
# File lib/rack/attack/rate-limit.rb, line 32 def rack_attack_key RACK_ATTACK_KEY end
# File lib/rack/attack/rate-limit.rb, line 43 def throttle Array(options[:throttle]) || [] end
Protected Instance Methods
Rate Limit available method for Rack::Attack
provider Checks that at least one of the keys provided by the user are in the rack.attack.throttle_data env hash key
env - Hash
Returns boolean
# File lib/rack/attack/rate-limit.rb, line 85 def rate_limit_available?(env) env.key?(rack_attack_key) && (env[rack_attack_key].keys & throttle).any? end
RateLimit
upper limit from Rack::Attack
env - Hash
Returns Fixnum
# File lib/rack/attack/rate-limit.rb, line 66 def rate_limit_limit(throttle_data) throttle_data[:limit] end
RateLimit
remaining request from Rack::Attack
env - Hash
Returns Fixnum
# File lib/rack/attack/rate-limit.rb, line 75 def rate_limit_remaining(throttle_data) rate_limit_limit(throttle_data) - throttle_data[:count] end
Throttle Data Closest to Limit Selects the hash in throttle_data_of_interest
where the user is closest to the limit
env - Hash
Returns Hash
# File lib/rack/attack/rate-limit.rb, line 105 def throttle_data_closest_to_limit(env) min_array = throttle_data_of_interest(env).min_by { |_k, v| v[:limit] - v[:count] } # The min_by method returns an array of the form [key, value] # We only need the values min_array.last end
Throttle Data of Interest Filters the rack.attack.throttle_data env hash key for the throttle names provided by the user
env - Hash
Returns Hash
# File lib/rack/attack/rate-limit.rb, line 95 def throttle_data_of_interest(env) env[rack_attack_key].select { |k, _v| throttle.include?(k) } end