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.Pool.Connections do
13 @type domain :: String.t()
14 @type conn :: Pleroma.Gun.Conn.t()
16 @type t :: %__MODULE__{
17 conns: %{domain() => conn()},
21 defstruct conns: %{}, opts: []
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 = Config.get([:connections_pool, :checkin_timeout], 250)
38 GenServer.call(name, {:checkin, uri}, timeout)
41 @spec alive?(atom()) :: boolean()
43 if pid = Process.whereis(name) do
50 @spec get_state(atom()) :: t()
51 def get_state(name) do
52 GenServer.call(name, :state)
55 @spec count(atom()) :: pos_integer()
57 GenServer.call(name, :count)
60 @spec get_unused_conns(atom()) :: [{domain(), conn()}]
61 def get_unused_conns(name) do
62 GenServer.call(name, :unused_conns)
65 @spec checkout(pid(), pid(), atom()) :: :ok
66 def checkout(conn, pid, name) do
67 GenServer.cast(name, {:checkout, conn, pid})
70 @spec add_conn(atom(), String.t(), Pleroma.Gun.Conn.t()) :: :ok
71 def add_conn(name, key, conn) do
72 GenServer.cast(name, {:add_conn, key, conn})
75 @spec remove_conn(atom(), String.t()) :: :ok
76 def remove_conn(name, key) do
77 GenServer.cast(name, {:remove_conn, key})
81 def handle_cast({:add_conn, key, conn}, state) do
82 state = put_in(state.conns[key], conn)
84 Process.monitor(conn.conn)
89 def handle_cast({:checkout, conn_pid, pid}, state) do
91 with true <- Process.alive?(conn_pid),
92 {key, conn} <- find_conn(state.conns, conn_pid),
93 used_by <- List.keydelete(conn.used_by, pid, 0) do
94 conn_state = if used_by == [], do: :idle, else: conn.conn_state
96 put_in(state.conns[key], %{conn | conn_state: conn_state, used_by: used_by})
99 Logger.debug("checkout for closed conn #{inspect(conn_pid)}")
103 Logger.debug("checkout for alive conn #{inspect(conn_pid)}, but is not in state")
111 def handle_cast({:remove_conn, key}, state) do
112 state = put_in(state.conns, Map.delete(state.conns, key))
117 def handle_call({:checkin, uri}, from, state) do
118 key = "#{uri.scheme}:#{uri.host}:#{uri.port}"
120 case state.conns[key] do
121 %{conn: pid, gun_state: :up} = conn ->
122 time = :os.system_time(:second)
123 last_reference = time - conn.last_reference
124 crf = crf(last_reference, 100, conn.crf)
127 put_in(state.conns[key], %{
129 | last_reference: time,
132 used_by: [from | conn.used_by]
137 %{gun_state: :down} ->
146 def handle_call(:state, _from, state), do: {:reply, state, state}
149 def handle_call(:count, _from, state) do
150 {:reply, Enum.count(state.conns), state}
154 def handle_call(:unused_conns, _from, state) do
157 |> Enum.filter(&filter_conns/1)
158 |> Enum.sort(&sort_conns/2)
160 {:reply, unused_conns, state}
163 defp filter_conns({_, %{conn_state: :idle, used_by: []}}), do: true
164 defp filter_conns(_), do: false
166 defp sort_conns({_, c1}, {_, c2}) do
167 c1.crf <= c2.crf and c1.last_reference <= c2.last_reference
171 def handle_info({:gun_up, conn_pid, _protocol}, state) do
172 %{origin_host: host, origin_scheme: scheme, origin_port: port} = Gun.info(conn_pid)
175 case :inet.ntoa(host) do
176 {:error, :einval} -> host
180 key = "#{scheme}:#{host}:#{port}"
183 with {key, conn} <- find_conn(state.conns, conn_pid, key),
184 {true, key} <- {Process.alive?(conn_pid), key} do
185 put_in(state.conns[key], %{
195 Map.delete(state.conns, key)
199 :ok = Gun.close(conn_pid)
208 def handle_info({:gun_down, conn_pid, _protocol, _reason, _killed}, state) do
209 retries = Config.get([:connections_pool, :retry], 1)
210 # we can't get info on this pid, because pid is dead
212 with {key, conn} <- find_conn(state.conns, conn_pid),
213 {true, key} <- {Process.alive?(conn_pid), key} do
214 if conn.retries == retries do
215 :ok = Gun.close(conn.conn)
219 Map.delete(state.conns, key)
222 put_in(state.conns[key], %{
225 retries: conn.retries + 1
232 Map.delete(state.conns, key)
236 Logger.debug(":gun_down for conn which isn't found in state")
245 def handle_info({:DOWN, _ref, :process, conn_pid, reason}, state) do
246 Logger.debug("received DOWN message for #{inspect(conn_pid)} reason -> #{inspect(reason)}")
249 with {key, conn} <- find_conn(state.conns, conn_pid) do
250 Enum.each(conn.used_by, fn {pid, _ref} ->
251 Process.exit(pid, reason)
256 Map.delete(state.conns, key)
260 Logger.debug(":DOWN for conn which isn't found in state")
268 defp find_conn(conns, conn_pid) do
269 Enum.find(conns, fn {_key, conn} ->
270 conn.conn == conn_pid
274 defp find_conn(conns, conn_pid, conn_key) do
275 Enum.find(conns, fn {key, conn} ->
276 key == conn_key and conn.conn == conn_pid
280 def crf(current, steps, crf) do
281 1 + :math.pow(0.5, current / steps) * crf