Class: APILimiter
- Inherits:
-
Object
- Object
- APILimiter
- Defined in:
- lib/globals.rb
Instance Attribute Summary collapse
-
#max_concurrent_requests ⇒ Object
readonly
Returns the value of attribute max_concurrent_requests.
Instance Method Summary collapse
-
#initialize(max_concurrent_requests:) ⇒ APILimiter
constructor
A new instance of APILimiter.
- #with_limit ⇒ Object
Constructor Details
#initialize(max_concurrent_requests:) ⇒ APILimiter
Returns a new instance of APILimiter.
32 33 34 35 36 37 |
# File 'lib/globals.rb', line 32 def initialize(max_concurrent_requests:) @max_concurrent_requests = max_concurrent_requests.must_be_a Integer @mutex = Mutex.new @condition = ConditionVariable.new @counter = 0 end |
Instance Attribute Details
#max_concurrent_requests ⇒ Object (readonly)
Returns the value of attribute max_concurrent_requests.
39 40 41 |
# File 'lib/globals.rb', line 39 def max_concurrent_requests @max_concurrent_requests end |
Instance Method Details
#with_limit ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/globals.rb', line 41 def with_limit @mutex.synchronize do @condition.wait(@mutex) while @counter >= @max_concurrent_requests @counter += 1 end begin yield # Execute the provided block rescue RateLimitExceededError => e retries += 1 if retries <= @max_retries putt :rpc, "Rate limit exceeded. Retrying in #{2 ** retries} seconds." sleep(2 ** retries + rand) # Exponential backoff with some random jitter retry else raise "Max retries reached. Original error: #{e.}" end ensure @mutex.synchronize do @counter -= 1 @condition.signal end end end |