tower_rate_limit_redis/
lib.rs

1//! ## Overview
2//! A Redis-backed rate-limiting middleware for Tower using [redis-rs](https://crates.io/crates/redis).
3//!
4//! Rate limiting is based on the [GCRA](https://liliace.dev/posts/intuition-of-the-gcra),
5//! which allows one request every [`emission_interval`], with unused allowance accumulating up to [`capacity`] to allow bursts.
6//!
7//! ## Required permissions
8//! Besides the commands redis-rs internally calls for all connections,
9//! this crate additionally uses the following commands:
10//! - [`EVALSHA`](https://valkey.io/commands/evalsha/)
11//! - [`GET`](https://valkey.io/commands/get/)
12//! - [`SCRIPT LOAD`](https://valkey.io/commands/script-load/)
13//! - [`SET`](https://valkey.io/commands/set/)
14//! - [`TIME`](https://valkey.io/commands/time/)
15//!
16//! ## Limitations
17//! All of [Redis](https://redis.io/), [Valkey](https://valkey.io/), and [Redict](https://redict.io/) currently embed [Lua](https://www.lua.org/) 5.1.
18//! Until they upgrade it to 5.3 or later, integers are stored as doubles, which start losing precision beyond 2^53.
19//! This occurs if the rate limit resets after May 2057, which is possible (but strongly discouraged) with improperly high [`capacity`] and [`emission_interval`], combined with heavy traffic.
20//!
21//! [`emission_interval`]: RateLimitLayerBuilder::emission_interval
22//! [`capacity`]: RateLimitLayerBuilder::capacity
23//!
24//! ## Features
25//! Exactly one of the tokio and smol features must be enabled.
26//!
27//! Name | Default | Description
28//! ---|---|---
29//! tokio | x | Use the Tokio runtime
30//! smol | | Use the smol runtime. Warning: not yet tested with the smol runtime (tests use the Tokio runtime, though they did pass with this feature enabled 😅)
31//! tracing | | Enable tracing. Keys are recorded as `&str`s if valid UTF-8, or as raw `&[u8]` otherwise
32//!
33//! ## Example
34//! ```
35#![doc = include_str!("../examples/axum.rs")]
36//! ```
37
38#[cfg(not(any(feature = "tokio", feature = "smol")))]
39compile_error!("At least one of the features `tokio` or `smol` must be enabled");
40
41#[cfg(all(feature = "tokio", feature = "smol"))]
42compile_error!("Features `tokio` and `smol` cannot be enabled at the same time");
43
44use cfg_if::cfg_if;
45
46cfg_if! {
47    if #[cfg(all(any(feature = "tokio", feature = "smol"), not(all(feature = "tokio", feature = "smol"))))] {
48        mod config;
49        mod future;
50        mod key_resolver;
51        mod layer;
52        mod service;
53
54        pub use key_resolver::*;
55        pub use layer::*;
56    }
57}