trevrpc/rate_limit
A rate-limit interceptor: a token bucket for each method and client.
let assert Ok(limit) =
rate_limit.start(
rate_limit.Options(
..rate_limit.options(),
policies: [#("/example.auth.Auth/Login", rate_limit.Policy(5, 60_000))],
default: Some(rate_limit.Policy(100, 1000)),
),
)
server.Config(..config, interceptors: [rate_limit.interceptor(limit)])
A call that finds its bucket empty fails with ResourceExhausted and a
google.rpc.RetryInfo detail that says when a token is next available,
which status.retry_delay reads. It is an interceptor rather than an
authorizer, as a call the client replays after the server refused its
optimistic stream compression is authorized twice but intercepted once.
See trevrpc_rate_limit for how it counts clients and bounds its table.
Types
pub type Options {
Options(
policies: List(#(String, Policy)),
default: option.Option(Policy),
key: option.Option(fn(server.CallInfo) -> String),
ipv6_prefix: Int,
max_buckets: Int,
)
}
Constructors
-
Options( policies: List(#(String, Policy)), default: option.Option(Policy), key: option.Option(fn(server.CallInfo) -> String), ipv6_prefix: Int, max_buckets: Int, )Arguments
- policies
-
The policies of the methods they name, by path, such as
/example.auth.Auth/Login. Every method has a bucket of its own for each client. - default
-
The policy of every other method, which are unlimited without one.
- key
-
Names the client a call is counted against, in place of its address, such as an API key from the metadata. The key is kept as long as its bucket is, so it must not be unbounded text the client chooses without a check.
- ipv6_prefix
-
The length in bits of the IPv6 prefix whose addresses share a bucket, from 1 to 128; IPv4 addresses each have their own.
- max_buckets
-
The number of buckets kept.
A token bucket: a client may make requests calls at once, and the
bucket refills at requests per window milliseconds.
pub type Policy {
Policy(requests: Int, window: Int)
}
Constructors
-
Policy(requests: Int, window: Int)
Values
pub fn interceptor(limit: RateLimit) -> server.Interceptor
The limiter’s interceptor, for a server’s interceptors. Put it before
the interceptors whose work a rejected call should not cost.
pub fn options() -> Options
Options that limit nothing, with a client’s IPv6 /64 sharing a bucket and 10,000 buckets at most.
pub fn start(options: Options) -> Result(RateLimit, String)
Starts a limiter, linked to the calling process: it stops when that process exits, and the interceptors made from it fail every call they limit once it is gone. An error says which option cannot work, such as a policy for something that is not a method path.