1 defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do
2 @moduledoc "Supervisor for pool workers. Does not do anything except enforce max connection limit"
6 def start_link(opts) do
7 DynamicSupervisor.start_link(__MODULE__, opts, name: __MODULE__)
11 DynamicSupervisor.init(
12 strategy: :one_for_one,
13 max_children: Pleroma.Config.get([:connections_pool, :max_connections])
17 def start_worker(opts) do
18 case DynamicSupervisor.start_child(__MODULE__, {Pleroma.Gun.ConnectionPool.Worker, opts}) do
19 {:error, :max_children} ->
25 :telemetry.execute([:pleroma, :connection_pool, :provision_failure], %{opts: opts})
34 @registry Pleroma.Gun.ConnectionPool
35 @enforcer_key "enforcer"
37 case Registry.lookup(@registry, @enforcer_key) do
41 {:ok, _pid} = Registry.register(@registry, @enforcer_key, nil)
42 max_connections = Pleroma.Config.get([:connections_pool, :max_connections])
45 [:connections_pool, :reclaim_multiplier]
46 |> Pleroma.Config.get()
47 |> Kernel.*(max_connections)
51 :telemetry.execute([:pleroma, :connection_pool, :reclaim, :start], %{}, %{
52 max_connections: max_connections,
53 reclaim_max: reclaim_max
57 # fn {_, {worker_pid, {_, used_by, crf, last_reference}}} when used_by == [] ->
58 # {worker_pid, crf, last_reference} end)
63 {{:_, :"$1", {:_, :"$2", :"$3", :"$4"}}, [{:==, :"$2", []}],
64 [{{:"$1", :"$3", :"$4"}}]}
71 [:pleroma, :connection_pool, :reclaim, :stop],
72 %{reclaimed_count: 0},
74 max_connections: max_connections
78 exit(:no_unused_conns)
83 |> Enum.sort(fn {_pid1, crf1, last_reference1},
84 {_pid2, crf2, last_reference2} ->
85 crf1 <= crf2 and last_reference1 <= last_reference2
87 |> Enum.take(reclaim_max)
90 |> Enum.each(fn {pid, _, _} ->
91 DynamicSupervisor.terminate_child(__MODULE__, pid)
95 [:pleroma, :connection_pool, :reclaim, :stop],
96 %{reclaimed_count: Enum.count(reclaimed)},
97 %{max_connections: max_connections}
102 wait_for_enforcer_finish(pid)
105 wait_for_enforcer_finish(pid)
109 defp wait_for_enforcer_finish(pid) do
110 ref = Process.monitor(pid)
113 {:DOWN, ^ref, :process, ^pid, :no_unused_conns} ->
116 {:DOWN, ^ref, :process, ^pid, :normal} ->