URL passed to helper is already MediaProxy
[akkoma] / lib / pleroma / gun / connection_pool / worker.ex
index a61892c60aa384ecc89a0d5247506e72eb38b81e..c36332817d1c585a0f4776468f104bae639ffe05 100644 (file)
@@ -36,10 +36,18 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
   end
 
   @impl true
-  def handle_cast({:add_client, client_pid, send}, state) do
+  def handle_cast({:add_client, client_pid}, state) do
     case handle_call(:add_client, {client_pid, nil}, state) do
       {:reply, conn_pid, state, :hibernate} ->
-        if send, do: send(client_pid, {:conn_pid, conn_pid})
+        send(client_pid, {:conn_pid, conn_pid})
+        {:noreply, state, :hibernate}
+    end
+  end
+
+  @impl true
+  def handle_cast({:remove_client, client_pid}, state) do
+    case handle_call(:remove_client, {client_pid, nil}, state) do
+      {:reply, _, state, :hibernate} ->
         {:noreply, state, :hibernate}
     end
   end
@@ -75,17 +83,25 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
       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)
-        Process.send_after(self(), :idle_close, max_idle)
+    # DOWN message can receive right after `remove_client` call and cause worker to terminate
+    state =
+      if is_nil(ref) do
+        state
       else
-        nil
+        Process.demonitor(ref)
+
+        timer =
+          if used_by == [] do
+            max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
+            Process.send_after(self(), :idle_close, max_idle)
+          else
+            nil
+          end
+
+        %{state | timer: timer}
       end
 
-    {:reply, :ok, %{state | timer: timer}, :hibernate}
+    {:reply, :ok, state, :hibernate}
   end
 
   @impl true
@@ -95,16 +111,21 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
     {:stop, :normal, state}
   end
 
+  @impl true
+  def handle_info({:gun_up, _pid, _protocol}, state) do
+    {:noreply, state, :hibernate}
+  end
+
   # Gracefully shutdown if the connection got closed without any streams left
   @impl true
   def handle_info({:gun_down, _pid, _protocol, _reason, []}, state) do
     {:stop, :normal, state}
   end
 
-  # Otherwise, shutdown with an error
+  # Otherwise, wait for retry
   @impl true
-  def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams} = down_message, state) do
-    {:stop, {:error, down_message}, state}
+  def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams}, state) do
+    {:noreply, state, :hibernate}
   end
 
   @impl true
@@ -115,7 +136,7 @@ defmodule Pleroma.Gun.ConnectionPool.Worker do
       %{key: state.key}
     )
 
-    handle_cast({:remove_client, pid, false}, state)
+    handle_cast({:remove_client, pid}, state)
   end
 
   # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478