packages
The Louise packages, each released on its own
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#31 · main · 4 min 11 s
0Étoiles
0Forks
3Issues
| 1 | /// Several throttles under one effect, each named for what it limits |
| 2 | /// (`login`, `subscribe`, `api`), each with its own rate. A shared |
| 3 | /// throttle keys its rows `<name>:<key>`, so they can share one table. A |
| 4 | /// name with no throttle admits everything. |
| 5 | |
| 6 | import log.{type log} |
| 7 | import resilience/rate_limit.{type Admission, Admitted} |
| 8 | import std/list |
| 9 | import std/process.{type proc} |
| 10 | import std/time.{type clock} |
| 11 | import throttle.{type Throttle} |
| 12 | @test import resilience/rate_limit.{Wait} |
| 13 | @test import std/test.{assert_equal} |
| 14 | |
| 15 | pub effect named |
| 16 | { |
| 17 | /// Whether one more request under `key` is within bucket `name`'s rate. |
| 18 | fn admitted :: name: String key: String -> Admission |
| 19 | } |
| 20 | |
| 21 | pub fn with_named :: |
| 22 | named: List<(String, Throttle)> |
| 23 | action: fn() -> a / <named, proc, clock, log | e> |
| 24 | -> a / <proc, clock, log | e> |
| 25 | { |
| 26 | handle |
| 27 | { |
| 28 | action () |
| 29 | } |
| 30 | with |
| 31 | { admitted name |
| 32 | key -> match list.find named fn pair { pair.0 == name } |
| 33 | { Some((_, t)) -> |
| 34 | throttle.with_throttle t fn { throttle.admission "{name}:{key}" } |
| 35 | , None -> Admitted |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | @test |
| 41 | fn each_name_has_its_own_bucket_and_an_unknown_name_admits :: -> () / <proc> |
| 42 | { |
| 43 | let named = [("login", throttle.start 1), ("api", throttle.start 2)] |
| 44 | let tries = fn name key |
| 45 | { |
| 46 | time.with_fixed_clock |
| 47 | (time.from_unix_ms 0) |
| 48 | fn { log.silently fn { with_named named fn { admitted name key } } } |
| 49 | } |
| 50 | assert_equal (tries "login" "a") Admitted |
| 51 | assert_equal (tries "login" "a") Wait(60) |
| 52 | // the same key under another name draws on another bucket |
| 53 | assert_equal (tries "api" "a") Admitted |
| 54 | assert_equal (tries "unknown" "a") Admitted |
| 55 | } |