using atom keys in search params
[akkoma] / lib / pleroma / gun / connection_pool / worker.ex
index 25fafc64c3c4de58f9db4f28f2874292f1ab27fb..f33447cb6352c137f88e2b15757c1145bd9445b0 100644 (file)
@@ -4,32 +4,40 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
 
   @registry Pleroma.Gun.ConnectionPool
 
-  def start_link(opts) do
-    GenServer.start_link(__MODULE__, opts)
+  def start_link([key | _] = opts) do
+    GenServer.start_link(__MODULE__, opts, name: {:via, Registry, {@registry, key}})
   end
 
   @impl true
-  def init([uri, key, opts, client_pid]) do
-    time = :os.system_time(:second)
-    # Register before opening connection to prevent race conditions
-    with {:ok, _owner} <- Registry.register(@registry, key, {nil, [client_pid], 1, time}),
-         {:ok, conn_pid} <- Gun.Conn.open(uri, opts),
+  def init([_key, _uri, _opts, _client_pid] = opts) do
+    {:ok, nil, {:continue, {:connect, opts}}}
+  end
+
+  @impl true
+  def handle_continue({:connect, [key, uri, opts, client_pid]}, _) do
+    with {:ok, conn_pid} <- Gun.Conn.open(uri, opts),
          Process.link(conn_pid) do
+      time = :erlang.monotonic_time(:millisecond)
+
       {_, _} =
-        Registry.update_value(@registry, key, fn {_, used_by, crf, last_reference} ->
-          {conn_pid, used_by, crf, last_reference}
+        Registry.update_value(@registry, key, fn _ ->
+          {conn_pid, [client_pid], 1, time}
         end)
 
       send(client_pid, {:conn_pid, conn_pid})
-      {:ok, %{key: key, timer: nil}, :hibernate}
+
+      {:noreply,
+       %{key: key, timer: nil, client_monitors: %{client_pid => Process.monitor(client_pid)}},
+       :hibernate}
     else
-      err -> {:stop, err}
+      err ->
+        {:stop, {:shutdown, err}, nil}
     end
   end
 
   @impl true
   def handle_cast({:add_client, client_pid, send_pid_back}, %{key: key} = state) do
-    time = :os.system_time(:second)
+    time = :erlang.monotonic_time(:millisecond)
 
     {{conn_pid, _, _, _}, _} =
       Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
@@ -46,6 +54,9 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
         state
       end
 
+    ref = Process.monitor(client_pid)
+
+    state = put_in(state.client_monitors[client_pid], ref)
     {:noreply, state, :hibernate}
   end
 
@@ -56,6 +67,9 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
         {conn_pid, List.delete(used_by, client_pid), crf, last_reference}
       end)
 
+    {ref, state} = pop_in(state.client_monitors[client_pid])
+    Process.demonitor(ref)
+
     timer =
       if used_by == [] do
         max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
@@ -86,8 +100,28 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
     {:stop, {:error, down_message}, state}
   end
 
+  @impl true
+  def handle_info({:DOWN, _ref, :process, pid, reason}, state) do
+    # Sometimes the client is dead before we demonitor it in :remove_client, so the message
+    # arrives anyway
+
+    case state.client_monitors[pid] do
+      nil ->
+        {:noreply, state, :hibernate}
+
+      _ref ->
+        :telemetry.execute(
+          [:pleroma, :connection_pool, :client_death],
+          %{client_pid: pid, reason: reason},
+          %{key: state.key}
+        )
+
+        handle_cast({:remove_client, pid}, state)
+    end
+  end
+
   # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478
   defp crf(time_delta, prev_crf) do
-    1 + :math.pow(0.5, time_delta / 100) * prev_crf
+    1 + :math.pow(0.5, 0.0001 * time_delta) * prev_crf
   end
 end