Skip to content

Commit

Permalink
initial request_stream implementation for Tesla
Browse files Browse the repository at this point in the history
  • Loading branch information
mwhitworth committed Apr 30, 2024
1 parent 909173c commit 2c6dec9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
23 changes: 23 additions & 0 deletions lib/reverse_proxy_plug/http_client/adapters/tesla.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ if Code.ensure_loaded?(Tesla) do

@behaviour HTTPClient

@tesla_version Application.spec(:tesla, :vsn) |> to_string() |> Version.parse!()
@minimum_version_for_stream Version.parse!("1.9.0")

@impl HTTPClient
def request(%HTTPClient.Request{options: options} = request) do
{client, opts} = Keyword.pop(options, :tesla_client)
Expand Down Expand Up @@ -50,5 +53,25 @@ if Code.ensure_loaded?(Tesla) do
{:error, %HTTPClient.Error{reason: error}}
end
end

if Version.compare(@tesla_version, @minimum_version_for_stream) in [:gt, :eq] do
@impl HTTPClient
def request_stream(%HTTPClient.Request{options: options} = req) do
case request(%{req | options: Keyword.merge(options, adapter: [response: :stream])}) do
{:ok, %HTTPClient.Response{status_code: status_code, headers: headers, body: body}} ->
{:ok,
Stream.concat(
[
{:status, status_code},
{:headers, headers}
],
Stream.map(body, &{:chunk, &1})
)}

{:error, _} = error ->
error
end
end
end
end
end
14 changes: 0 additions & 14 deletions test/reverse_proxy_plug_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,6 @@ defmodule ReverseProxyPlugTest do
assert conn.resp_body == Jason.encode!(body)
end

test "throws an error if :stream mode is used with the Tesla adapter" do
proxy_opts =
Keyword.merge(@opts,
client: ReverseProxyPlug.HTTPClient.Adapters.Tesla,
client_options: [tesla_client: Tesla.client([], ReverseProxyPlug.TeslaMock)],
response_mode: :stream
)

assert_raise ArgumentError, fn ->
conn(:get, "/")
|> ReverseProxyPlug.call(ReverseProxyPlug.init(proxy_opts))
end
end

test "does not add transfer-encoding header to response" do
headers = [{"host", "example.com"}, {"content-length", "42"}]

Expand Down

0 comments on commit 2c6dec9

Please sign in to comment.