From 3cdaafceebc69b9a2c8fc82108ef75a89cd260fc Mon Sep 17 00:00:00 2001 From: Wojtek Mach Date: Fri, 28 Jun 2024 12:59:51 +0200 Subject: [PATCH] `redirect`: Cancel async request before redirecting Closes #372 --- lib/req/finch.ex | 10 ++++++++++ lib/req/steps.ex | 4 ++++ test/req/finch_test.exs | 23 +++++++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/lib/req/finch.ex b/lib/req/finch.ex index c7fc07e..e870b0c 100644 --- a/lib/req/finch.ex +++ b/lib/req/finch.ex @@ -292,6 +292,16 @@ defmodule Req.Finch do defp finch_cancel(ref) do Finch.cancel_async_request(ref) + clean_responses(ref) + :ok + end + + defp clean_responses(ref) do + receive do + {^ref, _} -> clean_responses(ref) + after + 0 -> :ok + end end defp finch_name(request) do diff --git a/lib/req/steps.ex b/lib/req/steps.ex index a458183..be35e77 100644 --- a/lib/req/steps.ex +++ b/lib/req/steps.ex @@ -1691,6 +1691,10 @@ defmodule Req.Steps do redirect_count = Req.Request.get_private(request, :req_redirect_count, 0) if redirect_count < max_redirects do + with %Req.Response.Async{} <- response.body do + Req.cancel_async_response(response) + end + request = request |> build_redirect_request(response, location) diff --git a/test/req/finch_test.exs b/test/req/finch_test.exs index 07c01f2..15d5822 100644 --- a/test/req/finch_test.exs +++ b/test/req/finch_test.exs @@ -401,6 +401,29 @@ defmodule Req.FinchTest do assert resp.status == 200 assert :ok = Req.cancel_async_response(resp) end + + @tag :capture_log + test "into: :self with redirect" do + %{url: url} = + TestHelper.start_http_server(fn conn -> + Plug.Conn.send_resp(conn, 200, "ok") + end) + + %{url: url} = + TestHelper.start_http_server(fn conn -> + conn + |> Plug.Conn.put_resp_header("location", to_string(url)) + |> Plug.Conn.send_resp(307, "redirecting to #{url}") + end) + + req = + Req.new( + url: url, + into: :self + ) + + assert Req.get!(req).body |> Enum.to_list() == ["ok"] + end end describe "pool_options" do