2c35745614baea1d226314620836f217b7b74a49
[akkoma] / lib / pleroma / pool / request.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.Pool.Request do
6 use GenServer
7
8 require Logger
9
10 def start_link(args) do
11 GenServer.start_link(__MODULE__, args)
12 end
13
14 @impl true
15 def init(_), do: {:ok, []}
16
17 @spec execute(pid() | atom(), Tesla.Client.t(), keyword(), pos_integer()) ::
18 {:ok, Tesla.Env.t()} | {:error, any()}
19 def execute(pid, client, request, timeout) do
20 GenServer.call(pid, {:execute, client, request}, timeout)
21 end
22
23 @impl true
24 def handle_call({:execute, client, request}, _from, state) do
25 response = Pleroma.HTTP.request_try(client, request)
26
27 {:reply, response, state}
28 end
29
30 @impl true
31 def handle_info({:gun_data, _conn, stream, _, _}, state) do
32 # in some cases if we reuse conn and got {:error, :body_too_large}
33 # gun continues to send messages to this process,
34 # so we flush messages for this request
35 :ok = :gun.flush(stream)
36
37 {:noreply, state}
38 end
39
40 @impl true
41 def handle_info({:gun_up, _conn, _protocol}, state) do
42 {:noreply, state}
43 end
44
45 @impl true
46 def handle_info({:gun_down, _conn, _protocol, _reason, _killed}, state) do
47 # don't flush messages here, because gun can reconnect
48 {:noreply, state}
49 end
50
51 @impl true
52 def handle_info({:gun_error, _conn, stream, _error}, state) do
53 :ok = :gun.flush(stream)
54 {:noreply, state}
55 end
56
57 @impl true
58 def handle_info({:gun_push, _conn, _stream, _new_stream, _method, _uri, _headers}, state) do
59 {:noreply, state}
60 end
61
62 @impl true
63 def handle_info({:gun_response, _conn, _stream, _, _status, _headers}, state) do
64 {:noreply, state}
65 end
66
67 @impl true
68 def handle_info(msg, state) do
69 Logger.warn("Received unexpected message #{inspect(__MODULE__)} #{inspect(msg)}")
70 {:noreply, state}
71 end
72 end