2020-09-03 20:15:22 +00:00
|
|
|
# Pleroma: A lightweight social networking server
|
2021-01-13 06:49:20 +00:00
|
|
|
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
2020-09-03 20:15:22 +00: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 19:10:40 +00: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 20:15:22 +00: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 19:10:40 +00:00
|
|
|
case Tesla.run(env, next) do
|
|
|
|
{:ok, env} ->
|
|
|
|
unless opts[:adapter][:body_as] == :chunks do
|
|
|
|
ConnectionPool.release_conn(conn_pid)
|
2020-09-05 18:27:06 +00:00
|
|
|
{_, res} = pop_in(env.opts[:adapter][:conn])
|
|
|
|
{:ok, res}
|
2020-09-04 19:10:40 +00:00
|
|
|
else
|
|
|
|
{:ok, env}
|
|
|
|
end
|
|
|
|
|
|
|
|
err ->
|
|
|
|
ConnectionPool.release_conn(conn_pid)
|
|
|
|
err
|
2020-09-03 20:15:22 +00:00
|
|
|
end
|
2020-09-05 18:36:17 +00:00
|
|
|
|
|
|
|
err ->
|
|
|
|
err
|
2020-09-03 20:15:22 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|