Merge branch 'release/2.1.2' into 'stable'
[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}, state) do
40 case handle_call(:add_client, {client_pid, nil}, state) do
41 {:reply, conn_pid, state, :hibernate} ->
42 send(client_pid, {:conn_pid, conn_pid})
43 {:noreply, state, :hibernate}
44 end
45 end
46
47 @impl true
48 def handle_cast({:remove_client, client_pid}, state) do
49 case handle_call(:remove_client, {client_pid, nil}, state) do
50 {:reply, _, state, :hibernate} ->
51 {:noreply, state, :hibernate}
52 end
53 end
54
55 @impl true
56 def handle_call(:add_client, {client_pid, _}, %{key: key} = state) do
57 time = :erlang.monotonic_time(:millisecond)
58
59 {{conn_pid, _, _, _}, _} =
60 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
61 {conn_pid, [client_pid | used_by], crf(time - last_reference, crf), time}
62 end)
63
64 state =
65 if state.timer != nil do
66 Process.cancel_timer(state[:timer])
67 %{state | timer: nil}
68 else
69 state
70 end
71
72 ref = Process.monitor(client_pid)
73
74 state = put_in(state.client_monitors[client_pid], ref)
75 {:reply, conn_pid, state, :hibernate}
76 end
77
78 @impl true
79 def handle_call(:remove_client, {client_pid, _}, %{key: key} = state) do
80 {{_conn_pid, used_by, _crf, _last_reference}, _} =
81 Registry.update_value(@registry, key, fn {conn_pid, used_by, crf, last_reference} ->
82 {conn_pid, List.delete(used_by, client_pid), crf, last_reference}
83 end)
84
85 {ref, state} = pop_in(state.client_monitors[client_pid])
86 # DOWN message can receive right after `remove_client` call and cause worker to terminate
87 state =
88 if is_nil(ref) do
89 state
90 else
91 Process.demonitor(ref)
92
93 timer =
94 if used_by == [] do
95 max_idle = Pleroma.Config.get([:connections_pool, :max_idle_time], 30_000)
96 Process.send_after(self(), :idle_close, max_idle)
97 else
98 nil
99 end
100
101 %{state | timer: timer}
102 end
103
104 {:reply, :ok, state, :hibernate}
105 end
106
107 @impl true
108 def handle_info(:idle_close, state) do
109 # Gun monitors the owner process, and will close the connection automatically
110 # when it's terminated
111 {:stop, :normal, state}
112 end
113
114 @impl true
115 def handle_info({:gun_up, _pid, _protocol}, state) do
116 {:noreply, state, :hibernate}
117 end
118
119 # Gracefully shutdown if the connection got closed without any streams left
120 @impl true
121 def handle_info({:gun_down, _pid, _protocol, _reason, []}, state) do
122 {:stop, :normal, state}
123 end
124
125 # Otherwise, wait for retry
126 @impl true
127 def handle_info({:gun_down, _pid, _protocol, _reason, _killed_streams}, state) do
128 {:noreply, state, :hibernate}
129 end
130
131 @impl true
132 def handle_info({:DOWN, _ref, :process, pid, reason}, state) do
133 :telemetry.execute(
134 [:pleroma, :connection_pool, :client_death],
135 %{client_pid: pid, reason: reason},
136 %{key: state.key}
137 )
138
139 handle_cast({:remove_client, pid}, state)
140 end
141
142 # LRFU policy: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.1478
143 defp crf(time_delta, prev_crf) do
144 1 + :math.pow(0.5, 0.0001 * time_delta) * prev_crf
145 end
146 end