Class: Millrace::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/millrace/rate_limit.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, rate:, window:, penalty: 0, redis_config: nil) ⇒ RateLimit

Returns a new instance of RateLimit.



6
7
8
9
10
11
12
# File 'lib/millrace/rate_limit.rb', line 6

def initialize(name:, rate:, window:, penalty: 0, redis_config: nil)
  @name         = name
  @rate         = rate
  @window       = window
  @penalty      = penalty
  @redis_config = redis_config
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



14
15
16
# File 'lib/millrace/rate_limit.rb', line 14

def name
  @name
end

#rateObject (readonly)

Returns the value of attribute rate.



14
15
16
# File 'lib/millrace/rate_limit.rb', line 14

def rate
  @rate
end

#windowObject (readonly)

Returns the value of attribute window.



14
15
16
# File 'lib/millrace/rate_limit.rb', line 14

def window
  @window
end

Instance Method Details

#before(controller) ⇒ Object

Raises:



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/millrace/rate_limit.rb', line 16

def before(controller)
  bucket = get_bucket(controller.request.remote_ip)
  level = bucket.fillup(1).level

  return if level < threshold

  if level - 1 < threshold
    level = bucket.fillup(penalty).level
  end

  raise RateLimited.new(limit_name: name, retry_after: retry_after(level))
end