Class: ActiveHarness::Http::RetryPolicy

Inherits:
Object
  • Object
show all
Defined in:
lib/active_harness/http/retry_policy.rb

Overview

Wraps a block with automatic retry on transient errors. Uses exponential backoff: delay doubles after each failed attempt.

Example:

RetryPolicy.new(max_attempts: 3, base_delay: 0.5).run do
  http_client.post(...)
end

Custom errors:

RetryPolicy.new(errors: [MyTransientError]).run { ... }

Constant Summary collapse

DEFAULT_ERRORS =
[
  Errors::TimeoutError,
  Errors::RateLimitError,
  Errors::ProviderUnavailableError,
  Errors::ServerError
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(max_attempts: 3, base_delay: 1.0, errors: DEFAULT_ERRORS) ⇒ RetryPolicy

Returns a new instance of RetryPolicy.

Parameters:

  • max_attempts (Integer) (defaults to: 3)

    total number of attempts (first + retries)

  • base_delay (Float) (defaults to: 1.0)

    delay before 1st retry in seconds; doubles each round

  • errors (Array) (defaults to: DEFAULT_ERRORS)

    error classes that trigger a retry



25
26
27
28
29
# File 'lib/active_harness/http/retry_policy.rb', line 25

def initialize(max_attempts: 3, base_delay: 1.0, errors: DEFAULT_ERRORS)
  @max_attempts = max_attempts
  @base_delay   = base_delay
  @errors       = errors
end

Instance Method Details

#runObject

Yield Returns:

  • (Object)

    result of the block on success

Raises:

  • last error after all attempts are exhausted



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/active_harness/http/retry_policy.rb', line 33

def run
  attempt = 0
  begin
    attempt += 1
    yield
  rescue *@errors
    raise if attempt >= @max_attempts

    sleep(@base_delay * (2**(attempt - 1)))
    retry
  end
end