1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Pool.Connections do
10 @type domain :: String.t()
11 @type conn :: Pleroma.Gun.Conn.t()
13 @type t :: %__MODULE__{
14 conns: %{domain() => conn()},
18 defstruct conns: %{}, opts: []
21 alias Pleroma.Gun.Conn
23 @spec start_link({atom(), keyword()}) :: {:ok, pid()}
24 def start_link({name, opts}) do
25 GenServer.start_link(__MODULE__, opts, name: name)
29 def init(opts), do: {:ok, %__MODULE__{conns: %{}, opts: opts}}
31 @spec checkin(String.t() | URI.t(), atom()) :: pid() | nil
32 def checkin(url, name)
33 def checkin(url, name) when is_binary(url), do: checkin(URI.parse(url), name)
35 def checkin(%URI{} = uri, name) do
36 timeout = Pleroma.Config.get([:connections_pool, :receive_connection_timeout], 250)
45 @spec open_conn(String.t() | URI.t(), atom(), keyword()) :: :ok
46 def open_conn(url, name, opts \\ [])
47 def open_conn(url, name, opts) when is_binary(url), do: open_conn(URI.parse(url), name, opts)
49 def open_conn(%URI{} = uri, name, opts) do
50 pool_opts = Pleroma.Config.get([:connections_pool], [])
55 |> Map.put_new(:retry, pool_opts[:retry] || 0)
56 |> Map.put_new(:retry_timeout, pool_opts[:retry_timeout] || 100)
57 |> Map.put_new(:await_up_timeout, pool_opts[:await_up_timeout] || 5_000)
59 GenServer.cast(name, {:open_conn, %{opts: opts, uri: uri}})
62 @spec alive?(atom()) :: boolean()
64 pid = Process.whereis(name)
65 if pid, do: Process.alive?(pid), else: false
68 @spec get_state(atom()) :: t()
69 def get_state(name) do
70 GenServer.call(name, :state)
73 @spec checkout(pid(), pid(), atom()) :: :ok
74 def checkout(conn, pid, name) do
75 GenServer.cast(name, {:checkout, conn, pid})
79 def handle_cast({:open_conn, %{opts: opts, uri: uri}}, state) do
80 Logger.debug("opening new #{compose_uri(uri)}")
81 max_connections = state.opts[:max_connections]
83 key = compose_key(uri)
85 if Enum.count(state.conns) < max_connections do
86 open_conn(key, uri, state, opts)
88 try_to_open_conn(key, uri, state, opts)
93 def handle_cast({:checkout, conn_pid, pid}, state) do
94 Logger.debug("checkout #{inspect(conn_pid)}")
97 with true <- Process.alive?(conn_pid),
98 {key, conn} <- find_conn(state.conns, conn_pid),
99 used_by <- List.keydelete(conn.used_by, pid, 0) do
107 put_in(state.conns[key], %{conn | conn_state: conn_state, used_by: used_by})
110 Logger.debug("checkout for closed conn #{inspect(conn_pid)}")
114 Logger.debug("checkout for alive conn #{inspect(conn_pid)}, but is not in state")
122 def handle_call({:checkin, uri}, from, state) do
123 Logger.debug("checkin #{compose_uri(uri)}")
124 key = compose_key(uri)
126 case state.conns[key] do
127 %{conn: conn, gun_state: gun_state} = current_conn when gun_state == :up ->
128 Logger.debug("reusing conn #{compose_uri(uri)}")
130 with time <- :os.system_time(:second),
131 last_reference <- time - current_conn.last_reference,
132 current_crf <- crf(last_reference, 100, current_conn.crf),
134 put_in(state.conns[key], %{
136 | last_reference: time,
139 used_by: [from | current_conn.used_by]
141 {:reply, conn, state}
144 %{gun_state: gun_state} when gun_state == :down ->
153 def handle_call(:state, _from, state), do: {:reply, state, state}
156 def handle_info({:gun_up, conn_pid, _protocol}, state) do
158 with true <- Process.alive?(conn_pid),
159 conn_key when is_binary(conn_key) <- compose_key_gun_info(conn_pid),
160 {key, conn} <- find_conn(state.conns, conn_pid, conn_key),
161 time <- :os.system_time(:second),
162 last_reference <- time - conn.last_reference,
163 current_crf <- crf(last_reference, 100, conn.crf) do
164 put_in(state.conns[key], %{
167 last_reference: time,
174 Logger.debug(":gun.info caused error")
178 Logger.debug(":gun_up message for closed conn #{inspect(conn_pid)}")
183 ":gun_up message for alive conn #{inspect(conn_pid)}, but deleted from state"
186 :ok = API.close(conn_pid)
195 def handle_info({:gun_down, conn_pid, _protocol, _reason, _killed}, state) do
196 # we can't get info on this pid, because pid is dead
198 with true <- Process.alive?(conn_pid),
199 {key, conn} <- find_conn(state.conns, conn_pid) do
200 if conn.retries == 5 do
201 Logger.debug("closing conn if retries is eq 5 #{inspect(conn_pid)}")
202 :ok = API.close(conn.conn)
206 Map.delete(state.conns, key)
209 put_in(state.conns[key], %{
212 retries: conn.retries + 1
217 # gun can send gun_down for closed conn, maybe connection is not closed yet
218 Logger.debug(":gun_down message for closed conn #{inspect(conn_pid)}")
223 ":gun_down message for alive conn #{inspect(conn_pid)}, but deleted from state"
226 :ok = API.close(conn_pid)
234 defp compose_key(%URI{scheme: scheme, host: host, port: port}), do: "#{scheme}:#{host}:#{port}"
236 defp compose_key_gun_info(pid) do
238 # sometimes :gun.info can raise MatchError, which lead to pool terminate
239 %{origin_host: origin_host, origin_scheme: scheme, origin_port: port} = API.info(pid)
242 case :inet.ntoa(origin_host) do
243 {:error, :einval} -> origin_host
247 "#{scheme}:#{host}:#{port}"
253 defp find_conn(conns, conn_pid) do
254 Enum.find(conns, fn {_key, conn} ->
255 conn.conn == conn_pid
259 defp find_conn(conns, conn_pid, conn_key) do
260 Enum.find(conns, fn {key, conn} ->
261 key == conn_key and conn.conn == conn_pid
265 defp open_conn(key, uri, state, %{proxy: {proxy_host, proxy_port}} = opts) do
268 |> destination_opts()
269 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
271 with open_opts <- Map.delete(opts, :tls_opts),
272 {:ok, conn} <- API.open(proxy_host, proxy_port, open_opts),
273 {:ok, _} <- API.await_up(conn),
274 stream <- API.connect(conn, connect_opts),
275 {:response, :fin, 200, _} <- API.await(conn, stream),
277 put_in(state.conns[key], %Conn{
281 last_reference: :os.system_time(:second)
287 "Received error on opening connection with http proxy #{uri.scheme}://#{
289 }: #{inspect(error)}"
296 defp open_conn(key, uri, state, %{proxy: {proxy_type, proxy_host, proxy_port}} = opts) do
308 |> destination_opts()
309 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
310 |> Map.put(:version, version)
314 |> Map.put(:protocols, [:socks])
315 |> Map.put(:socks_opts, socks_opts)
317 with {:ok, conn} <- API.open(proxy_host, proxy_port, opts),
318 {:ok, _} <- API.await_up(conn),
320 put_in(state.conns[key], %Conn{
324 last_reference: :os.system_time(:second)
330 "Received error on opening connection with socks proxy #{uri.scheme}://#{
332 }: #{inspect(error)}"
339 defp open_conn(key, %URI{host: host, port: port} = uri, state, opts) do
340 Logger.debug("opening conn #{compose_uri(uri)}")
341 {_type, host} = Pleroma.HTTP.Adapter.domain_or_ip(host)
343 with {:ok, conn} <- API.open(host, port, opts),
344 {:ok, _} <- API.await_up(conn),
346 put_in(state.conns[key], %Conn{
350 last_reference: :os.system_time(:second)
352 Logger.debug("new conn opened #{compose_uri(uri)}")
353 Logger.debug("replying to the call #{compose_uri(uri)}")
358 "Received error on opening connection #{uri.scheme}://#{compose_uri(uri)}: #{
367 defp destination_opts(%URI{host: host, port: port}) do
368 {_type, host} = Pleroma.HTTP.Adapter.domain_or_ip(host)
369 %{host: host, port: port}
372 defp add_http2_opts(opts, "https", tls_opts) do
373 Map.merge(opts, %{protocols: [:http2], transport: :tls, tls_opts: tls_opts})
376 defp add_http2_opts(opts, _, _), do: opts
378 @spec get_unused_conns(map()) :: [{domain(), conn()}]
379 def get_unused_conns(conns) do
381 |> Enum.filter(fn {_k, v} ->
382 v.conn_state == :idle and v.used_by == []
384 |> Enum.sort(fn {_x_k, x}, {_y_k, y} ->
385 x.crf <= y.crf and x.last_reference <= y.last_reference
389 defp try_to_open_conn(key, uri, state, opts) do
390 Logger.debug("try to open conn #{compose_uri(uri)}")
392 with [{close_key, least_used} | _conns] <- get_unused_conns(state.conns),
393 :ok <- API.close(least_used.conn),
397 Map.delete(state.conns, close_key)
400 "least used conn found and closed #{inspect(least_used.conn)} #{compose_uri(uri)}"
403 open_conn(key, uri, state, opts)
405 [] -> {:noreply, state}
409 def crf(current, steps, crf) do
410 1 + :math.pow(0.5, current / steps) * crf
413 def compose_uri(%URI{} = uri), do: "#{uri.host}#{uri.path}"