2020-09-03 14:15:22 -06:00
|
|
|
# Pleroma: A lightweight social networking server
|
2022-02-25 23:11:42 -07:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2020-09-03 14:15:22 -06:00
|
|
|
# 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)
|
|
|
|
|
2020-09-04 13:10:40 -06:00
|
|
|
# Avoid leaking connections when the middleware is called twice
|
|
|
|
# with body_as: :chunks. We assume only the middleware can set
|
|
|
|
# opts[:adapter][:conn]
|
|
|
|
if opts[:adapter][:conn] do
|
|
|
|
ConnectionPool.release_conn(opts[:adapter][:conn])
|
|
|
|
end
|
|
|
|
|
2020-09-03 14:15:22 -06:00
|
|
|
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}
|
|
|
|
|
2020-09-04 13:10:40 -06:00
|
|
|
case Tesla.run(env, next) do
|
|
|
|
{:ok, env} ->
|
|
|
|
unless opts[:adapter][:body_as] == :chunks do
|
|
|
|
ConnectionPool.release_conn(conn_pid)
|
2020-09-05 12:27:06 -06:00
|
|
|
{_, res} = pop_in(env.opts[:adapter][:conn])
|
|
|
|
{:ok, res}
|
2020-09-04 13:10:40 -06:00
|
|
|
else
|
|
|
|
{:ok, env}
|
|
|
|
end
|
|
|
|
|
|
|
|
err ->
|
|
|
|
ConnectionPool.release_conn(conn_pid)
|
|
|
|
err
|
2020-09-03 14:15:22 -06:00
|
|
|
end
|
2020-09-05 12:36:17 -06:00
|
|
|
|
|
|
|
err ->
|
|
|
|
err
|
2020-09-03 14:15:22 -06:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|