2020-10-12 19:00:50 +02:00
|
|
|
# Pleroma: A lightweight social networking server
|
2021-01-13 07:49:20 +01:00
|
|
|
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
2020-10-12 19:00:50 +02:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-06-24 07:39:56 +02:00
|
|
|
defmodule Pleroma.Web.Plugs.RateLimiter.LimiterSupervisor do
|
2019-11-11 13:13:06 +01:00
|
|
|
use DynamicSupervisor
|
|
|
|
|
|
|
|
import Cachex.Spec
|
|
|
|
|
|
|
|
def start_link(init_arg) do
|
|
|
|
DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
|
|
|
|
end
|
|
|
|
|
2020-02-28 15:35:01 +01:00
|
|
|
def add_or_return_limiter(limiter_name, expiration) do
|
|
|
|
result =
|
2019-11-11 13:13:06 +01:00
|
|
|
DynamicSupervisor.start_child(
|
|
|
|
__MODULE__,
|
|
|
|
%{
|
|
|
|
id: String.to_atom("rl_#{limiter_name}"),
|
|
|
|
start:
|
|
|
|
{Cachex, :start_link,
|
|
|
|
[
|
|
|
|
limiter_name,
|
|
|
|
[
|
|
|
|
expiration:
|
|
|
|
expiration(
|
|
|
|
default: expiration,
|
|
|
|
interval: check_interval(expiration),
|
|
|
|
lazy: true
|
|
|
|
)
|
|
|
|
]
|
|
|
|
]}
|
|
|
|
}
|
|
|
|
)
|
2020-02-28 15:35:01 +01:00
|
|
|
|
|
|
|
case result do
|
|
|
|
{:ok, _pid} = result -> result
|
|
|
|
{:error, {:already_started, pid}} -> {:ok, pid}
|
|
|
|
_ -> result
|
|
|
|
end
|
2019-11-11 13:13:06 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def init(_init_arg) do
|
|
|
|
DynamicSupervisor.init(strategy: :one_for_one)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp check_interval(exp) do
|
|
|
|
(exp / 2)
|
|
|
|
|> Kernel.trunc()
|
|
|
|
|> Kernel.min(5000)
|
|
|
|
|> Kernel.max(1)
|
|
|
|
end
|
|
|
|
end
|