View Source opuntia (opuntia v1.1.0)
opuntia
, traffic shapers for Erlang and Elixir
This module implements the token-bucket traffic-shaping algorithm.
The rate is given in tokens/0
per time_unit/0
and a bucket size. Resolution is in native unit times as described by erlang:monotonic_time/0
.
Summary
Types
Maximum capacity of the bucket regardless of how much time passes.
Number of milliseconds that is advise to wait after a shaping update.
Number of tokens accepted per
time_unit/0
.Shaper type
Supported shaping time units.
Unit element the shaper consumes, for example bytes or requests.
Functions
Creates a new shaper according to the configuration.
Peek currently available tokens.
Update shaper and return possible waiting time.
Types
-type bucket_size() :: non_neg_integer().
-type config() :: 0 | #{bucket_size := bucket_size(), rate := rate(), time_unit := time_unit(), start_full := boolean()}.
-type delay() :: non_neg_integer().
-type rate() :: non_neg_integer().
time_unit/0
.
-type shape() :: {bucket_size(), rate(), time_unit()}.
new/1
for more details.
-type shaper() :: none | #token_bucket_shaper{}.
-type time_unit() :: second | millisecond | microsecond | nanosecond | native.
-type tokens() :: non_neg_integer().
Functions
Creates a new shaper according to the configuration.
If zero is given, no shaper in created and any update action will always return zero delay; to configure a shaper it will need a config like #{bucket_size => MaximumTokens, rate => Rate, time_unit => TimeUnit, start_full => Boolean}
whereTimeUnit
is the time unit of measurement as defined bytime_unit/0
Rate
is the number of tokens perTimeUnit
the bucket will grow with.MaximumTokens
is the maximum number of tokens the bucket can grow.StartFull
indicates if the shaper starts with the bucket full, or empty if not.
#{bucket_size => 60000, rate => 10, time_unit => millisecond, start_full => true}
it means that the bucket will allow 10
tokens per millisecond
, up to 60000 tokens, regardless of how long it is left unused to charge: it will never charge further than 60000 tokens.
-spec peek(shaper()) -> non_neg_integer() | infinity.
Update shaper and return possible waiting time.
This function takes the current shaper state, and the number of tokens that have been consumed, and returns a tuple containing the new shaper state, and a possibly non-zero number of unit times to wait if more tokens that the shaper allows were consumed.