Foretoken (foretoken v0.4.0)

Copy Markdown View Source

An ETS-based implementation of the token bucket algorithm.

Hex.pm Coverage Status

Feature & Design

  • Simplest possible API (only 1 public interface function: Foretoken.take/5)
  • ETS as concurrently accessible bucket storage
  • Bucket lifecycle management
    • On-demand creation of buckets (whch can be disabled)
    • Automatic cleanup of unused buckets

Compatibility notes

This package requires Erlang/OTP 20 (or later).


See also Foretoken.Config.

Summary

Functions

Tries to take the specified number of token(s) from the bucket identified by bucket.

Types

reason()

@type reason() ::
  {:not_enough_token, milliseconds_to_wait :: pos_integer()}
  | :nonexisting_bucket

Functions

take(bucket, milliseconds_per_token, max_tokens, tokens_to_take \\ 1, create_nonexisting_bucket? \\ true)

@spec take(
  any(),
  pos_integer(),
  pos_integer(),
  pos_integer(),
  boolean()
) :: :ok | {:error, reason()}

Tries to take the specified number of token(s) from the bucket identified by bucket.

If the specified bucket does not exist, it's created on-demand filled with max_tokens tokens. If the bucket exists, current number of tokens is computed (using milliseconds_per_token and max_tokens) and, if available, tokens_to_take tokens are removed from the bucket. When there are no enough tokens in the bucket this function returns {:error, milliseconds_to_wait}, where milliseconds_to_wait is the duration after which the requested tokens become available. Note that waiting for milliseconds_to_wait doesn't guarantee success at the next take/5; another concurrent process may precede the current process.

Although you can use basically arbitrary term for bucket argument, atoms with $ and integers (such as :"$1", :"$2", ...) are not usable.