glimit

A framework-agnostic rate limiter.

Types

The messages that the actor can receive.

pub type Message(a) {
  Shutdown
  Hit(input: a, reply_with: Subject(Result(Nil, Nil)))
}

Constructors

  • Shutdown

    Stop the actor.

  • Hit(input: a, reply_with: Subject(Result(Nil, Nil)))

    Mark a hit for a given identifier.

The rate limiter’s public interface.

pub type RateLimiter(a, b) {
  RateLimiter(subject: Subject(Message(a)), handler: fn(a) -> b)
}

Constructors

  • RateLimiter(subject: Subject(Message(a)), handler: fn(a) -> b)

A rate limiter.

pub type RateLimiterBuilder(a, b, id) {
  RateLimiterBuilder(
    per_second: Option(Int),
    per_minute: Option(Int),
    per_hour: Option(Int),
    identifier: fn(a) -> id,
    handler: fn(a) -> b,
  )
}

Constructors

  • RateLimiterBuilder(
      per_second: Option(Int),
      per_minute: Option(Int),
      per_hour: Option(Int),
      identifier: fn(a) -> id,
      handler: fn(a) -> b,
    )

The actor state of the actor.

The state is a dictionary where the key is the identifier and the value is a list of epoch timestamps.

pub type State(a, b, id) {
  RateLimiterState(
    hit_log: dict.Dict(id, List(Int)),
    per_second: Option(Int),
    per_minute: Option(Int),
    per_hour: Option(Int),
    identifier: fn(a) -> id,
    handler: fn(a) -> b,
  )
}

Constructors

  • RateLimiterState(
      hit_log: dict.Dict(id, List(Int)),
      per_second: Option(Int),
      per_minute: Option(Int),
      per_hour: Option(Int),
      identifier: fn(a) -> id,
      handler: fn(a) -> b,
    )

Functions

pub fn apply(
  func: fn(a) -> b,
  limiter: RateLimiter(a, b),
) -> fn(a) -> b

Apply the rate limiter to a request handler or function.

pub fn build(
  config: RateLimiterBuilder(a, b, c),
) -> RateLimiter(a, b)

Build the rate limiter.

pub fn handler(
  limiter: RateLimiterBuilder(a, b, c),
  handler: fn(a) -> b,
) -> RateLimiterBuilder(a, b, c)

Set the handler to be called when the rate limit is reached.

pub fn identifier(
  limiter: RateLimiterBuilder(a, b, c),
  identifier: fn(a) -> c,
) -> RateLimiterBuilder(a, b, c)

Set the identifier function to be used to identify the rate limit.

pub fn new() -> RateLimiterBuilder(a, b, c)

Create a new rate limiter builder.

Panics when the rate limit hit counter cannot be created.

pub fn per_hour(
  limiter: RateLimiterBuilder(a, b, c),
  limit: Int,
) -> RateLimiterBuilder(a, b, c)

Set the rate limit per hour.

pub fn per_minute(
  limiter: RateLimiterBuilder(a, b, c),
  limit: Int,
) -> RateLimiterBuilder(a, b, c)

Set the rate limit per minute.

pub fn per_second(
  limiter: RateLimiterBuilder(a, b, c),
  limit: Int,
) -> RateLimiterBuilder(a, b, c)

Set the rate limit per second.

pub fn stop(limiter: RateLimiter(a, b)) -> Nil

Stop the rate limiter agent.

Search Document