aboutsummaryrefslogtreecommitdiff
path: root/lib/pleroma/gun/connections.ex
blob: e3d392de79b2ea564ea080da1e49c3a79c492c2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# Pleroma: A lightweight social networking server
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Gun.Connections do
  use GenServer
  require Logger

  @type domain :: String.t()
  @type conn :: Pleroma.Gun.Conn.t()

  @type t :: %__MODULE__{
          conns: %{domain() => conn()},
          opts: keyword()
        }

  defstruct conns: %{}, opts: [], queue: []

  alias Pleroma.Gun.API
  alias Pleroma.Gun.Conn

  @spec start_link({atom(), keyword()}) :: {:ok, pid()} | :ignore
  def start_link({name, opts}) do
    GenServer.start_link(__MODULE__, opts, name: name)
  end

  @impl true
  def init(opts), do: {:ok, %__MODULE__{conns: %{}, opts: opts}}

  @spec checkin(String.t(), keyword(), atom()) :: pid()
  def checkin(url, opts \\ [], name \\ :default) do
    opts = Enum.into(opts, %{})

    uri = URI.parse(url)

    opts =
      if uri.scheme == "https" and uri.port != 443,
        do: Map.put(opts, :transport, :tls),
        else: opts

    opts =
      if uri.scheme == "https" do
        host = uri.host |> to_charlist()

        tls_opts =
          Map.get(opts, :tls_opts, [])
          |> Keyword.put(:server_name_indication, host)

        Map.put(opts, :tls_opts, tls_opts)
      else
        opts
      end

    GenServer.call(
      name,
      {:checkin, %{opts: opts, uri: uri}}
    )
  end

  @spec alive?(atom()) :: boolean()
  def alive?(name \\ :default) do
    pid = Process.whereis(name)
    if pid, do: Process.alive?(pid), else: false
  end

  @spec get_state(atom()) :: t()
  def get_state(name \\ :default) do
    GenServer.call(name, {:state})
  end

  def checkout(conn, pid, name \\ :default) do
    GenServer.cast(name, {:checkout, conn, pid})
  end

  def process_queue(name \\ :default) do
    GenServer.cast(name, {:process_queue})
  end

  @impl true
  def handle_cast({:checkout, conn_pid, pid}, state) do
    {key, conn} = find_conn(state.conns, conn_pid)
    used_by = List.keydelete(conn.used_by, pid, 0)
    conn_state = if used_by == [], do: :idle, else: conn.conn_state
    state = put_in(state.conns[key], %{conn | conn_state: conn_state, used_by: used_by})
    {:noreply, state}
  end

  @impl true
  def handle_cast({:process_queue}, state) do
    case state.queue do
      [{from, key, uri, opts} | _queue] ->
        try_to_checkin(key, uri, from, state, Map.put(opts, :from_cast, true))

      [] ->
        {:noreply, state}
    end
  end

  @impl true
  def handle_call({:checkin, %{opts: opts, uri: uri}}, from, state) do
    key = compose_key(uri)

    case state.conns[key] do
      %{conn: conn, gun_state: gun_state} = current_conn when gun_state == :up ->
        time = current_time()
        last_reference = time - current_conn.last_reference

        current_crf = crf(last_reference, 100, current_conn.crf)

        state =
          put_in(state.conns[key], %{
            current_conn
            | last_reference: time,
              crf: current_crf,
              conn_state: :active,
              used_by: [from | current_conn.used_by]
          })

        {:reply, conn, state}

      %{gun_state: gun_state, waiting_pids: pids} when gun_state in [:open, :down] ->
        state = put_in(state.conns[key].waiting_pids, [from | pids])
        {:noreply, state}

      nil ->
        max_connections = state.opts[:max_connections]

        if Enum.count(state.conns) < max_connections do
          open_conn(key, uri, from, state, opts)
        else
          try_to_checkin(key, uri, from, state, opts)
        end
    end
  end

  @impl true
  def handle_call({:state}, _from, state), do: {:reply, state, state}

  defp try_to_checkin(key, uri, from, state, opts) do
    unused_conns =
      state.conns
      |> Enum.filter(fn {_k, v} ->
        v.conn_state == :idle and v.waiting_pids == [] and v.used_by == []
      end)
      |> Enum.sort(fn {_x_k, x}, {_y_k, y} ->
        x.crf < y.crf and x.last_reference < y.last_reference
      end)

    case unused_conns do
      [{close_key, least_used} | _conns] ->
        :ok = API.close(least_used.conn)

        state =
          put_in(
            state.conns,
            Map.delete(state.conns, close_key)
          )

        open_conn(key, uri, from, state, opts)

      [] ->
        queue =
          if List.keymember?(state.queue, from, 0),
            do: state.queue,
            else: state.queue ++ [{from, key, uri, opts}]

        state = put_in(state.queue, queue)
        {:noreply, state}
    end
  end

  @impl true
  def handle_info({:gun_up, conn_pid, _protocol}, state) do
    conn_key = compose_key_gun_info(conn_pid)
    {key, conn} = find_conn(state.conns, conn_pid, conn_key)

    # Update state of the current connection and set waiting_pids to empty list
    time = current_time()
    last_reference = time - conn.last_reference
    current_crf = crf(last_reference, 100, conn.crf)

    state =
      put_in(state.conns[key], %{
        conn
        | gun_state: :up,
          waiting_pids: [],
          last_reference: time,
          crf: current_crf,
          conn_state: :active,
          used_by: conn.waiting_pids ++ conn.used_by
      })

    # Send to all waiting processes connection pid
    Enum.each(conn.waiting_pids, fn waiting_pid -> GenServer.reply(waiting_pid, conn_pid) end)

    {:noreply, state}
  end

  @impl true
  def handle_info({:gun_down, conn_pid, _protocol, _reason, _killed, _unprocessed}, state) do
    # we can't get info on this pid, because pid is dead
    {key, conn} = find_conn(state.conns, conn_pid)

    Enum.each(conn.waiting_pids, fn waiting_pid -> GenServer.reply(waiting_pid, nil) end)

    state = put_in(state.conns[key].gun_state, :down)
    {:noreply, state}
  end

  defp compose_key(uri), do: "#{uri.scheme}:#{uri.host}:#{uri.port}"

  defp compose_key_gun_info(pid) do
    info = API.info(pid)
    "#{info.origin_scheme}:#{info.origin_host}:#{info.origin_port}"
  end

  defp find_conn(conns, conn_pid) do
    Enum.find(conns, fn {_key, conn} ->
      conn.conn == conn_pid
    end)
  end

  defp find_conn(conns, conn_pid, conn_key) do
    Enum.find(conns, fn {key, conn} ->
      key == conn_key and conn.conn == conn_pid
    end)
  end

  defp open_conn(key, uri, from, state, %{proxy: {proxy_host, proxy_port}} = opts) do
    host = to_charlist(uri.host)
    port = uri.port

    tls_opts = Map.get(opts, :tls_opts, [])
    connect_opts = %{host: host, port: port}

    connect_opts =
      if uri.scheme == "https" do
        Map.put(connect_opts, :protocols, [:http2])
        |> Map.put(:transport, :tls)
        |> Map.put(:tls_opts, tls_opts)
      else
        connect_opts
      end

    with open_opts <- Map.delete(opts, :tls_opts),
         {:ok, conn} <- API.open(proxy_host, proxy_port, open_opts),
         {:ok, _} <- API.await_up(conn),
         stream <- API.connect(conn, connect_opts),
         {:response, :fin, 200, _} <- API.await(conn, stream) do
      state =
        put_in(state.conns[key], %Conn{
          conn: conn,
          waiting_pids: [],
          gun_state: :up,
          conn_state: :active,
          used_by: [from]
        })

      if opts[:from_cast] do
        GenServer.reply(from, conn)
      end

      {:reply, conn, state}
    else
      error ->
        Logger.warn(inspect(error))
        {:reply, nil, state}
    end
  end

  defp open_conn(key, uri, from, state, opts) do
    host = to_charlist(uri.host)
    port = uri.port

    with {:ok, conn} <- API.open(host, port, opts) do
      state =
        if opts[:from_cast] do
          put_in(state.queue, List.keydelete(state.queue, from, 0))
        else
          state
        end

      state =
        put_in(state.conns[key], %Conn{
          conn: conn,
          waiting_pids: [from]
        })

      {:noreply, state}
    else
      error ->
        Logger.warn(inspect(error))
        {:reply, nil, state}
    end
  end

  defp current_time do
    :os.system_time(:second)
  end

  def crf(current, steps, crf) do
    1 + :math.pow(0.5, current / steps) * crf
  end
end