From 5bc10fff60e28514419b489102768db18db6afc1 Mon Sep 17 00:00:00 2001 From: Jordan Bracco Date: Sat, 16 May 2020 12:39:22 +0200 Subject: [PATCH] Fix tests & add ConcurrentLimiter.delete/1 --- lib/concurrent_limiter.ex | 15 +++++++++++++-- test/concurrent_limiter_test.exs | 18 +++++++++--------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/lib/concurrent_limiter.ex b/lib/concurrent_limiter.ex index 9555f00..a581447 100644 --- a/lib/concurrent_limiter.ex +++ b/lib/concurrent_limiter.ex @@ -73,9 +73,20 @@ defmodule ConcurrentLimiter do end end + @spec delete(name) :: :ok when name: atom() + @doc "Deletes a limiter." + def delete(name) do + if defined?(name) do + :persistent_term.put(name, nil) + end + + :ok + end + @doc "Limits invocation of `fun`." - @spec limit(atom(), function(), opts) :: {:error, :overload} | any() - when opts: [option], + @spec limit(name, function(), opts) :: {:error, :overload} | any() + when name: atom(), + opts: [option], option: {:wait, non_neg_integer()} | {:max_retries, non_neg_integer()} def limit(name, fun, opts \\ []) do do_limit(prefix_name(name), fun, opts, 0) diff --git a/test/concurrent_limiter_test.exs b/test/concurrent_limiter_test.exs index 090417e..83e9981 100644 --- a/test/concurrent_limiter_test.exs +++ b/test/concurrent_limiter_test.exs @@ -11,11 +11,11 @@ defmodule ConcurrentLimiterTest do ConcurrentLimiter.new(name, 2, 2) self = self() - spawn_link(fn -> sleepy(name, 500) end) - spawn_link(fn -> sleepy(name, 500) end) - spawn_link(fn -> sleepy(name, 500) end) - spawn_link(fn -> sleepy(name, 500) end) - spawn_link(fn -> sleepy(name, 500) end) + spawn_link(fn -> sleepy(self, name, 500) end) + spawn_link(fn -> sleepy(self, name, 500) end) + spawn_link(fn -> sleepy(self, name, 500) end) + spawn_link(fn -> sleepy(self, name, 500) end) + spawn_link(fn -> sleepy(self, name, 500) end) assert_receive :ok, 2000 assert_receive :ok, 2000 assert_receive {:error, :overload}, 2000 @@ -23,17 +23,17 @@ defmodule ConcurrentLimiterTest do assert_receive :ok, 2000 end - defp sleepy(duration) do + defp sleepy(parent, name, duration) do result = ConcurrentLimiter.limit(name, fn -> - send(self, :ok) - Process.sleep(sleep) + send(parent, :ok) + Process.sleep(duration) :ok end) case result do :ok -> :ok - other -> send(self, other) + other -> send(parent, other) end end end