Class: Philiprehberger::RetryKit::Budget

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(max_retries:, window:) ⇒ Budget

Returns a new instance of Budget.

Parameters:

  • max_retries (Integer)

    maximum number of retries allowed in the window

  • window (Numeric)

    sliding window duration in seconds



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

#acquireBoolean

Try to consume one retry from the budget.

Returns:

  • (Boolean)

    true if a retry was consumed, false if budget is exhausted



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.

Returns:

  • (Boolean)


48
49
50
# File 'lib/philiprehberger/retry_kit/budget.rb', line 48

def exhausted?
  remaining <= 0
end

#remainingInteger

Returns the number of remaining retries in the current window.

Returns:

  • (Integer)


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

#resetself

Clear all recorded retries. Useful in tests and when manually recovering from a retry storm.

Returns:

  • (self)


56
57
58
59
# File 'lib/philiprehberger/retry_kit/budget.rb', line 56

def reset
  @mutex.synchronize { @timestamps.clear }
  self
end