Class: Bearcat::RateLimiting::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/bearcat/rate_limiting.rb

Direct Known Subclasses

RedisLimiter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace: "bearcat", **kwargs) ⇒ RateLimiter

Returns a new instance of RateLimiter.



13
14
15
16
# File 'lib/bearcat/rate_limiting.rb', line 13

def initialize(namespace: "bearcat", **kwargs)
  @namespace = namespace
  @params = kwargs
end

Instance Attribute Details

#namespaceObject (readonly)

Returns the value of attribute namespace.



11
12
13
# File 'lib/bearcat/rate_limiting.rb', line 11

def namespace
  @namespace
end

Instance Method Details

#apply(key, guess: GUESS_COST, on_sleep: nil, max_sleep: 15) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/bearcat/rate_limiting.rb', line 18

def apply(key, guess: GUESS_COST, on_sleep: nil, max_sleep: 15)
  current = increment("#{key}", 0, guess)
  cost = guess
  remaining = MAXIMUM - current[:count]

  if remaining < 0
    tts = -remaining / LEAK_RATE
    tts = [tts, max_sleep].min if max_sleep
    on_sleep.call(tts) if on_sleep
    sleep tts
  end

  cost = yield
ensure
  increment(key, (cost || 0), -guess)
end