1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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 alias Pleroma.Gun.ConnectionPool
10 @type headers() :: [{String.t(), String.t()}]
11 @type status() :: pos_integer()
13 @spec request(atom(), String.t(), headers(), String.t(), keyword()) ::
14 {:ok, status(), headers}
15 | {:ok, status(), headers, map()}
16 | {:error, atom() | String.t()}
20 def request(method, url, headers, body, opts \\ []) do
23 opts = Keyword.put(opts, :body_as, :chunks)
25 with {:ok, response} <-
33 if is_map(response.body) and method != :head do
34 {:ok, response.status, response.headers, response.body}
36 conn_pid = response.opts[:adapter][:conn]
37 ConnectionPool.release_conn(conn_pid)
38 {:ok, response.status, response.headers}
41 {:error, error} -> {:error, error}
46 @spec stream_body(map()) ::
47 {:ok, binary(), map()} | {:error, atom() | String.t()} | :done | no_return()
48 def stream_body(%{pid: pid, fin: true}) do
49 ConnectionPool.release_conn(pid)
53 def stream_body(client) do
54 case read_chunk!(client) do
56 {:ok, body, Map.put(client, :fin, true)}
66 defp read_chunk!(%{pid: pid, stream: stream, opts: opts}) do
67 adapter = check_adapter()
68 adapter.read_chunk(pid, stream, opts)
72 @spec close(map) :: :ok | no_return()
73 def close(%{pid: pid}) do
74 ConnectionPool.release_conn(pid)
78 adapter = Application.get_env(:tesla, :adapter)
80 unless adapter == Tesla.Adapter.Gun do
81 raise "#{adapter} doesn't support reading body in chunks"