summaryrefslogtreecommitdiff
path: root/lib/pleroma/tesla/middleware/connection_pool.ex
blob: a435ab4cc5232ab39646fa73687eb7e862a29a35 (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
# Pleroma: A lightweight social networking server
# Copyright © 2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Tesla.Middleware.ConnectionPool do
  @moduledoc """
  Middleware to get/release connections from `Pleroma.Gun.ConnectionPool`
  """

  @behaviour Tesla.Middleware

  alias Pleroma.Gun.ConnectionPool

  @impl Tesla.Middleware
  def call(%Tesla.Env{url: url, opts: opts} = env, next, _) do
    uri = URI.parse(url)

    case ConnectionPool.get_conn(uri, opts[:adapter]) do
      {:ok, conn_pid} ->
        adapter_opts = Keyword.merge(opts[:adapter], conn: conn_pid, close_conn: false)
        opts = Keyword.put(opts, :adapter, adapter_opts)
        env = %{env | opts: opts}
        res = Tesla.run(env, next)

        unless opts[:adapter][:body_as] == :chunks do
          ConnectionPool.release_conn(conn_pid)
        end

        res

      err ->
        err
    end
  end
end