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
//! Token-bucket rate limiting utilities.
//!
//! This module provides a lightweight, thread-safe token-bucket [`RateLimiter`]
//! implementation. A token bucket accumulates tokens over time at a fixed rate
//! up to a maximum capacity. Each permitted action consumes one token. If the
//! bucket is empty, the action is not allowed.
//!
//! - Useful for protecting external services, APIs, or any resource from being
//! overwhelmed.
//! - Non-blocking: [`RateLimiter::allow`] returns immediately with a boolean.
//! - Thread-safe: internal state is protected by `Mutex`es wrapped in `Arc`s so
//! a single limiter can be shared across threads.
//!
//! Basic example:
//!
//! ```rust
//! use toolchest::functions::RateLimiter;
//! use std::time::Duration;
//! use std::thread::sleep;
//!
//! // Capacity: 2 tokens; Refill rate: 5 tokens/second
//! let limiter = RateLimiter::new(2, 5);
//!
//! assert!(limiter.allow()); // consume 1
//! assert!(limiter.allow()); // consume 2 (bucket now empty)
//! assert!(!limiter.allow()); // no tokens available
//!
//! // After ~300ms at 5 tokens/sec, ~1.5 tokens accumulate (clamped to capacity)
//! sleep(Duration::from_millis(300));
//! assert!(limiter.allow()); // now allowed again
//! ```
//!
//! Sharing across threads:
//!
//! ```rust
//! use toolchest::functions::RateLimiter;
//! use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
//! use std::thread;
//! use std::time::Duration;
//!
//! let limiter = Arc::new(RateLimiter::new(1, 2)); // 1 token capacity, 2/sec refill
//! let hits = Arc::new(AtomicUsize::new(0));
//!
//! let mut handles = Vec::new();
//! for _ in 0..3 {
//! let limiter_cloned = Arc::clone(&limiter);
//! let hits_cloned = Arc::clone(&hits);
//! handles.push(thread::spawn(move || {
//! if limiter_cloned.allow() {
//! hits_cloned.fetch_add(1, Ordering::SeqCst);
//! }
//! }));
//! }
//! for h in handles { h.join().unwrap(); }
//!
//! // At most 1 immediate hit (capacity 1). After a short wait, more would be allowed.
//! assert!(hits.load(Ordering::SeqCst) <= 1);
//! ```
use ;
use Instant;
/// Token-bucket rate limiter.
///
/// - `capacity`: maximum number of tokens the bucket can hold
/// - `refill_per_sec`: number of tokens replenished per second
///
/// Tokens are tracked with fractional precision, so refills are smooth over
/// time. Methods are thread-safe and can be called from multiple threads.