a61892c60aa384ecc89a0d5247506e72eb38b81e
[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 ->
34 {:stop, {:shutdown, err}, nil}
35 end
36 end
37
38 @impl true
39 def handle_cast({:add_client, client_pid, send}, state) do
40 case handle_call(:add_client, {client_pid, nil}, state) do
41 {:reply, conn_pid, state, :hibernate} ->
42 if send, do: send(client_pid, {:conn_pid, conn_pid})
43 {:noreply, state, :hibernate}
44 end
45 end
46
47 @impl true
48 def handle_call(:add_client, {client_pid, _}, %{key: key} = state) do
49 time = :erlang.monotonic_time(:millisecond)
50
51 {{conn_pid, _, _, _}, _} =
52 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
53 {conn_pid, [client_pid | used_by], crf(time - last_reference, crf), time}
54 end)
55
56 state =
57 if state.timer != nil do
58 Process.cancel_timer(state[:timer])
59 %{state | timer: nil}
60 else
61 state
62 end
63
64 ref = Process.monitor(client_pid)
65
66 state = put_in(state.client_monitors[client_pid], ref)
67 {:reply, conn_pid, state, :hibernate}
68 end
69
70 @impl true
71 def handle_call(:remove_client, {client_pid, _}, %{key: key} = state) do
72 {{_conn_pid, used_by, _crf, _last_reference}, _} =
73 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
74 {conn_pid, List.delete(used_by, client_pid), crf, last_reference}
75 end)
76
77 {ref, state} = pop_in(state.client_monitors[client_pid])
78 Process.demonitor(ref)
79
80 timer =
81 if used_by == [] do
82 max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
83 Process.send_after(self(), :idle_close, max_idle)
84 else
85 nil
86 end
87
88 {:reply, :ok, %{state | timer: timer}, :hibernate}
89 end
90
91 @impl true
92 def handle_info(:idle_close, state) do
93 # Gun monitors the owner process, and will close the connection automatically
94 # when it's terminated
95 {:stop, :normal, state}
96 end
97
98 # Gracefully shutdown if the connection got closed without any streams left
99 @impl true
100 def handle_info({:gun_down, _pid, _protocol, _reason, []}, state) do
101 {:stop, :normal, state}
102 end
103
104 # Otherwise, shutdown with an error
105 @impl true
106 def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams} = down_message, state) do
107 {:stop, {:error, down_message}, state}
108 end
109
110 @impl true
111 def handle_info({:DOWN, _ref, :process, pid, reason}, state) do
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, false}, state)
119 end
120
121 # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478
122 defp crf(time_delta, prev_crf) do
123 1 + :math.pow(0.5, 0.0001 * time_delta) * prev_crf
124 end
125 end