Fix MastoAPI.AuthControllerTest, json_response(:no_content) --> empty_json_response()
[akkoma] / lib / pleroma / http / adapter_helper / gun.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.HTTP.AdapterHelper.Gun do
6 @behaviour Pleroma.HTTP.AdapterHelper
7
8 alias Pleroma.Config
9 alias Pleroma.Gun.ConnectionPool
10 alias Pleroma.HTTP.AdapterHelper
11
12 require Logger
13
14 @defaults [
15 connect_timeout: 5_000,
16 domain_lookup_timeout: 5_000,
17 tls_handshake_timeout: 5_000,
18 retry: 1,
19 retry_timeout: 1000,
20 await_up_timeout: 5_000
21 ]
22
23 @type pool() :: :federation | :upload | :media | :default
24
25 @spec options(keyword(), URI.t()) :: keyword()
26 def options(incoming_opts \\ [], %URI{} = uri) do
27 proxy =
28 [:http, :proxy_url]
29 |> Config.get()
30 |> AdapterHelper.format_proxy()
31
32 config_opts = Config.get([:http, :adapter], [])
33
34 @defaults
35 |> Keyword.merge(config_opts)
36 |> add_scheme_opts(uri)
37 |> AdapterHelper.maybe_add_proxy(proxy)
38 |> Keyword.merge(incoming_opts)
39 |> put_timeout()
40 end
41
42 defp add_scheme_opts(opts, %{scheme: "http"}), do: opts
43
44 defp add_scheme_opts(opts, %{scheme: "https"}) do
45 Keyword.put(opts, :certificates_verification, true)
46 end
47
48 defp put_timeout(opts) do
49 # this is the timeout to receive a message from Gun
50 Keyword.put_new(opts, :timeout, pool_timeout(opts[:pool]))
51 end
52
53 @spec pool_timeout(pool()) :: non_neg_integer()
54 def pool_timeout(pool) do
55 default = Config.get([:pools, :default, :timeout], 5_000)
56
57 Config.get([:pools, pool, :timeout], default)
58 end
59
60 @spec get_conn(URI.t(), keyword()) :: {:ok, keyword()} | {:error, atom()}
61 def get_conn(uri, opts) do
62 case ConnectionPool.get_conn(uri, opts) do
63 {:ok, conn_pid} -> {:ok, Keyword.merge(opts, conn: conn_pid, close_conn: false)}
64 err -> err
65 end
66 end
67
68 @prefix Pleroma.Gun.ConnectionPool
69 def limiter_setup do
70 wait = Config.get([:connections_pool, :connection_acquisition_wait])
71 retries = Config.get([:connections_pool, :connection_acquisition_retries])
72
73 :pools
74 |> Config.get([])
75 |> Enum.each(fn {name, opts} ->
76 max_running = Keyword.get(opts, :size, 50)
77 max_waiting = Keyword.get(opts, :max_waiting, 10)
78
79 result =
80 ConcurrentLimiter.new(:"#{@prefix}.#{name}", max_running, max_waiting,
81 wait: wait,
82 max_retries: retries
83 )
84
85 case result do
86 :ok -> :ok
87 {:error, :existing} -> :ok
88 end
89 end)
90
91 :ok
92 end
93 end