Skip to main content

tower_rate_tier/
lib.rs

1//! Tier-based rate limiting middleware for [`tower`](https://docs.rs/tower) services.
2//!
3//! Assign users to named tiers (e.g. "free", "pro") with distinct quotas,
4//! and let the middleware enforce limits automatically via the GCRA algorithm.
5//!
6//! # Features
7//!
8//! - `buffered-body`: identify users from the request body
9//!   (`TierLimitLayer::buffer_body`).
10//! - `redis`: `RedisStorage` keeps the limits in Redis, shared by every
11//!   instance of a service. Requires Rust 1.88.
12
13#![warn(missing_debug_implementations)]
14
15pub(crate) mod check;
16/// Clock abstractions for real and deterministic (test) time sources.
17pub mod clock;
18/// Cost extraction: decide how many tokens each request consumes.
19pub mod cost;
20/// Events reported while rate limiting, for logging and metrics.
21pub mod event;
22/// Background garbage collection for expired rate-limit entries.
23pub mod gc;
24/// Generic Cell Rate Algorithm (GCRA) implementation.
25pub mod gcra;
26/// User identity and tier extraction from incoming requests.
27pub mod identifier;
28/// Tower `Layer` implementation that wraps services with rate limiting.
29pub mod layer;
30/// Policy for handling requests whose identity cannot be resolved.
31pub mod on_missing;
32/// Policy for handling storage backend errors.
33pub mod on_storage_error;
34/// Policy for handling tiers that are not configured.
35pub mod on_unknown_tier;
36/// Quota definitions (rate, burst, period).
37pub mod quota;
38/// HTTP response helpers for rate-limit headers and 429 replies.
39pub mod response;
40/// Tower `Service` implementation that enforces per-tier rate limits.
41pub mod service;
42/// Storage backends for persisting rate-limit state.
43pub mod storage;
44/// Tier configuration and the `RateTier` builder.
45pub mod tier;
46
47#[cfg(feature = "buffered-body")]
48/// Buffered-body variants that allow identifier access to the request body.
49///
50/// Requires the `buffered-body` feature.
51pub mod buffered;
52
53pub use cost::{tier_cost, TierCost};
54pub use event::LimitEvent;
55pub use gcra::{RateLimitInfo, RateLimited};
56pub use identifier::{TierIdentifier, TierIdentity};
57pub use layer::TierLimitLayer;
58pub use on_missing::OnMissing;
59pub use on_storage_error::OnStorageError;
60pub use on_unknown_tier::OnUnknownTier;
61pub use quota::{Nanos, Quota};
62pub use storage::{StorageError, StorageKey};
63pub use tier::{CheckError, RateTier};
64
65#[cfg(feature = "buffered-body")]
66pub use buffered::{BufferedTierLimitLayer, BufferedTierLimitService};
67#[cfg(feature = "redis")]
68pub use storage::redis::RedisStorage;