/// Several throttles under one effect, each named for what it limits /// (`login`, `subscribe`, `api`), each with its own rate. A shared /// throttle keys its rows `:`, so they can share one table. A /// name with no throttle admits everything. import log.{type log} import resilience/rate_limit.{type Admission, Admitted} import std/list import std/process.{type proc} import std/time.{type clock} import throttle.{type Throttle} @test import resilience/rate_limit.{Wait} @test import std/test.{assert_equal} pub effect named { /// Whether one more request under `key` is within bucket `name`'s rate. fn admitted :: name: String key: String -> Admission } pub fn with_named :: named: List<(String, Throttle)> action: fn() -> a / -> a / { handle { action () } with { admitted name key -> match list.find named fn pair { pair.0 == name } { Some((_, t)) -> throttle.with_throttle t fn { throttle.admission "{name}:{key}" } , None -> Admitted } } } @test fn each_name_has_its_own_bucket_and_an_unknown_name_admits :: -> () / { let named = [("login", throttle.start 1), ("api", throttle.start 2)] let tries = fn name key { time.with_fixed_clock (time.from_unix_ms 0) fn { log.silently fn { with_named named fn { admitted name key } } } } assert_equal (tries "login" "a") Admitted assert_equal (tries "login" "a") Wait(60) // the same key under another name draws on another bucket assert_equal (tries "api" "a") Admitted assert_equal (tries "unknown" "a") Admitted }