Class: Lapsoss::Sampling::RateLimiter
- Defined in:
- lib/lapsoss/sampling/rate_limiter.rb
Instance Method Summary collapse
-
#initialize(max_events_per_second: 10) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
- #sample?(_event, _hint = {}) ⇒ Boolean
Constructor Details
#initialize(max_events_per_second: 10) ⇒ RateLimiter
Returns a new instance of RateLimiter.
6 7 8 9 10 11 |
# File 'lib/lapsoss/sampling/rate_limiter.rb', line 6 def initialize(max_events_per_second: 10) @max_events_per_second = max_events_per_second @tokens = max_events_per_second @last_refill = Time.zone.now @mutex = Mutex.new end |
Instance Method Details
#sample?(_event, _hint = {}) ⇒ Boolean
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/lapsoss/sampling/rate_limiter.rb', line 13 def sample?(_event, _hint = {}) @mutex.synchronize do now = Time.zone.now time_passed = now - @last_refill # Refill tokens based on time passed @tokens = [ @tokens + (time_passed * @max_events_per_second), @max_events_per_second ].min @last_refill = now if @tokens >= 1 @tokens -= 1 true else false end end end |