some refactoring

This commit is contained in:
Alex S 2019-08-23 20:11:02 +03:00
parent 487e05a9c9
commit 26a98737a8

View File

@ -17,6 +17,7 @@ defmodule Pleroma.Gun.Connections do
defstruct conns: %{}, opts: [] defstruct conns: %{}, opts: []
alias Pleroma.Gun.API alias Pleroma.Gun.API
alias Pleroma.Gun.Conn
@spec start_link({atom(), keyword()}) :: {:ok, pid()} | :ignore @spec start_link({atom(), keyword()}) :: {:ok, pid()} | :ignore
def start_link({name, opts}) do def start_link({name, opts}) do
@ -154,12 +155,10 @@ defmodule Pleroma.Gun.Connections do
end) end)
end end
defp open_conn(key, uri, from, state, opts) do defp open_conn(key, uri, _from, state, %{proxy: {proxy_host, proxy_port}} = opts) do
host = to_charlist(uri.host) host = to_charlist(uri.host)
port = uri.port port = uri.port
result =
if opts[:proxy] do
tls_opts = Map.get(opts, :tls_opts, []) tls_opts = Map.get(opts, :tls_opts, [])
connect_opts = %{host: host, port: port} connect_opts = %{host: host, port: port}
@ -172,53 +171,42 @@ defmodule Pleroma.Gun.Connections do
connect_opts connect_opts
end end
with {proxy_host, proxy_port} <- opts[:proxy], with open_opts <- Map.delete(opts, :tls_opts),
open_opts <- Map.delete(opts, :tls_opts),
{:ok, conn} <- API.open(proxy_host, proxy_port, open_opts), {:ok, conn} <- API.open(proxy_host, proxy_port, open_opts),
{:ok, _} <- API.await_up(conn), {:ok, _} <- API.await_up(conn),
stream <- API.connect(conn, connect_opts), stream <- API.connect(conn, connect_opts),
{:response, :fin, 200, _} <- API.await(conn, stream) do {:response, :fin, 200, _} <- API.await(conn, stream) do
{:ok, conn, true}
else
{:error, error} ->
{:error, error}
error ->
Logger.warn(inspect(error))
{:error, :error_connection_to_proxy}
end
else
with {:ok, conn} <- API.open(host, port, opts) do
{:ok, conn, false}
else
{:error, error} ->
{:error, error}
error ->
Logger.warn(inspect(error))
{:error, :error_connection}
end
end
case result do
{:ok, conn, is_up} ->
{from_list, used, conn_state} = if is_up, do: {[], 1, :up}, else: {[from], 0, :open}
state = state =
put_in(state.conns[key], %Pleroma.Gun.Conn{ put_in(state.conns[key], %Conn{
conn: conn, conn: conn,
waiting_pids: from_list, waiting_pids: [],
used: used, used: 1,
state: conn_state state: :up
}) })
if is_up do
{:reply, conn, state} {:reply, conn, state}
else else
{:noreply, state} error ->
Logger.warn(inspect(error))
{:reply, nil, state}
end
end end
{:error, _error} -> 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 =
put_in(state.conns[key], %Conn{
conn: conn,
waiting_pids: [from]
})
{:noreply, state}
else
error ->
Logger.warn(inspect(error))
{:reply, nil, state} {:reply, nil, state}
end end
end end