Class: Pebbles::River::RateLimiter
- Inherits:
-
Object
- Object
- Pebbles::River::RateLimiter
- Defined in:
- lib/pebbles/river/rate_limiter.rb
Overview
Simple queueless token-bucket limiter.
Instance Method Summary collapse
- #increment ⇒ Object
-
#initialize(max_rate, window_seconds) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
Constructor Details
#initialize(max_rate, window_seconds) ⇒ RateLimiter
Returns a new instance of RateLimiter.
7 8 9 10 11 |
# File 'lib/pebbles/river/rate_limiter.rb', line 7 def initialize(max_rate, window_seconds) @last_check = Time.now @max_rate = @allowance = max_rate @window_seconds = window_seconds end |
Instance Method Details
#increment ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/pebbles/river/rate_limiter.rb', line 13 def increment now = Time.now time_passed = now - @last_check @last_check = now @allowance += time_passed * (@max_rate / @window_seconds) if @allowance > @max_rate @allowance = @max_rate end if @allowance < 1 sleep((1 - @allowance) * (@window_seconds / @max_rate)) @allowance = 0 else @allowance -= 1 end end |