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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
//! Rate Limiting
//!
//! Per-topic and per-node rate limiting to prevent message flooding and ensure QoS.
//!
//! # Features
//!
//! - Token bucket algorithm for smooth rate limiting
//! - Per-topic limits
//! - Per-node limits
//! - Burst capacity
//! - Configurable policies
//! - Metrics integration
//! - Low overhead with async
//!
//! # Example
//!
//! ```rust
//! use mecha10_core::prelude::*;
//! use mecha10_core::rate_limit::{RateLimiter, RateLimit};
//!
//! # async fn example() -> Result<()> {
//! // Create rate limiter: 10 messages/sec with burst of 20
//! let limiter = RateLimiter::new(10.0, 20);
//!
//! // Check if message is allowed
//! if limiter.check_and_consume().await {
//! // Allowed - publish message
//! println!("Message allowed");
//! } else {
//! // Rate limited - drop or queue
//! println!("Rate limited!");
//! }
//! # Ok(())
//! # }
//! ```
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::RwLock;
pub struct RateLimiter {
tokens: Arc<RwLock<f64>>,
capacity: f64,
refill_rate: f64,
last_refill: Arc<RwLock<Instant>>,
}
impl RateLimiter {
/// Create a new rate limiter
///
/// # Arguments
///
/// * `rate` - Messages per second
/// * `burst` - Maximum burst size
///
/// # Example
///
/// ```rust
/// use mecha10_core::rate_limit::RateLimiter;
///
/// // 100 msg/sec with burst of 200
/// let limiter = RateLimiter::new(100.0, 200);
/// ```
pub fn new(rate: f64, burst: usize) -> Self {
Self {
tokens: Arc::new(RwLock::new(burst as f64)),
capacity: burst as f64,
refill_rate: rate,
last_refill: Arc::new(RwLock::new(Instant::now())),
}
}
/// Check if request is allowed (does not consume token)
pub async fn check(&self) -> bool {
self.refill().await;
let tokens = self.tokens.read().await;
*tokens >= 1.0
}
/// Check and consume a token if available
pub async fn check_and_consume(&self) -> bool {
self.refill().await;
let mut tokens = self.tokens.write().await;
if *tokens >= 1.0 {
*tokens -= 1.0;
true
} else {
false
}
}
/// Get current token count
pub async fn available_tokens(&self) -> f64 {
self.refill().await;
*self.tokens.read().await
}
/// Refill tokens based on elapsed time
async fn refill(&self) {
let now = Instant::now();
let mut last_refill = self.last_refill.write().await;
let elapsed = now.duration_since(*last_refill).as_secs_f64();
if elapsed > 0.0 {
let tokens_to_add = elapsed * self.refill_rate;
let mut tokens = self.tokens.write().await;
*tokens = (*tokens + tokens_to_add).min(self.capacity);
*last_refill = now;
}
}
/// Reset the rate limiter (fill bucket)
pub async fn reset(&self) {
let mut tokens = self.tokens.write().await;
*tokens = self.capacity;
let mut last_refill = self.last_refill.write().await;
*last_refill = Instant::now();
}
}
#[derive(Debug, Clone)]
pub struct RateLimit {
pub rate: f64,
pub burst: usize,
}
impl RateLimit {
/// Create a new rate limit policy
pub fn new(rate: f64, burst: usize) -> Self {
Self { rate, burst }
}
/// Create rate limit from messages per second (burst = rate * 2)
pub fn per_second(rate: f64) -> Self {
Self {
rate,
burst: (rate * 2.0) as usize,
}
}
/// Create rate limit from messages per minute
pub fn per_minute(rate: f64) -> Self {
let per_sec = rate / 60.0;
Self {
rate: per_sec,
burst: (per_sec * 2.0) as usize,
}
}
/// No limit
pub fn unlimited() -> Self {
Self {
rate: f64::MAX,
burst: usize::MAX,
}
}
}
pub struct MultiKeyRateLimiter {
limiters: Arc<RwLock<HashMap<String, RateLimiter>>>,
default_limit: RateLimit,
}
impl MultiKeyRateLimiter {
/// Create a new multi-key rate limiter with default unlimited
pub fn new() -> Self {
Self {
limiters: Arc::new(RwLock::new(HashMap::new())),
default_limit: RateLimit::unlimited(),
}
}
/// Create with a default limit for all keys
pub fn with_default(default: RateLimit) -> Self {
Self {
limiters: Arc::new(RwLock::new(HashMap::new())),
default_limit: default,
}
}
/// Set rate limit for a specific key
pub async fn set_limit(&self, key: impl Into<String>, limit: RateLimit) {
let key = key.into();
let limiter = RateLimiter::new(limit.rate, limit.burst);
let mut limiters = self.limiters.write().await;
limiters.insert(key, limiter);
}
/// Check if request for key is allowed
pub async fn check(&self, key: &str) -> bool {
let limiters = self.limiters.read().await;
if let Some(limiter) = limiters.get(key) {
limiter.check().await
} else if self.default_limit.rate == f64::MAX {
true
} else {
drop(limiters);
self.set_limit(key, self.default_limit.clone()).await;
true
}
}
/// Check and consume token for key
pub async fn check_and_consume(&self, key: &str) -> bool {
let should_create = {
let limiters = self.limiters.read().await;
!limiters.contains_key(key) && self.default_limit.rate != f64::MAX
};
if should_create {
self.set_limit(key, self.default_limit.clone()).await;
}
let limiters = self.limiters.read().await;
if let Some(limiter) = limiters.get(key) {
limiter.check_and_consume().await
} else {
true
}
}
/// Get available tokens for a key
pub async fn available_tokens(&self, key: &str) -> Option<f64> {
let limiters = self.limiters.read().await;
if let Some(limiter) = limiters.get(key) {
Some(limiter.available_tokens().await)
} else {
None
}
}
/// Clear all limiters
pub async fn clear(&self) {
let mut limiters = self.limiters.write().await;
limiters.clear();
}
}
impl Default for MultiKeyRateLimiter {
fn default() -> Self {
Self::new()
}
}
pub struct RateLimiterManager {
node_limiters: Arc<MultiKeyRateLimiter>,
}
impl RateLimiterManager {
/// Create a new rate limiter manager
pub fn new() -> Self {
Self {
node_limiters: Arc::new(MultiKeyRateLimiter::new()),
}
}
/// Check if node can publish
pub async fn check_node(&self, node_id: &str) -> bool {
self.node_limiters.check_and_consume(node_id).await
}
}
impl Default for RateLimiterManager {
fn default() -> Self {
Self::new()
}
}