Class: Chokepoint::Interval

Inherits:
Limiter
  • Object
show all
Defined in:
lib/chokepoint/interval.rb

Overview

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

Examples:

Allowing up to two requests per second

Chokepoint::Interval.new('activity', :min => 0.5)   #  500 ms interval

Allowing a request every two seconds

Chokepoint::Interval.new('activity', :min => 2)   #  2000 ms interval

Instance Attribute Summary

Attributes inherited from Limiter

#name, #options

Instance Method Summary collapse

Methods inherited from Limiter

#blacklisted?, #throttle, #whitelisted?

Constructor Details

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

Returns a new instance of Interval.

Parameters:

  • name (String)
  • options (Hash{Symbol => Object}) (defaults to: {})

Options Hash (options):

  • :min (Float) — default: 1.0


17
18
19
# File 'lib/chokepoint/interval.rb', line 17

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

Instance Method Details

#allowed?(context) ⇒ Boolean

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

Parameters:

  • context (Object)

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/chokepoint/interval.rb', line 27

def allowed?(context)
  time_now = Time.now.to_f
  last_call_time = cache_get(key = cache_key(context)) rescue nil
  allowed = !last_call_time || (dt = time_now - last_call_time.to_f) >= minimum_interval
  begin
    cache_set(key, time_now)
    allowed
  rescue => e
    # 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 application blowing up merely due to a
    # backend cache server (Memcached, Redis, etc.) being offline.
    allowed = true
  end
end

#minimum_intervalFloat

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

Returns:

  • (Float)


48
49
50
# File 'lib/chokepoint/interval.rb', line 48

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