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
90 Logger.debug("checkout #{inspect(conn_pid)}")
93 with true <- Process.alive?(conn_pid),
94 {key, conn} <- find_conn(state.conns, conn_pid),
95 used_by <- List.keydelete(conn.used_by, pid, 0) do
103 put_in(state.conns[key], %{conn | conn_state: conn_state, used_by: used_by})
106 Logger.debug("checkout for closed conn #{inspect(conn_pid)}")
110 Logger.debug("checkout for alive conn #{inspect(conn_pid)}, but is not in state")
118 def handle_cast({:remove_conn, key}, state) do
119 state = put_in(state.conns, Map.delete(state.conns, key))
124 def handle_call({:checkin, uri}, from, state) do
125 key = "#{uri.scheme}:#{uri.host}:#{uri.port}"
126 Logger.debug("checkin #{key}")
128 case state.conns[key] do
129 %{conn: conn, gun_state: :up} = current_conn ->
130 Logger.debug("reusing conn #{key}")
132 time = :os.system_time(:second)
133 last_reference = time - current_conn.last_reference
134 current_crf = crf(last_reference, 100, current_conn.crf)
137 put_in(state.conns[key], %{
139 | last_reference: time,
142 used_by: [from | current_conn.used_by]
145 {:reply, conn, state}
147 %{gun_state: :down} ->
156 def handle_call(:state, _from, state), do: {:reply, state, state}
159 def handle_call(:count, _from, state) do
160 {:reply, Enum.count(state.conns), state}
164 def handle_call(:unused_conns, _from, state) do
167 |> Enum.filter(fn {_k, v} ->
168 v.conn_state == :idle and v.used_by == []
170 |> Enum.sort(fn {_x_k, x}, {_y_k, y} ->
171 x.crf <= y.crf and x.last_reference <= y.last_reference
174 {:reply, unused_conns, state}
178 def handle_info({:gun_up, conn_pid, _protocol}, state) do
180 with conn_key when is_binary(conn_key) <- compose_key_gun_info(conn_pid),
181 {key, conn} <- find_conn(state.conns, conn_pid, conn_key),
182 {true, key} <- {Process.alive?(conn_pid), key} do
183 time = :os.system_time(:second)
184 last_reference = time - conn.last_reference
185 current_crf = crf(last_reference, 100, conn.crf)
187 put_in(state.conns[key], %{
190 last_reference: time,
197 Logger.debug(":gun.info caused error")
201 Logger.debug(":gun_up message for closed conn #{inspect(conn_pid)}")
205 Map.delete(state.conns, key)
209 Logger.debug(":gun_up message for conn which is not found in state")
211 :ok = Gun.close(conn_pid)
220 def handle_info({:gun_down, conn_pid, _protocol, _reason, _killed}, state) do
221 retries = Config.get([:connections_pool, :retry], 1)
222 # we can't get info on this pid, because pid is dead
224 with {key, conn} <- find_conn(state.conns, conn_pid),
225 {true, key} <- {Process.alive?(conn_pid), key} do
226 if conn.retries == retries do
227 Logger.debug("closing conn if retries is eq #{inspect(conn_pid)}")
228 :ok = Gun.close(conn.conn)
232 Map.delete(state.conns, key)
235 put_in(state.conns[key], %{
238 retries: conn.retries + 1
243 # gun can send gun_down for closed conn, maybe connection is not closed yet
244 Logger.debug(":gun_down message for closed conn #{inspect(conn_pid)}")
248 Map.delete(state.conns, key)
252 Logger.debug(":gun_down message for conn which is not found in state")
254 :ok = Gun.close(conn_pid)
263 def handle_info({:DOWN, _ref, :process, conn_pid, reason}, state) do
264 Logger.debug("received DOWM message for #{inspect(conn_pid)} reason -> #{inspect(reason)}")
267 with {key, conn} <- find_conn(state.conns, conn_pid) do
268 Enum.each(conn.used_by, fn {pid, _ref} ->
269 Process.exit(pid, reason)
274 Map.delete(state.conns, key)
278 Logger.debug(":DOWN message for conn which is not found in state")
286 defp compose_key_gun_info(pid) do
287 %{origin_host: origin_host, origin_scheme: scheme, origin_port: port} = Gun.info(pid)
290 case :inet.ntoa(origin_host) do
291 {:error, :einval} -> origin_host
295 "#{scheme}:#{host}:#{port}"
298 defp find_conn(conns, conn_pid) do
299 Enum.find(conns, fn {_key, conn} ->
300 conn.conn == conn_pid
304 defp find_conn(conns, conn_pid, conn_key) do
305 Enum.find(conns, fn {key, conn} ->
306 key == conn_key and conn.conn == conn_pid
310 def crf(current, steps, crf) do
311 1 + :math.pow(0.5, current / steps) * crf
314 def compose_uri_log(%URI{scheme: scheme, host: host, path: path}) do
315 "#{scheme}://#{host}#{path}"