Skip to content

retry: handle unexpected float delays #464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/req/response.ex
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ defmodule Req.Response do
{seconds, ""} ->
:timer.seconds(seconds)

# when value is non-RFC9110 compliant (i.e. float) round up
{seconds, _} ->
(seconds + 1) |> :timer.seconds()

:error ->
delay_value
|> Req.Utils.parse_http_date!()
Expand Down
39 changes: 39 additions & 0 deletions test/req/steps_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1771,6 +1771,45 @@ defmodule Req.StepsTest do
end
end

describe "get_retry_after" do
test "returns nil when no retry-after header exists" do
response = Req.Response.new()
assert Req.Response.get_retry_after(response) == nil
end

test "converts integer seconds to milliseconds" do
response = Req.Response.new() |> Req.Response.put_header("retry-after", "30")
assert Req.Response.get_retry_after(response) == :timer.seconds(30)
end

test "rounds up non-RFC-compliant float values" do
response = Req.Response.new() |> Req.Response.put_header("retry-after", "0.123")
assert Req.Response.get_retry_after(response) == :timer.seconds(1)
end

test "parses HTTP date and calculates delay" do
# Set a future date for consistent testing
future_date = DateTime.utc_now() |> DateTime.add(60, :second)
formatted_date = Req.Utils.format_http_date(future_date)

response = Req.Response.new() |> Req.Response.put_header("retry-after", formatted_date)

# The result should be approximately 6000 milliseconds, but need to add some padding for the time it takes to process
delay = Req.Response.get_retry_after(response)
assert delay >= :timer.seconds(58)
assert delay <= :timer.seconds(60)
end

test "returns zero for past HTTP date" do
past_date = DateTime.utc_now() |> DateTime.add(-60, :second)
formatted_date = Req.Utils.format_http_date(past_date)

response = Req.Response.new() |> Req.Response.put_header("retry-after", formatted_date)

assert Req.Response.get_retry_after(response) == 0
end
end

@tag :tmp_dir
test "cache", c do
pid = self()
Expand Down