Class: Pazuzu::Utility::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/pazuzu/utility/rate_limiter.rb

Overview

Simple limiter that can be used to limit the rate of processing. Uses a short time window to calculate current rate.

Instance Method Summary collapse

Constructor Details

#initialize(max_hertz, window_seconds = 3.0) ⇒ RateLimiter

Initialize limiter with max_hertz as the maximum frequency per second, and window_seconds as the number of seconds to calculate frequency based on.



11
12
13
14
15
# File 'lib/pazuzu/utility/rate_limiter.rb', line 11

def initialize(max_hertz, window_seconds = 3.0)
  @max_hertz = max_hertz
  @history_seconds = window_seconds
  @window = []
end

Instance Method Details

#count!Object

Count a cycle. If the current rate exceeds the permitted limit, it will sleep until the rate goes below the limit. Returns true if not currently rate-limited, otherwise false.



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pazuzu/utility/rate_limiter.rb', line 26

def count!
  iterate
  limited = false
  @window[-1][1] += 1
  while rate > @max_hertz
    sleep(0.5)
    limited = true
    iterate
  end
  !limited
end

#limited?Boolean

Returns true if current rate exceeds limit.

Returns:

  • (Boolean)


18
19
20
21
# File 'lib/pazuzu/utility/rate_limiter.rb', line 18

def limited?
  iterate
  rate > @max_hertz
end

#rateObject

Returns current rate, in hertz.



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pazuzu/utility/rate_limiter.rb', line 39

def rate
  rate = 0
  window = @window
  unless window.empty?
    range = window[-1][0] - window[0][0]
    if range > 0
      total = window.inject(0.0) { |sum, (t, count)| sum + count }
      rate = total / range if total >= @max_hertz
    end
  end
  rate
end