Module: Woods::RetryAfter

Defined in:
lib/woods/retry_after.rb

Overview

Parse an HTTP Retry-After header into a number of seconds to wait.

Per RFC 9110 the header is either a non-negative integer count of seconds or an HTTP-date. Calling .to_f on the header directly (the naive approach) turns the HTTP-date form into 0.0, so a client honoring it would retry immediately and hammer a server that is actively asking it to back off. This helper handles both forms and falls back to a caller-supplied value when the header is absent or unparseable.

Class Method Summary collapse

Class Method Details

.seconds(header, fallback:, now: Time.now) ⇒ Float

Returns non-negative seconds to wait.

Parameters:

  • header (String, nil)

    the raw Retry-After header value

  • fallback (Numeric)

    seconds to use when the header is missing or unparseable

  • now (Time) (defaults to: Time.now)

    reference time for the HTTP-date form (injectable for tests)

Returns:

  • (Float)

    non-negative seconds to wait



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/woods/retry_after.rb', line 21

def seconds(header, fallback:, now: Time.now)
  value = header.to_s.strip
  return fallback.to_f if value.empty?

  # delta-seconds form: a bare non-negative integer.
  return value.to_f if value.match?(/\A\d+\z/)

  # HTTP-date form: wait until that instant, never negative.
  begin
    [Time.httpdate(value) - now, 0.0].max
  rescue ArgumentError
    fallback.to_f
  end
end