Skip to main content

gatekpr_rate_limiter/
lib.rs

1//! Reusable rate limiting library
2//!
3//! Provides a flexible, high-performance rate limiting solution with:
4//! - Lock-free concurrent access using DashMap
5//! - Configurable per-minute and per-hour limits
6//! - Plan-based configuration (free, pro, enterprise)
7//! - Optional Axum middleware integration
8//!
9//! # Basic Usage
10//!
11//! ```rust
12//! use gatekpr_rate_limiter::{RateLimitConfig, RateLimitStore};
13//!
14//! // Create a store to track rate limits
15//! let store = RateLimitStore::new();
16//!
17//! // Get config for a plan
18//! let config = RateLimitConfig::for_plan("pro");
19//!
20//! // Check rate limit for a key (e.g., user ID, IP, tenant)
21//! let result = store.check("user-123", &config);
22//!
23//! if result.is_allowed() {
24//!     // Process the request
25//! } else {
26//!     // Return 429 Too Many Requests
27//!     if let Some(retry_after) = result.retry_after() {
28//!         println!("Rate limited. Retry after {} seconds", retry_after);
29//!     }
30//! }
31//! ```
32//!
33//! # Custom Configuration
34//!
35//! ```rust
36//! use gatekpr_rate_limiter::RateLimitConfigBuilder;
37//!
38//! let config = RateLimitConfigBuilder::new()
39//!     .per_minute(200)
40//!     .per_hour(10000)
41//!     .build();
42//! ```
43//!
44//! # Axum Integration (requires `axum` feature)
45//!
46//! ```rust,ignore
47//! use gatekpr_rate_limiter::axum::RateLimitLayer;
48//! use axum::Router;
49//!
50//! let app = Router::new()
51//!     .route("/api", get(handler))
52//!     .layer(RateLimitLayer::new());
53//! ```
54
55pub mod config;
56pub mod state;
57
58#[cfg(feature = "axum")]
59pub mod axum_layer;
60
61// Re-exports
62pub use config::{RateLimitConfig, RateLimitConfigBuilder};
63pub use state::{KeyRateLimit, RateLimitResult, RateLimitStore};
64
65#[cfg(feature = "axum")]
66pub use axum_layer::{RateLimitLayer, RateLimitService};
67
68/// Prelude module for convenient imports
69pub mod prelude {
70    pub use crate::config::{RateLimitConfig, RateLimitConfigBuilder};
71    pub use crate::state::{RateLimitResult, RateLimitStore};
72
73    #[cfg(feature = "axum")]
74    pub use crate::axum_layer::{RateLimitLayer, RateLimitService};
75}