ConnectionPool.Worker: Open gun conn in continue instead of init
[akkoma] / lib / pleroma / gun / connection_pool / worker.ex
1 defmodule Pleroma.Gun.ConnectionPool.Worker do
2 alias Pleroma.Gun
3 use GenServer, restart: :temporary
4
5 @registry Pleroma.Gun.ConnectionPool
6
7 def start_link([key | _] = opts) do
8 GenServer.start_link(__MODULE__, opts, name: {:via, Registry, {@registry, key}})
9 end
10
11 @impl true
12 def init([_key, _uri, _opts, _client_pid] = opts) do
13 {:ok, nil, {:continue, {:connect, opts}}}
14 end
15
16 @impl true
17 def handle_continue({:connect, [key, uri, opts, client_pid]}, _) do
18 with {:ok, conn_pid} <- Gun.Conn.open(uri, opts),
19 Process.link(conn_pid) do
20 time = :erlang.monotonic_time(:millisecond)
21
22 {_, _} =
23 Registry.update_value(@registry, key, fn _ ->
24 {conn_pid, [client_pid], 1, time}
25 end)
26
27 send(client_pid, {:conn_pid, conn_pid})
28
29 {:noreply,
30 %{key: key, timer: nil, client_monitors: %{client_pid => Process.monitor(client_pid)}},
31 :hibernate}
32 else
33 err -> {:stop, err}
34 end
35 end
36
37 @impl true
38 def handle_cast({:add_client, client_pid, send_pid_back}, %{key: key} = state) do
39 time = :erlang.monotonic_time(:millisecond)
40
41 {{conn_pid, _, _, _}, _} =
42 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
43 {conn_pid, [client_pid | used_by], crf(time - last_reference, crf), time}
44 end)
45
46 if send_pid_back, do: send(client_pid, {:conn_pid, conn_pid})
47
48 state =
49 if state.timer != nil do
50 Process.cancel_timer(state[:timer])
51 %{state | timer: nil}
52 else
53 state
54 end
55
56 ref = Process.monitor(client_pid)
57
58 state = put_in(state.client_monitors[client_pid], ref)
59 {:noreply, state, :hibernate}
60 end
61
62 @impl true
63 def handle_cast({:remove_client, client_pid}, %{key: key} = state) do
64 {{_conn_pid, used_by, _crf, _last_reference}, _} =
65 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
66 {conn_pid, List.delete(used_by, client_pid), crf, last_reference}
67 end)
68
69 {ref, state} = pop_in(state.client_monitors[client_pid])
70 Process.demonitor(ref)
71
72 timer =
73 if used_by == [] do
74 max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
75 Process.send_after(self(), :idle_close, max_idle)
76 else
77 nil
78 end
79
80 {:noreply, %{state | timer: timer}, :hibernate}
81 end
82
83 @impl true
84 def handle_info(:idle_close, state) do
85 # Gun monitors the owner process, and will close the connection automatically
86 # when it's terminated
87 {:stop, :normal, state}
88 end
89
90 # Gracefully shutdown if the connection got closed without any streams left
91 @impl true
92 def handle_info({:gun_down, _pid, _protocol, _reason, []}, state) do
93 {:stop, :normal, state}
94 end
95
96 # Otherwise, shutdown with an error
97 @impl true
98 def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams} = down_message, state) do
99 {:stop, {:error, down_message}, state}
100 end
101
102 @impl true
103 def handle_info({:DOWN, _ref, :process, pid, reason}, state) do
104 # Sometimes the client is dead before we demonitor it in :remove_client, so the message
105 # arrives anyway
106
107 case state.client_monitors[pid] do
108 nil ->
109 {:noreply, state, :hibernate}
110
111 _ref ->
112 :telemetry.execute(
113 [:pleroma, :connection_pool, :client_death],
114 %{client_pid: pid, reason: reason},
115 %{key: state.key}
116 )
117
118 handle_cast({:remove_client, pid}, state)
119 end
120 end
121
122 # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478
123 defp crf(time_delta, prev_crf) do
124 1 + :math.pow(0.5, 0.0001 * time_delta) * prev_crf
125 end
126 end