ratelimiter

master
cynic 3 years ago
parent 79c5ed7d8e
commit de70439f3e
  1. 16
      lib/tir_inna_noc/imageboard.ex
  2. 23
      lib/tir_inna_noc/rate.ex
  3. 1
      lib/tir_inna_noc/sup.ex

@ -5,16 +5,24 @@ defmodule TirInnaNoc.Imageboard do
#plug Tesla.Middleware.Headers, [{"authorization", "token xyz"}] #plug Tesla.Middleware.Headers, [{"authorization", "token xyz"}]
plug Tesla.Middleware.JSON plug Tesla.Middleware.JSON
def wget(uri) do
if GenServer.call(:ratelimiter, :activate) == :goahead do
get(uri)
else
Process.sleep(1000)
wget(uri)
end
end
def boards() do def boards() do
get("/boards.json") wget("/boards.json")
end end
def threads(board) do def threads(board) do
get("/"<>board<>"/threads.json") wget("/"<>board<>"/threads.json")
end end
def thread(board, id) do def thread(board, id) do
get("/"<>board<>"/thread/"<>to_string(id)<>".json") wget("/"<>board<>"/thread/"<>to_string(id)<>".json")
end end
def catalog(board) do def catalog(board) do
get("/"<>board<>"/catalog.json") wget("/"<>board<>"/catalog.json")
end end
end end

@ -0,0 +1,23 @@
defmodule TirInnaNoc.Rate do
use GenServer
def start_link(last_activity) do
GenServer.start_link(__MODULE__, last_activity, name: :ratelimiter)
end
@impl true
def init(last_activity) do
last_activity = :os.system_time(:millisecond)
{:ok, last_activity}
end
@impl true
def handle_call(:activate, _, last_activity) do
if :os.system_time(:millisecond) - last_activity > 10_000 do
last_activity = :os.system_time(:millisecond)
{:reply, :goahead, last_activity}
else
{:reply, :defer, last_activity}
end
end
end

@ -9,6 +9,7 @@ defmodule TirInnaNoc.Sup do
def init(:ok) do def init(:ok) do
children = [ children = [
{TirInnaNoc.Db, [nil]}, {TirInnaNoc.Db, [nil]},
{TirInnaNoc.Rate, [nil]},
{DynamicSupervisor, strategy: :one_for_one, name: MerlinSupervisor}, {DynamicSupervisor, strategy: :one_for_one, name: MerlinSupervisor},
{TirInnaNoc.Merlin, [nil]} {TirInnaNoc.Merlin, [nil]}
] ]

Loading…
Cancel
Save