Skip to main content

throttle_machines/
lib.rs

1//! Rate limiting on a caller-supplied clock: GCRA, token bucket and fixed
2//! window, each a small `Copy` value behind the shared [`Gate`] contract.
3//!
4//! The crate is `no_std` and allocation-free; it reads no clock. `now` is a
5//! [`Duration`](core::time::Duration) since an epoch the caller picks, and so
6//! is every span. A refused call answers [`Refusal`] and changes nothing.
7//!
8//! The `std` feature adds [`KeyedGcra`], which keeps per-key GCRA state in a
9//! sharded, mutex-guarded map.
10//!
11//! ```
12//! use core::num::NonZeroU64;
13//! use core::time::Duration;
14//! use throttle_machines::{Gate, Gcra, GcraPolicy, Refusal};
15//!
16//! let policy = GcraPolicy::per(Duration::from_secs(1), NonZeroU64::new(2).unwrap(), NonZeroU64::MIN)
17//!     .unwrap();
18//! let mut gcra = Gcra::new(policy);
19//! let now = Duration::from_secs(100);
20//! assert_eq!(gcra.check(now), Ok(0));
21//! assert_eq!(gcra.check(now), Err(Refusal::Throttled));
22//! assert_eq!(gcra.retry_after(now), Duration::from_millis(500));
23//! ```
24
25#![no_std]
26#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
27
28#[cfg(feature = "std")]
29extern crate std;
30
31mod fixed_window;
32mod gate;
33mod gcra;
34#[cfg(feature = "std")]
35mod keyed;
36mod refusal;
37mod token_bucket;
38
39/// Compiles and runs the README's examples as doctests.
40#[cfg(doctest)]
41#[doc = include_str!("../README.md")]
42struct ReadmeDoctests;
43
44pub use fixed_window::{FixedWindow, FixedWindowPolicy};
45pub use gate::Gate;
46pub use gcra::{Gcra, GcraPolicy};
47#[cfg(feature = "std")]
48pub use keyed::KeyedGcra;
49pub use refusal::Refusal;
50pub use token_bucket::{TokenBucket, TokenBucketPolicy};