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