Class: BSV::Network::Services::TokenBucket
- Inherits:
-
Object
- Object
- BSV::Network::Services::TokenBucket
- Defined in:
- lib/bsv/network/services.rb
Overview
Simple token bucket rate limiter. One per provider. Refills at rate tokens per second. Burst capacity is max(rate, 1) so that sub-1 rates (e.g. 0.5 req/sec) can still acquire a token.
Instance Method Summary collapse
-
#acquire! ⇒ Object
Block until a token is available, then consume it.
-
#initialize(rate) ⇒ TokenBucket
constructor
A new instance of TokenBucket.
Constructor Details
#initialize(rate) ⇒ TokenBucket
Returns a new instance of TokenBucket.
276 277 278 279 280 281 282 283 284 |
# File 'lib/bsv/network/services.rb', line 276 def initialize(rate) raise ArgumentError, 'rate must be positive' unless rate.to_f.positive? @rate = rate.to_f @capacity = [@rate, 1.0].max @tokens = @capacity @last_refill = Time.now @mutex = Mutex.new end |
Instance Method Details
#acquire! ⇒ Object
Block until a token is available, then consume it.
287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/bsv/network/services.rb', line 287 def acquire! loop do @mutex.synchronize do refill if @tokens >= 1.0 @tokens -= 1.0 return end end sleep(0.05) end end |