Class: Chokepoint::Limiter

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

Overview

This is the base class for rate limiter implementations.

Examples:

Defining a rate limiter subclass

class MyLimiter < Limiter
  def allowed?(request)
    # TODO: custom logic goes here
  end
end

Direct Known Subclasses

Interval, TimeWindow

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Limiter.

Parameters:

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

Options Hash (options):

  • :cache (String) — default: Hash.new
  • :key_prefix (String) — default: nil
  • :code (Integer) — default: 403
  • :message (String) — default: "Rate Limit Exceeded"


23
24
25
# File 'lib/chokepoint/limiter.rb', line 23

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

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



13
14
15
# File 'lib/chokepoint/limiter.rb', line 13

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



14
15
16
# File 'lib/chokepoint/limiter.rb', line 14

def options
  @options
end

Instance Method Details

#allowed?(context = nil) ⇒ Boolean

Returns ‘false` if the rate limit has been exceeded for the given `request`, or `true` otherwise.

Override this method in subclasses that implement custom rate limiter strategies.

Parameters:

  • context (Object) (defaults to: nil)

Returns:

  • (Boolean)


40
41
42
43
44
45
46
# File 'lib/chokepoint/limiter.rb', line 40

def allowed?(context = nil)
  case
    when whitelisted?(context) then true
    when blacklisted?(context) then false
    else true # override in subclasses
  end
end

#blacklisted?(context) ⇒ Boolean

This method is abstract.

Returns ‘true` if the originator of the given `request` is blacklisted (not honoring rate limits, and thus permanently forbidden access without the need to maintain further rate limit counters).

The default implementation always returns ‘false`. Override this method in a subclass to implement custom blacklisting logic.

Parameters:

  • context (Object)

Returns:

  • (Boolean)


73
74
75
# File 'lib/chokepoint/limiter.rb', line 73

def blacklisted?(context)
  false
end

#throttle(context = nil) ⇒ Object



27
28
29
# File 'lib/chokepoint/limiter.rb', line 27

def throttle(context = nil)
  allowed?(context) ? yield : rate_limit_exceeded(context)
end

#whitelisted?(context) ⇒ Boolean

This method is abstract.

Returns ‘true` if the originator of the given `request` is whitelisted (not subject to further rate limits).

The default implementation always returns ‘false`. Override this method in a subclass to implement custom whitelisting logic.

Parameters:

  • context (Object)

Returns:

  • (Boolean)


58
59
60
# File 'lib/chokepoint/limiter.rb', line 58

def whitelisted?(context)
  false
end