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