1 defmodule Pleroma.Gun.ConnectionPool.Worker do
3 use GenServer, restart: :temporary
5 @registry Pleroma.Gun.ConnectionPool
7 def start_link(opts) do
8 GenServer.start_link(__MODULE__, opts)
12 def init([uri, key, opts, client_pid]) do
13 time = :os.system_time(:second)
14 # Register before opening connection to prevent race conditions
15 with {:ok, _owner} <- Registry.register(@registry, key, {nil, [client_pid], 1, time}),
16 {:ok, conn_pid} <- Gun.Conn.open(uri, opts),
17 Process.link(conn_pid) do
19 Registry.update_value(@registry, key, fn {_, used_by, crf, last_reference} ->
20 {conn_pid, used_by, crf, last_reference}
23 send(client_pid, {:conn_pid, conn_pid})
24 {:ok, %{key: key, timer: nil}, :hibernate}
31 def handle_cast({:add_client, client_pid, send_pid_back}, %{key: key} = state) do
32 time = :os.system_time(:second)
34 {{conn_pid, _, _, _}, _} =
35 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
36 {conn_pid, [client_pid | used_by], crf(time - last_reference, crf), time}
39 if send_pid_back, do: send(client_pid, {:conn_pid, conn_pid})
42 if state.timer != nil do
43 Process.cancel_timer(state[:timer])
49 {:noreply, state, :hibernate}
53 def handle_cast({:remove_client, client_pid}, %{key: key} = state) do
54 {{_conn_pid, used_by, _crf, _last_reference}, _} =
55 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
56 {conn_pid, List.delete(used_by, client_pid), crf, last_reference}
61 max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
62 Process.send_after(self(), :idle_close, max_idle)
67 {:noreply, %{state | timer: timer}, :hibernate}
71 def handle_info(:idle_close, state) do
72 # Gun monitors the owner process, and will close the connection automatically
73 # when it's terminated
74 {:stop, :normal, state}
77 # Gracefully shutdown if the connection got closed without any streams left
79 def handle_info({:gun_down, _pid, _protocol, _reason, []}, state) do
80 {:stop, :normal, state}
83 # Otherwise, shutdown with an error
85 def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams} = down_message, state) do
86 {:stop, {:error, down_message}, state}
89 # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478
90 defp crf(time_delta, prev_crf) do
91 1 + :math.pow(0.5, time_delta / 100) * prev_crf