···7788## [Unreleased]
991010+### Added
1111+1212+- Added the `per_second_fn` and `burst_limit_fn` functions to dynamically set limits based on the identifier.
1313+1014### Changed
11151216- Removed the need for `glimit.build()` and `glimit.try_build()` functions. Now, the `glimit.apply()` function can be used directly with the limiter configuration.
+22-4
src/glimit.gleam
···5555///
5656pub type RateLimiterBuilder(a, b, id) {
5757 RateLimiterBuilder(
5858- per_second: Option(Int),
5959- burst_limit: Option(Int),
5858+ per_second: Option(fn(id) -> Int),
5959+ burst_limit: Option(fn(id) -> Int),
6060 identifier: Option(fn(a) -> id),
6161 on_limit_exceeded: Option(fn(a) -> b),
6262 )
···8383 limiter: RateLimiterBuilder(a, b, id),
8484 limit: Int,
8585) -> RateLimiterBuilder(a, b, id) {
8686- RateLimiterBuilder(..limiter, per_second: Some(limit))
8686+ RateLimiterBuilder(..limiter, per_second: Some(fn(_) { limit }))
8787+}
8888+8989+/// Set the rate limit per second, based on the identifier.
9090+///
9191+pub fn per_second_fn(
9292+ limiter: RateLimiterBuilder(a, b, id),
9393+ limit_fn: fn(id) -> Int,
9494+) -> RateLimiterBuilder(a, b, id) {
9595+ RateLimiterBuilder(..limiter, per_second: Some(limit_fn))
8796}
88978998/// Set the maximum number of available tokens.
···95104 limiter: RateLimiterBuilder(a, b, id),
96105 burst_limit: Int,
97106) -> RateLimiterBuilder(a, b, id) {
9898- RateLimiterBuilder(..limiter, burst_limit: Some(burst_limit))
107107+ RateLimiterBuilder(..limiter, burst_limit: Some(fn(_) { burst_limit }))
108108+}
109109+110110+/// Set the maximum number of available tokens, based on the identifier.
111111+///
112112+pub fn burst_limit_fn(
113113+ limiter: RateLimiterBuilder(a, b, id),
114114+ burst_limit_fn: fn(id) -> Int,
115115+) -> RateLimiterBuilder(a, b, id) {
116116+ RateLimiterBuilder(..limiter, burst_limit: Some(burst_limit_fn))
99117}
100118101119/// Set the handler to be called when the rate limit is reached.
+6-6
src/glimit/registry.gleam
···1919 State(
2020 /// The maximum number of tokens.
2121 ///
2222- max_token_count: Int,
2222+ max_token_count: fn(id) -> Int,
2323 /// The rate of token generation per second.
2424 ///
2525- token_rate: Int,
2525+ token_rate: fn(id) -> Int,
2626 /// The registry of rate limiters.
2727 ///
2828 registry: Dict(id, Subject(rate_limiter.Message)),
···5454 }
5555 Error(_) -> {
5656 use rate_limiter <- result.try(rate_limiter.new(
5757- state.max_token_count,
5858- state.token_rate,
5757+ state.max_token_count(identifier),
5858+ state.token_rate(identifier),
5959 ))
6060 Ok(rate_limiter)
6161 }
···103103/// Create a new rate limiter registry.
104104///
105105pub fn new(
106106- per_second: Int,
107107- burst_limit: Int,
106106+ per_second: fn(id) -> Int,
107107+ burst_limit: fn(id) -> Int,
108108) -> Result(RateLimiterRegistryActor(id), Nil) {
109109 let state =
110110 State(