HTTP: radically simplify pool checkin/checkout
[akkoma] / lib / pleroma / tesla / middleware / connection_pool.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Tesla.Middleware.ConnectionPool do
6 @moduledoc """
7 Middleware to get/release connections from `Pleroma.Gun.ConnectionPool`
8 """
9
10 @behaviour Tesla.Middleware
11
12 alias Pleroma.Gun.ConnectionPool
13
14 @impl Tesla.Middleware
15 def call(%Tesla.Env{url: url, opts: opts} = env, next, _) do
16 uri = URI.parse(url)
17
18 case ConnectionPool.get_conn(uri, opts[:adapter]) do
19 {:ok, conn_pid} ->
20 adapter_opts = Keyword.merge(opts[:adapter], conn: conn_pid, close_conn: false)
21 opts = Keyword.put(opts, :adapter, adapter_opts)
22 env = %{env | opts: opts}
23 res = Tesla.run(env, next)
24
25 unless opts[:adapter][:body_as] == :chunks do
26 ConnectionPool.release_conn(conn_pid)
27 end
28
29 res
30
31 err ->
32 err
33 end
34 end
35 end