2020-10-12 17:00:50 +00:00
|
|
|
# Pleroma: A lightweight social networking server
|
2023-01-02 20:38:50 +00:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2020-10-12 17:00:50 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-05-06 20:14:24 +00:00
|
|
|
defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do
|
2020-07-15 12:24:47 +00:00
|
|
|
@moduledoc "Supervisor for pool workers. Does not do anything except enforce max connection limit"
|
2020-05-06 20:14:24 +00:00
|
|
|
|
|
|
|
use DynamicSupervisor
|
|
|
|
|
|
|
|
def start_link(opts) do
|
|
|
|
DynamicSupervisor.start_link(__MODULE__, opts, name: __MODULE__)
|
|
|
|
end
|
|
|
|
|
|
|
|
def init(_opts) do
|
|
|
|
DynamicSupervisor.init(
|
|
|
|
strategy: :one_for_one,
|
|
|
|
max_children: Pleroma.Config.get([:connections_pool, :max_connections])
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2024-02-23 16:12:10 +00:00
|
|
|
def start_worker(opts, last_attempt \\ false) do
|
2020-05-06 20:14:24 +00:00
|
|
|
case DynamicSupervisor.start_child(__MODULE__, {Pleroma.Gun.ConnectionPool.Worker, opts}) do
|
|
|
|
{:error, :max_children} ->
|
2024-02-23 16:12:10 +00:00
|
|
|
funs = [fn -> last_attempt end, fn -> match?(:error, free_pool()) end]
|
2024-02-09 15:36:58 +00:00
|
|
|
|
|
|
|
if Enum.any?(funs, fn fun -> fun.() end) do
|
2020-05-07 13:11:48 +00:00
|
|
|
:telemetry.execute([:pleroma, :connection_pool, :provision_failure], %{opts: opts})
|
|
|
|
{:error, :pool_full}
|
|
|
|
else
|
|
|
|
start_worker(opts, true)
|
2020-05-06 20:14:24 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
res ->
|
|
|
|
res
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp free_pool do
|
2020-07-08 11:22:42 +00:00
|
|
|
wait_for_reclaimer_finish(Pleroma.Gun.ConnectionPool.Reclaimer.start_monitor())
|
2020-05-06 20:14:24 +00:00
|
|
|
end
|
|
|
|
|
2020-07-08 11:22:42 +00:00
|
|
|
defp wait_for_reclaimer_finish({pid, mon}) do
|
2020-05-06 20:14:24 +00:00
|
|
|
receive do
|
2020-07-08 11:22:42 +00:00
|
|
|
{:DOWN, ^mon, :process, ^pid, :no_unused_conns} ->
|
2020-05-06 20:14:24 +00:00
|
|
|
:error
|
|
|
|
|
2020-07-08 11:22:42 +00:00
|
|
|
{:DOWN, ^mon, :process, ^pid, :normal} ->
|
2020-05-06 20:14:24 +00:00
|
|
|
:ok
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|