foretoken v0.1.1 Foretoken View Source

An ETS-based implementation of the token bucket algorithm.

Hex.pm Build Status Coverage Status

Feature & Design

  • ETS as bucket storage
  • Direct access to ETS table to exploit concurrency
  • On-demand creation of buckets
  • Automatic cleanup of unused buckets
  • Extremely simple API (only 1 public interface function): Foretoken.take/4.

Compatibility notes

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

Link to this section Summary

Functions

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

Link to this section Functions

Link to this function take(bucket, milliseconds_per_token, max_tokens, tokens_to_take \\ 1) View Source
take(any(), pos_integer(), pos_integer(), pos_integer()) ::
  :ok | {:error, pos_integer()}

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/4; 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.