logo

pleroma

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

limiter_supervisor.ex (1305B)


  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.Web.Plugs.RateLimiter.LimiterSupervisor do
  5. use DynamicSupervisor
  6. import Cachex.Spec
  7. def start_link(init_arg) do
  8. DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
  9. end
  10. def add_or_return_limiter(limiter_name, expiration) do
  11. result =
  12. DynamicSupervisor.start_child(
  13. __MODULE__,
  14. %{
  15. id: String.to_atom("rl_#{limiter_name}"),
  16. start:
  17. {Cachex, :start_link,
  18. [
  19. limiter_name,
  20. [
  21. expiration:
  22. expiration(
  23. default: expiration,
  24. interval: check_interval(expiration),
  25. lazy: true
  26. )
  27. ]
  28. ]}
  29. }
  30. )
  31. case result do
  32. {:ok, _pid} = result -> result
  33. {:error, {:already_started, pid}} -> {:ok, pid}
  34. _ -> result
  35. end
  36. end
  37. @impl true
  38. def init(_init_arg) do
  39. DynamicSupervisor.init(strategy: :one_for_one)
  40. end
  41. defp check_interval(exp) do
  42. (exp / 2)
  43. |> Kernel.trunc()
  44. |> Kernel.min(5000)
  45. |> Kernel.max(1)
  46. end
  47. end