Class: LeakyBucket::Throttler

Inherits:
Object
  • Object
show all
Defined in:
lib/leaky_bucket/throttler.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cacheObject

Returns the value of attribute cache.



14
15
16
# File 'lib/leaky_bucket/throttler.rb', line 14

def cache
  @cache
end

Class Method Details

.throttle(ip, threshold: 100, interval: 3600, burst: 10) ⇒ Object



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

def throttle(ip, threshold: 100, interval: 3600, burst: 10)
  bucket = LeakyBucket.cache.read(ip) || new_counter

  #leak proper number of requests since last request time.
  bucket = leak(bucket, threshold, interval)

  if bucket[:current_load] > burst
    raise LeakyBucket::TooManyRequests.new((interval/threshold) - (Time.now.to_i - bucket[:last_request_made_at]))
  end

  increment(ip, bucket)
end