Skip to content

Commit

Permalink
feat: add retry_count opt in the retry middleware (#686)
Browse files Browse the repository at this point in the history
  • Loading branch information
yordis authored Jun 20, 2024
1 parent ec423d7 commit a173a47
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
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

0 comments on commit a173a47

Please sign in to comment.