59fd5493cc7c1cb48f7b79ca3577cbbbd6a48b4f
[akkoma] / lib / pleroma / reverse_proxy / client / tesla.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ReverseProxy.Client.Tesla do
6 @behaviour Pleroma.ReverseProxy.Client
7
8 @type headers() :: [{String.t(), String.t()}]
9 @type status() :: pos_integer()
10
11 @spec request(atom(), String.t(), headers(), String.t(), keyword()) ::
12 {:ok, status(), headers}
13 | {:ok, status(), headers, map()}
14 | {:error, atom() | String.t()}
15 | no_return()
16
17 @impl true
18 def request(method, url, headers, body, opts \\ []) do
19 check_adapter()
20
21 opts = Keyword.put(opts, :body_as, :chunks)
22
23 with {:ok, response} <-
24 Pleroma.HTTP.request(
25 method,
26 url,
27 body,
28 headers,
29 opts
30 ) do
31 if is_map(response.body) and method != :head do
32 {:ok, response.status, response.headers, response.body}
33 else
34 {:ok, response.status, response.headers}
35 end
36 else
37 {:error, error} -> {:error, error}
38 end
39 end
40
41 @impl true
42 @spec stream_body(map()) ::
43 {:ok, binary(), map()} | {:error, atom() | String.t()} | :done | no_return()
44 def stream_body(%{pid: _pid, fin: true}) do
45 :done
46 end
47
48 def stream_body(client) do
49 case read_chunk!(client) do
50 {:fin, body} ->
51 {:ok, body, Map.put(client, :fin, true)}
52
53 {:nofin, part} ->
54 {:ok, part, client}
55
56 {:error, error} ->
57 {:error, error}
58 end
59 end
60
61 defp read_chunk!(%{pid: pid, stream: stream, opts: opts}) do
62 adapter = check_adapter()
63 adapter.read_chunk(pid, stream, opts)
64 end
65
66 @impl true
67 @spec close(map) :: :ok | no_return()
68 def close(%{pid: _pid}) do
69 end
70
71 defp check_adapter do
72 adapter = Application.get_env(:tesla, :adapter)
73
74 adapter
75 end
76 end