Class: Philiprehberger::RetryKit::Budget
- Inherits:
-
Object
- Object
- Philiprehberger::RetryKit::Budget
- Defined in:
- lib/philiprehberger/retry_kit/budget.rb
Overview
Thread-safe sliding window retry budget to prevent retry storms.
Multiple executors can share a single budget instance. When the budget is exhausted, retries are skipped and the error is raised immediately.
Defined Under Namespace
Classes: ExhaustedError
Instance Method Summary collapse
-
#acquire ⇒ Boolean
Try to consume one retry from the budget.
-
#exhausted? ⇒ Boolean
Returns whether the budget is exhausted.
-
#initialize(max_retries:, window:) ⇒ Budget
constructor
A new instance of Budget.
-
#remaining ⇒ Integer
Returns the number of remaining retries in the current window.
-
#reset ⇒ self
Clear all recorded retries.
Constructor Details
#initialize(max_retries:, window:) ⇒ Budget
Returns a new instance of Budget.
15 16 17 18 19 20 |
# File 'lib/philiprehberger/retry_kit/budget.rb', line 15 def initialize(max_retries:, window:) @max_retries = max_retries @window = window @timestamps = [] @mutex = Mutex.new end |
Instance Method Details
#acquire ⇒ Boolean
Try to consume one retry from the budget.
25 26 27 28 29 30 31 32 33 |
# File 'lib/philiprehberger/retry_kit/budget.rb', line 25 def acquire @mutex.synchronize do prune return false if @timestamps.length >= @max_retries @timestamps << now true end end |
#exhausted? ⇒ Boolean
Returns whether the budget is exhausted.
48 49 50 |
# File 'lib/philiprehberger/retry_kit/budget.rb', line 48 def exhausted? remaining <= 0 end |
#remaining ⇒ Integer
Returns the number of remaining retries in the current window.
38 39 40 41 42 43 |
# File 'lib/philiprehberger/retry_kit/budget.rb', line 38 def remaining @mutex.synchronize do prune @max_retries - @timestamps.length end end |
#reset ⇒ self
Clear all recorded retries. Useful in tests and when manually recovering from a retry storm.
56 57 58 59 |
# File 'lib/philiprehberger/retry_kit/budget.rb', line 56 def reset @mutex.synchronize { @timestamps.clear } self end |