1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.ReverseProxy.Client.Tesla do
6 @behaviour Pleroma.ReverseProxy.Client
8 @type headers() :: [{String.t(), String.t()}]
9 @type status() :: pos_integer()
11 @spec request(atom(), String.t(), headers(), String.t(), keyword()) ::
12 {:ok, status(), headers}
13 | {:ok, status(), headers, map()}
14 | {:error, atom() | String.t()}
18 def request(method, url, headers, body, opts \\ []) do
21 opts = Keyword.put(opts, :body_as, :chunks)
23 with {:ok, response} <-
29 Keyword.put(opts, :adapter, opts)
31 if is_map(response.body) and method != :head do
32 {:ok, response.status, response.headers, response.body}
34 {:ok, response.status, response.headers}
37 {:error, error} -> {:error, error}
42 @spec stream_body(map()) ::
43 {:ok, binary(), map()} | {:error, atom() | String.t()} | :done | no_return()
44 def stream_body(%{pid: pid, opts: opts, fin: true}) do
45 # if connection was reused, but in tesla were redirects,
46 # tesla returns new opened connection, which must be closed manually
47 if opts[:old_conn], do: Tesla.Adapter.Gun.close(pid)
48 # if there were redirects we need to checkout old conn
49 conn = opts[:old_conn] || opts[:conn]
51 if conn, do: :ok = Pleroma.Pool.Connections.checkout(conn, self(), :gun_connections)
56 def stream_body(client) do
57 case read_chunk!(client) do
59 {:ok, body, Map.put(client, :fin, true)}
69 defp read_chunk!(%{pid: pid, stream: stream, opts: opts}) do
70 adapter = check_adapter()
71 adapter.read_chunk(pid, stream, opts)
75 @spec close(map) :: :ok | no_return()
76 def close(%{pid: pid}) do
77 adapter = check_adapter()
82 adapter = Application.get_env(:tesla, :adapter)
84 unless adapter == Tesla.Adapter.Gun do
85 raise "#{adapter} doesn't support reading body in chunks"