governor/
lib.rs

1//! # governor - a rate-limiting library for rust.
2//!
3//! Governor aims to be a very efficient and ergonomic way to enforce
4//! rate limits in Rust programs. It implements the [Generic Cell Rate
5//! Algorithm](https://en.wikipedia.org/wiki/Generic_cell_rate_algorithm)
6//! and keeps state in a very efficient way.
7//!
8//! For detailed information on usage, please see the [user's guide][crate::_guide].
9//!
10//! # Quick example
11//!
12//! In this example, we set up a rate limiter to allow 50 elements per
13//! second, and check that a single element can pass through.
14//!
15//! ``` rust
16//! use std::num::NonZeroU32;
17//! use nonzero_ext::*;
18//! use governor::{Quota, RateLimiter};
19//!
20//! # #[cfg(feature = "std")]
21//! # fn main () {
22//! let mut lim = RateLimiter::direct(Quota::per_second(nonzero!(50u32))); // Allow 50 units per second
23//! assert_eq!(Ok(()), lim.check());
24//! # }
25//! # #[cfg(not(feature = "std"))]
26//! # fn main() {}
27//! ```
28//!
29
30#![cfg_attr(not(feature = "std"), no_std)]
31// Clippy config: Deny warnings but allow unknown lint configuration (so I can use nightly)
32#![deny(warnings)]
33#![allow(unknown_lints)]
34// Unfortunately necessary, otherwise features aren't supported in doctests:
35#![allow(clippy::needless_doctest_main)]
36
37extern crate no_std_compat as std;
38
39pub mod r#_guide;
40pub mod clock;
41mod errors;
42mod gcra;
43mod jitter;
44pub mod middleware;
45pub mod nanos;
46mod quota;
47pub mod state;
48
49pub use errors::*;
50pub use gcra::NotUntil;
51#[cfg(all(feature = "std", feature = "jitter"))]
52pub use jitter::Jitter;
53#[cfg(all(feature = "std", not(feature = "jitter")))]
54pub(crate) use jitter::Jitter;
55pub use quota::Quota;
56#[doc(inline)]
57pub use state::RateLimiter;
58
59#[cfg(feature = "std")]
60pub use state::direct::RatelimitedSink;
61#[cfg(feature = "std")]
62pub use state::direct::RatelimitedStream;
63
64/// The collection of asynchronous traits exported from this crate.
65pub mod prelude {
66    #[cfg(feature = "std")]
67    pub use crate::state::direct::SinkRateLimitExt;
68    #[cfg(feature = "std")]
69    pub use crate::state::direct::StreamRateLimitExt;
70}
71
72/// A rate limiter representing a single item of state in memory, running on the default clock.
73///
74/// See the [`RateLimiter`] documentation for details.
75pub type DefaultDirectRateLimiter<
76    MW = middleware::NoOpMiddleware<<clock::DefaultClock as clock::Clock>::Instant>,
77> = RateLimiter<state::direct::NotKeyed, state::InMemoryState, clock::DefaultClock, MW>;
78
79/// A rate limiter with one state per key, running on the default clock.
80///
81/// See the [`RateLimiter`] documentation for details.
82pub type DefaultKeyedRateLimiter<
83    K,
84    MW = middleware::NoOpMiddleware<<clock::DefaultClock as clock::Clock>::Instant>,
85> = RateLimiter<K, state::keyed::DefaultKeyedStateStore<K>, clock::DefaultClock, MW>;