1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! Rate-Guard: A flexible and type-safe rate limiting library for Rust.
//!
//! Rate-Guard provides a unified interface for multiple rate limiting algorithms
//! with Duration-based configuration, type-safe time handling, and comprehensive
//! error reporting. It's designed to integrate seamlessly with Rust's async
//! ecosystem while maintaining high performance through zero-cost abstractions.
//!
//! Key Features:
//! - Duration-Based Configuration: All timing parameters use std::time::Duration
//! - Multiple Algorithms: Token bucket, fixed window counter, sliding window counter, and approximate sliding window
//! - Time Source Abstraction: Pluggable time sources (mock, std::time, etc.)
//! - Precision Control: Compile-time precision selection for optimal performance
//! - Builder Pattern: Fluent configuration API with compile-time validation
//! - Zero-Cost Abstractions: High-level ergonomics without runtime overhead
//! - Comprehensive Testing: Built-in mock time source for deterministic testing
//!
//!
//! # Feature Flags
//!
//! ## Time Sources (Optional)
//! - `std-time` - Standard library time source (recommended for production)
//! - `tokio-time` - Tokio time source (for async environments)
//!
//! ## Precision Types (Mutually Exclusive, defaults to u64)
//! - `tick-u64` (default) - 64-bit precision, suitable for most scenarios
//! - `tick-u128` - 128-bit precision, for extreme long-duration use cases
//!
//! ```toml
//! # Default configuration
//! rate-guard = "0.1.0"
//!
//! # Production recommended
//! rate-guard = { version = "0.1.0", features = ["std-time"] }
//!
//! # Special requirements: high precision
//! rate-guard = { version = "0.1.0", features = ["std-time", "tick-u128"] }
//! ```
//!
//!
//! # Quick Start
//!
//! ```rust
//! use rate_guard::{Nanos, MockTimeSource, RateLimit};
//! use rate_guard::limits::TokenBucketBuilder;
//! use std::time::Duration;
//!
//! // Create a token bucket using the builder pattern
//! let bucket = TokenBucketBuilder::builder()
//! .capacity(100)
//! .refill_amount(10)
//! .refill_every(Duration::from_millis(100))
//! .with_time(MockTimeSource::new())
//! .with_precision::<Nanos>()
//! .build()
//! .unwrap();
//!
//! // Use the rate limiter
//! match bucket.try_acquire(50) {
//! Ok(()) => println!("Request allowed"),
//! Err(_) => println!("Rate limited"),
//! }
//! ```
//!
//! # Testing with Mock Time
//!
//! ```rust
//! use rate_guard::{Millis, MockTimeSource, RateLimit};
//! use rate_guard::limits::TokenBucketBuilder;
//! use std::time::Duration;
//!
//! let time_source = MockTimeSource::new();
//! let bucket = TokenBucketBuilder::builder()
//! .capacity(50)
//! .refill_amount(5)
//! .refill_every(Duration::from_millis(200))
//! .with_time(time_source.clone())
//! .with_precision::<Millis>()
//! .build()
//! .unwrap();
//!
//! // Use all tokens
//! assert!(bucket.try_acquire(50).is_ok());
//! assert_eq!(bucket.capacity_remaining().unwrap(), 0);
//!
//! // Advance time to trigger refill
//! time_source.advance(Duration::from_millis(200));
//! assert_eq!(bucket.capacity_remaining().unwrap(), 5);
//! ```
//!
//! # All Rate Limiter Types
//!
//! ```rust
//! use rate_guard::{
//! Millis, MockTimeSource, RateLimit
//! };
//! use rate_guard::limits::{
//! TokenBucketBuilder, FixedWindowCounterBuilder,
//! SlidingWindowCounterBuilder, ApproximateSlidingWindowBuilder
//! };
//! use std::time::Duration;
//!
//! let time_source = MockTimeSource::new();
//!
//! // Token Bucket - allows bursts
//! let token_bucket = TokenBucketBuilder::builder()
//! .capacity(100)
//! .refill_amount(10)
//! .refill_every(Duration::from_millis(100))
//! .with_time(time_source.clone())
//! .with_precision::<Millis>()
//! .build()
//! .unwrap();
//!
//!
//! // Fixed Window Counter
//! let fixed_window = FixedWindowCounterBuilder::builder()
//! .capacity(100)
//! .window_duration(Duration::from_secs(60))
//! .with_time(time_source.clone())
//! .with_precision::<Millis>()
//! .build()
//! .unwrap();
//!
//! // Sliding Window Counter
//! let sliding_window = SlidingWindowCounterBuilder::builder()
//! .capacity(100)
//! .bucket_duration(Duration::from_secs(10))
//! .bucket_count(6)
//! .with_time(time_source.clone())
//! .with_precision::<Millis>()
//! .build()
//! .unwrap();
//!
//! // Approximate Sliding Window
//! let approx_window = ApproximateSlidingWindowBuilder::builder()
//! .capacity(100)
//! .window_duration(Duration::from_secs(60))
//! .with_time(time_source)
//! .with_precision::<Millis>()
//! .build()
//! .unwrap();
//! ```
// Re-export core types
pub use Uint;
// Precision system
pub use ;
// Time source abstraction
pub use ;
pub use StdTimeSource;
pub use TokioTimeSource;
// Error types with Duration-based retry timing and builder validation
pub use ;
// Rate limiter implementations
pub use ;
// Configuration types (keeping for backward compatibility)
pub use *;
// Standard rate limiter type aliases for backward compatibility
/// Type alias for a fixed window counter with standard nanosecond precision.
pub type FixedWindowCounterNanos = ;
/// Type alias for a sliding window counter with standard nanosecond precision.
pub type SlidingWindowCounterNanos = ;
/// Type alias for an approximate sliding window with standard nanosecond precision.
pub type ApproximateSlidingWindowNanos = ;
// Type aliases for common configurations (users can define their own)
/// Common configuration: Token bucket with nanosecond precision and standard time.
pub type StdTokenBucket = ;
/// Common configuration: Token bucket with nanosecond precision and mock time for testing.
pub type MockTokenBucket = ;
/// Common configuration: Token bucket with millisecond precision and standard time.
pub type MillisTokenBucket = ;
/// Common configuration: Token bucket with millisecond precision and mock time for testing.
pub type MillisMockTokenBucket = ;
pub type StdFixedWindowCounter = ;
pub type MockFixedWindowCounter = ;
pub type StdSlidingWindowCounter = ;
pub type MockSlidingWindowCounter = ;
pub type StdApproximateSlidingWindow = ;
pub type MockApproximateSlidingWindow = ;