Merge branch 'develop' into issue/1023
[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.Gun.ConnectionPool
9 alias Pleroma.HTTP.AdapterHelper
10
11 require Logger
12
13 @defaults [
14 connect_timeout: 5_000,
15 domain_lookup_timeout: 5_000,
16 tls_handshake_timeout: 5_000,
17 retry: 0,
18 retry_timeout: 1000,
19 await_up_timeout: 5_000
20 ]
21
22 @spec options(keyword(), URI.t()) :: keyword()
23 def options(incoming_opts \\ [], %URI{} = uri) do
24 proxy =
25 Pleroma.Config.get([:http, :proxy_url])
26 |> AdapterHelper.format_proxy()
27
28 config_opts = Pleroma.Config.get([:http, :adapter], [])
29
30 @defaults
31 |> Keyword.merge(config_opts)
32 |> add_scheme_opts(uri)
33 |> AdapterHelper.maybe_add_proxy(proxy)
34 |> Keyword.merge(incoming_opts)
35 end
36
37 defp add_scheme_opts(opts, %{scheme: "http"}), do: opts
38
39 defp add_scheme_opts(opts, %{scheme: "https"}) do
40 opts
41 |> Keyword.put(:certificates_verification, true)
42 end
43
44 @spec get_conn(URI.t(), keyword()) :: {:ok, keyword()} | {:error, atom()}
45 def get_conn(uri, opts) do
46 case ConnectionPool.get_conn(uri, opts) do
47 {:ok, conn_pid} -> {:ok, Keyword.merge(opts, conn: conn_pid, close_conn: false)}
48 err -> err
49 end
50 end
51
52 @prefix Pleroma.Gun.ConnectionPool
53 def limiter_setup do
54 wait = Pleroma.Config.get([:connections_pool, :connection_acquisition_wait])
55 retries = Pleroma.Config.get([:connections_pool, :connection_acquisition_retries])
56
57 :pools
58 |> Pleroma.Config.get([])
59 |> Enum.each(fn {name, opts} ->
60 max_running = Keyword.get(opts, :size, 50)
61 max_waiting = Keyword.get(opts, :max_waiting, 10)
62
63 result =
64 ConcurrentLimiter.new(:"#{@prefix}.#{name}", max_running, max_waiting,
65 wait: wait,
66 max_retries: retries
67 )
68
69 case result do
70 :ok -> :ok
71 {:error, :existing} -> :ok
72 e -> raise e
73 end
74 end)
75
76 :ok
77 end
78 end