removing unnecessary with
[akkoma] / lib / pleroma / reverse_proxy / client / tesla.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.ReverseProxy.Client.Tesla do
6 @type headers() :: [{String.t(), String.t()}]
7 @type status() :: pos_integer()
8
9 @behaviour Pleroma.ReverseProxy.Client
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.merge(opts, body_as: :chunks)
22
23 with {:ok, response} <-
24 Pleroma.HTTP.request(
25 method,
26 url,
27 body,
28 headers,
29 Keyword.put(opts, :adapter, 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()) :: {:ok, binary(), map()} | {:error, atom() | String.t()} | :done
43 def stream_body(%{pid: pid, opts: opts, fin: true}) do
44 # if connection was reused, but in tesla were redirects,
45 # tesla returns new opened connection, which must be closed manually
46 if opts[:old_conn], do: Tesla.Adapter.Gun.close(pid)
47 # if there were redirects we need to checkout old conn
48 conn = opts[:old_conn] || opts[:conn]
49
50 if conn, do: :ok = Pleroma.Pool.Connections.checkout(conn, self(), :gun_connections)
51
52 :done
53 end
54
55 def stream_body(client) do
56 case read_chunk!(client) do
57 {:fin, body} ->
58 {:ok, body, Map.put(client, :fin, true)}
59
60 {:nofin, part} ->
61 {:ok, part, client}
62
63 {:error, error} ->
64 {:error, error}
65 end
66 end
67
68 defp read_chunk!(%{pid: pid, stream: stream, opts: opts}) do
69 adapter = check_adapter()
70 adapter.read_chunk(pid, stream, opts)
71 end
72
73 @impl true
74 @spec close(map) :: :ok | no_return()
75 def close(%{pid: pid}) do
76 adapter = check_adapter()
77 adapter.close(pid)
78 end
79
80 defp check_adapter do
81 adapter = Application.get_env(:tesla, :adapter)
82
83 unless adapter == Tesla.Adapter.Gun do
84 raise "#{adapter} doesn't support reading body in chunks"
85 end
86
87 adapter
88 end
89 end