logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

worker_supervisor.ex (1465B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do
  5. @moduledoc "Supervisor for pool workers. Does not do anything except enforce max connection limit"
  6. use DynamicSupervisor
  7. def start_link(opts) do
  8. DynamicSupervisor.start_link(__MODULE__, opts, name: __MODULE__)
  9. end
  10. def init(_opts) do
  11. DynamicSupervisor.init(
  12. strategy: :one_for_one,
  13. max_children: Pleroma.Config.get([:connections_pool, :max_connections])
  14. )
  15. end
  16. def start_worker(opts, retry \\ false) do
  17. case DynamicSupervisor.start_child(__MODULE__, {Pleroma.Gun.ConnectionPool.Worker, opts}) do
  18. {:error, :max_children} ->
  19. funs = [fn -> retry end, fn -> match?(:error, free_pool()) end]
  20. if Enum.any?(funs, fn fun -> fun.() end) do
  21. :telemetry.execute([:pleroma, :connection_pool, :provision_failure], %{opts: opts})
  22. {:error, :pool_full}
  23. else
  24. start_worker(opts, true)
  25. end
  26. res ->
  27. res
  28. end
  29. end
  30. defp free_pool do
  31. wait_for_reclaimer_finish(Pleroma.Gun.ConnectionPool.Reclaimer.start_monitor())
  32. end
  33. defp wait_for_reclaimer_finish({pid, mon}) do
  34. receive do
  35. {:DOWN, ^mon, :process, ^pid, :no_unused_conns} ->
  36. :error
  37. {:DOWN, ^mon, :process, ^pid, :normal} ->
  38. :ok
  39. end
  40. end
  41. end