1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP.AdapterHelper.Gun do
6 @behaviour Pleroma.HTTP.AdapterHelper
8 alias Pleroma.HTTP.AdapterHelper
12 alias Pleroma.Pool.Connections
15 connect_timeout: 5_000,
16 domain_lookup_timeout: 5_000,
17 tls_handshake_timeout: 5_000,
20 await_up_timeout: 5_000
23 @spec options(keyword(), URI.t()) :: keyword()
24 def options(connection_opts \\ [], %URI{} = uri) do
25 proxy = Pleroma.Config.get([:http, :proxy_url], nil)
28 |> Keyword.merge(Pleroma.Config.get([:http, :adapter], []))
30 |> add_scheme_opts(uri)
31 |> AdapterHelper.maybe_add_proxy(AdapterHelper.format_proxy(proxy))
32 |> maybe_get_conn(uri, connection_opts)
35 @spec after_request(keyword()) :: :ok
36 def after_request(opts) do
37 with conn when not is_nil(conn) <- opts[:conn],
38 body_as when body_as != :chunks <- opts[:body_as] do
39 Connections.checkout(conn, self(), :gun_connections)
45 defp add_original(opts, %URI{host: host, port: port}) do
46 formatted_host = format_host(host)
48 Keyword.put(opts, :original, "#{formatted_host}:#{port}")
51 defp add_scheme_opts(opts, %URI{scheme: "http"}), do: opts
53 defp add_scheme_opts(opts, %URI{scheme: "https", host: host, port: port}) do
55 certificates_verification: true,
58 cacertfile: CAStore.file_path(),
60 reuse_sessions: false,
61 verify_fun: {&:ssl_verify_hostname.verify_fun/3, [check_hostname: format_host(host)]},
68 Keyword.put(adapter_opts, :transport, :tls)
73 Keyword.merge(opts, adapter_opts)
76 defp maybe_get_conn(adapter_opts, uri, connection_opts) do
77 {receive_conn?, opts} =
79 |> Keyword.merge(connection_opts)
80 |> Keyword.pop(:receive_conn, true)
82 if Connections.alive?(:gun_connections) and receive_conn? do
83 try_to_get_conn(uri, opts)
89 defp try_to_get_conn(uri, opts) do
90 case Connections.checkin(uri, :gun_connections) do
93 "Gun connections pool checkin was not successful. Trying to open conn for next request."
96 Task.start(fn -> Pleroma.Gun.Conn.open(uri, :gun_connections, opts) end)
99 conn when is_pid(conn) ->
100 Logger.debug("received conn #{inspect(conn)} #{Connections.compose_uri_log(uri)}")
103 |> Keyword.put(:conn, conn)
104 |> Keyword.put(:close_conn, false)
108 @spec format_host(String.t()) :: charlist()
109 def format_host(host) do
110 host_charlist = to_charlist(host)
112 case :inet.parse_address(host_charlist) do
114 :idna.encode(host_charlist)