From a173a47432d9739c911ef14a5788e15e0d8e6799 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Thu, 20 Jun 2024 04:08:25 -0400 Subject: [PATCH] feat: add retry_count opt in the retry middleware (#686) --- lib/tesla/middleware/retry.ex | 20 +++++++++++++++++--- mix.exs | 2 +- test/tesla/middleware/retry_test.exs | 10 +++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/tesla/middleware/retry.ex b/lib/tesla/middleware/retry.ex index aaefed139..45754ef53 100644 --- a/lib/tesla/middleware/retry.ex +++ b/lib/tesla/middleware/retry.ex @@ -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) @@ -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 diff --git a/mix.exs b/mix.exs index 8cb62d05b..ebb3b9467 100644 --- a/mix.exs +++ b/mix.exs @@ -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 [ diff --git a/test/tesla/middleware/retry_test.exs b/test/tesla/middleware/retry_test.exs index 351d9d3ad..dc02e430c 100644 --- a/test/tesla/middleware/retry_test.exs +++ b/test/tesla/middleware/retry_test.exs @@ -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