Class: Rack::Throttle::Interval

Inherits:
Limiter
  • Object
show all
Defined in:
lib/rack/throttle/limiters/interval.rb

Overview

This rate limiter strategy throttles the application by enforcing a minimum interval (by default, 1 second) between subsequent allowed HTTP requests.

Examples:

Allowing up to two requests per second

use Rack::Throttle::Interval, :min => 0.5   #  500 ms interval

Allowing a request every two seconds

use Rack::Throttle::Interval, :min => 2.0   # 2000 ms interval

Instance Attribute Summary

Attributes inherited from Limiter

#app, #matchers, #options

Instance Method Summary collapse

Methods inherited from Limiter

#blacklisted?, #call, #restricted_url?, #whitelisted?

Constructor Details

#initialize(app, options = {}) ⇒ Interval

Returns a new instance of Interval.

Parameters:

  • app (#call)
  • options (Hash{Symbol => Object}) (defaults to: {})

Options Hash (options):

  • :min (Float) — default: 1.0


18
19
20
# File 'lib/rack/throttle/limiters/interval.rb', line 18

def initialize(app, options = {})
  super
end

Instance Method Details

#allowed?(request) ⇒ Boolean

Returns ‘true` if sufficient time (equal to or more than #minimum_interval) has passed since the last request and the given present `request`.

Parameters:

  • request (Rack::Request)

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/throttle/limiters/interval.rb', line 29

def allowed?(request)
  t1 = request_start_time(request)
  t0 = cache_get(key = cache_key(request)) rescue nil
  allowed = !t0 || (dt = t1 - t0.to_f) >= minimum_interval
  begin
    cache_set(key, t1)
    allowed
  rescue StandardError => e
    allowed = true
    # If an error occurred while trying to update the timestamp stored
    # in the cache, we will fall back to allowing the request through.
    # This prevents the Rack application blowing up merely due to a
    # backend cache server (Memcached, Redis, etc.) being offline.
  end
end

#minimum_intervalFloat

Returns the required minimal interval (in terms of seconds) that must elapse between two subsequent HTTP requests.

Returns:

  • (Float)


59
60
61
# File 'lib/rack/throttle/limiters/interval.rb', line 59

def minimum_interval
  @min ||= (@options[:min] || 1.0).to_f
end

#retry_afterFloat

Returns the number of seconds before the client is allowed to retry an HTTP request.

Returns:

  • (Float)


50
51
52
# File 'lib/rack/throttle/limiters/interval.rb', line 50

def retry_after
  minimum_interval
end