Class: Aikido::Zen::RateLimiter
- Inherits:
-
Object
- Object
- Aikido::Zen::RateLimiter
- Defined in:
- lib/aikido/zen/rate_limiter.rb
Overview
Keeps track of all requests in this process, broken up by Route and further discriminated by client. Provides a single method that checks if a certain Request needs to be throttled or not.
Defined Under Namespace
Classes: Breaker, Bucket, Result
Instance Method Summary collapse
-
#initialize(config: Aikido::Zen.config, settings: Aikido::Zen.runtime_settings) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
-
#throttle?(request) ⇒ Boolean
Checks whether the request requires rate limiting.
Constructor Details
#initialize(config: Aikido::Zen.config, settings: Aikido::Zen.runtime_settings) ⇒ RateLimiter
Returns a new instance of RateLimiter.
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/aikido/zen/rate_limiter.rb', line 13 def initialize( config: Aikido::Zen.config, settings: Aikido::Zen.runtime_settings ) @config = config @settings = settings @buckets = Hash.new { |store, route| synchronize { settings = settings_for(route) store[route] = Bucket.new(ttl: settings.period, max_size: settings.max_requests) } } end |
Instance Method Details
#throttle?(request) ⇒ Boolean
Checks whether the request requires rate limiting. As a side effect, this will annotate the request with the “aikido.rate_limiting” ENV key, holding the result of the check, and including useful stats in case you want to return RateLimit headers..
36 37 38 39 40 41 42 43 44 |
# File 'lib/aikido/zen/rate_limiter.rb', line 36 def throttle?(request) settings = settings_for(request.route) return false unless settings.enabled? bucket = @buckets[request.route] key = @config.rate_limiting_discriminator.call(request) request.env["aikido.rate_limiting"] = bucket.increment(key) request.env["aikido.rate_limiting"].throttled? end |