1 defmodule Pleroma.Gun.ConnectionPool do
4 alias Pleroma.Gun.ConnectionPool.WorkerSupervisor
8 {Registry, keys: :unique, name: @registry},
9 Pleroma.Gun.ConnectionPool.WorkerSupervisor
13 def get_conn(uri, opts) do
14 key = "#{uri.scheme}:#{uri.host}:#{uri.port}"
16 case Registry.lookup(@registry, key) do
17 # The key has already been registered, but connection is not up yet
18 [{worker_pid, nil}] ->
19 get_gun_pid_from_worker(worker_pid, true)
21 [{worker_pid, {gun_pid, _used_by, _crf, _last_reference}}] ->
22 GenServer.call(worker_pid, :add_client)
26 # :gun.set_owner fails in :connected state for whatevever reason,
27 # so we open the connection in the process directly and send it's pid back
28 # We trust gun to handle timeouts by itself
29 case WorkerSupervisor.start_worker([key, uri, opts, self()]) do
31 get_gun_pid_from_worker(worker_pid, false)
33 {:error, {:already_started, worker_pid}} ->
34 get_gun_pid_from_worker(worker_pid, true)
42 defp get_gun_pid_from_worker(worker_pid, register) do
43 # GenServer.call will block the process for timeout length if
44 # the server crashes on startup (which will happen if gun fails to connect)
45 # so instead we use cast + monitor
47 ref = Process.monitor(worker_pid)
48 if register, do: GenServer.cast(worker_pid, {:add_client, self()})
52 Process.demonitor(ref)
55 {:DOWN, ^ref, :process, ^worker_pid, reason} ->
57 {:shutdown, error} -> error
63 def release_conn(conn_pid) do
64 # :ets.fun2ms(fn {_, {worker_pid, {gun_pid, _, _, _}}} when gun_pid == conn_pid ->
67 Registry.select(@registry, [
68 {{:_, :"$1", {:"$2", :_, :_, :_}}, [{:==, :"$2", conn_pid}], [:"$1"]}
73 GenServer.call(worker_pid, :remove_client)