Skip to content
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

feat: add retry_count opt in the retry middleware #686

Merged
merged 1 commit into from
Jun 20, 2024
Merged
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
20 changes: 17 additions & 3 deletions lib/tesla/middleware/retry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,18 @@ defmodule Tesla.Middleware.Retry do
defp retry(env, next, %{max_retries: 0}), do: Tesla.run(env, next)

# If we're on our last retry then just run and don't handle the error
defp retry(env, next, %{max_retries: max, retries: max}) do
Tesla.run(env, next)
defp retry(env, next, %{max_retries: max, retries: max} = context) do
env
|> put_retry_count_opt(context)
|> Tesla.run(next)
end

# Otherwise we retry if we get a retriable error
defp retry(env, next, context) do
res = Tesla.run(env, next)
res =
env
|> put_retry_count_opt(context)
|> Tesla.run(next)

{:arity, should_retry_arity} = :erlang.fun_info(context.should_retry, :arity)

Expand Down Expand Up @@ -129,6 +134,15 @@ defmodule Tesla.Middleware.Retry do
:timer.sleep(delay)
end

defp put_retry_count_opt(env, %{retries: 0} = _context) do
env
end

defp put_retry_count_opt(env, context) do
opts = Keyword.put(env.opts, :retry_count, context.retries)
%{env | opts: opts}
end

defp integer_opt!(opts, key, min) do
case Keyword.fetch(opts, key) do
{:ok, value} when is_integer(value) and value >= min -> value
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defmodule Tesla.Mixfile do
use Mix.Project

@source_url "https://github.com/teamon/tesla"
@version "1.10.3"
@version "1.11.0"

def project do
[
Expand Down
10 changes: 9 additions & 1 deletion test/tesla/middleware/retry_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,15 @@ defmodule Tesla.Middleware.RetryTest do
end

test "finally pass on laggy request" do
assert {:ok, %Tesla.Env{url: "/maybe", method: :get}} = Client.get("/maybe")
assert {:ok, %Tesla.Env{url: "/maybe", method: :get}} = Client.get("/maybe") |> dbg()
end

test "pass retry_count opt" do
assert {:ok, env} = Client.get("/maybe")
assert env.opts[:retry_count] == 5

assert {:ok, env} = Client.get("/ok")
assert env.opts[:retry_count] == nil
end

test "raise if max_retries is exceeded" do
Expand Down
Loading