ntex_ratelimiter/lib.rs
1//! # ntex-ratelimiter
2//!
3//! `ntex-ratelimiter` is a rate limiting middleware for the `ntex` web framework.
4//! It uses the token bucket algorithm to limit the number of requests from clients
5//! based on their IP address.
6//!
7//! ## Features
8//!
9//! - **Token Bucket Algorithm**: Efficiently manages request rates.
10//! - **IP-based Rate Limiting**: Identifies clients by IP address, with support for `X-Forwarded-For` and `X-Real-IP` headers.
11//! - **Configurable**: Allows customization of capacity, time window, and cleanup intervals.
12//! - **Asynchronous Cleanup**: Periodically removes stale rate limit entries to save memory.
13//! - **Response Headers**: Adds `X-RateLimit-Remaining`, `X-RateLimit-Limit`, and `X-RateLimit-Reset` headers to responses.
14//! - **Customizable Error Response**: Returns a `429 Too Many Requests` JSON response when limits are exceeded.
15//! - **Runtime Agnostic**: Supports both `tokio` (default) and `async-std` runtimes via feature flags.
16//!
17//! ## Installation
18//!
19//! Add this to your `Cargo.toml`:
20//!
21//! ```toml
22//! [dependencies]
23//! ntex-ratelimiter = "^0.1.0"
24//! ```
25//!
26//! ## Feature Flags
27//!
28//! - `tokio` (default): Enables Tokio runtime support.
29//! - `async-std`: Enables async-std runtime support.
30//! - `json` (default): Enables JSON serialization for error responses using `serde`.
31//!
32//! Example with `async-std` and `json`:
33//! ```toml
34//! [dependencies]
35//! ntex-ratelimiter = { version = "^0.1.0", default-features = false, features = ["async-std", "json"] }
36//! ```
37//!
38//! ## Quick Start
39//!
40//! ```rust,no_run
41//! use ntex::web;
42//! use ntex_ratelimiter::{RateLimit, RateLimiter};
43//!
44//! #[ntex::main]
45//! async fn main() -> std::io::Result<()> {
46//! // Create a rate limiter: 100 requests per 60 seconds
47//! let limiter = RateLimiter::new(100, 60);
48//!
49//! web::HttpServer::new(move || {
50//! web::App::new()
51//! // Apply rate limiting middleware
52//! .wrap(RateLimit::new(limiter.clone()))
53//! .service(web::resource("/").to(|| async { "Hello world!" }))
54//! })
55//! .bind("127.0.0.1:8080")?
56//! .run()
57//! .await
58//! }
59//! ```
60//!
61//! For more advanced usage and configuration, please refer to the documentation of
62//! [`RateLimiter`] and [`RateLimiterConfig`].
63//!
64//! ## Module Structure
65//!
66//! - `limiter`: Contains the core rate limiting logic, including the `RateLimiter` struct,
67//! `RateLimiterConfig`, `TokenBucket` implementation, and the `RateLimit` ntex middleware.
68
69mod limiter;
70
71pub use limiter::{RateLimit, RateLimitResult, RateLimiter, RateLimiterConfig, RateLimiterStats};
72
73// Prevent conflicting runtime features
74#[cfg(all(feature = "tokio", feature = "async-std"))]
75compile_error!("Features \"tokio\" and \"async-std\" cannot be enabled at the same time.");
76
77#[cfg(not(any(feature = "tokio", feature = "async-std")))]
78compile_error!("Enable either feature \"tokio\" or \"async-std\" for ntex-ratelimiter to work.");
79
80#[cfg(feature = "tokio")]
81pub use tokio;
82
83#[cfg(feature = "async-std")]
84pub use async_std;