throttle_machines 0.4.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +231 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +31 -0
- data/README.md +89 -14
- data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
- data/ext/throttle_machines_native/core/Cargo.toml +25 -0
- data/ext/throttle_machines_native/core/README.md +100 -0
- data/ext/throttle_machines_native/core/src/fixed_window.rs +172 -0
- data/ext/throttle_machines_native/core/src/gate.rs +82 -0
- data/ext/throttle_machines_native/core/src/gcra.rs +219 -0
- data/ext/throttle_machines_native/core/src/keyed.rs +325 -0
- data/ext/throttle_machines_native/core/src/lib.rs +50 -0
- data/ext/throttle_machines_native/core/src/refusal.rs +30 -0
- data/ext/throttle_machines_native/core/src/token_bucket.rs +191 -0
- data/ext/throttle_machines_native/extconf.rb +2 -0
- data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
- data/ext/throttle_machines_native/ffi/Cargo.toml +22 -0
- data/ext/throttle_machines_native/ffi/extconf.rb +14 -0
- data/ext/throttle_machines_native/ffi/src/init.rs +63 -0
- data/ext/throttle_machines_native/ffi/src/lib.rs +255 -0
- data/ext/throttle_machines_native/ffi/src/values.rs +194 -0
- data/lib/throttle_machines/async_breaker.rb +5 -0
- data/lib/throttle_machines/async_support.rb +16 -21
- data/lib/throttle_machines/breakers.rb +46 -0
- data/lib/throttle_machines/control.rb +25 -46
- data/lib/throttle_machines/controller_helpers.rb +11 -10
- data/lib/throttle_machines/hedged_breaker.rb +4 -6
- data/lib/throttle_machines/hedged_request.rb +29 -42
- data/lib/throttle_machines/instrumentation.rb +10 -75
- data/lib/throttle_machines/limiter.rb +71 -136
- data/lib/throttle_machines/middleware.rb +6 -6
- data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
- data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
- data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
- data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
- data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
- data/lib/throttle_machines/rack_middleware.rb +3 -1
- data/lib/throttle_machines/storage/base.rb +49 -48
- data/lib/throttle_machines/storage/cache.rb +12 -6
- data/lib/throttle_machines/storage/memory.rb +68 -96
- data/lib/throttle_machines/storage/null.rb +18 -28
- data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
- data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
- data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
- data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
- data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
- data/lib/throttle_machines/storage/redis.rb +63 -69
- data/lib/throttle_machines/throttled_error.rb +4 -1
- data/lib/throttle_machines/version.rb +1 -1
- data/lib/throttle_machines.rb +130 -87
- data/sig/throttle_machines.rbs +555 -0
- metadata +55 -71
- data/lib/throttle_machines/async_limiter.rb +0 -24
- data/lib/throttle_machines/dependency_error.rb +0 -6
- data/lib/throttle_machines/native_speedup.rb +0 -110
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
//! Generic Cell Rate Algorithm: smooth rate limiting through a theoretical
|
|
2
|
+
//! arrival time (TAT) that each admission pushes one emission interval on.
|
|
3
|
+
//!
|
|
4
|
+
//! Every count is exact. A policy exists only when its burst ceiling
|
|
5
|
+
//! (`delay_tolerance + emission_interval`) is a `Duration` and holds at most
|
|
6
|
+
//! `u64::MAX` emission intervals, so the capacity a gate answers is never
|
|
7
|
+
//! clamped. The TAT never saturates: an admission that would push it past
|
|
8
|
+
//! `Duration::MAX` is refused as [`Refusal::Overflow`] with nothing changed,
|
|
9
|
+
//! and `peek` counts only the admissions whose TAT fits. No later instant
|
|
10
|
+
//! lifts an `Overflow`, so `retry_after` answers `Duration::MAX` (never)
|
|
11
|
+
//! when the next admission's TAT cannot fit; the subtractions that measure
|
|
12
|
+
//! how far ahead the TAT runs floor at zero.
|
|
13
|
+
|
|
14
|
+
use core::num::NonZeroU64;
|
|
15
|
+
use core::time::Duration;
|
|
16
|
+
|
|
17
|
+
use crate::gate::{count, fits, share, times};
|
|
18
|
+
use crate::{Gate, Refusal};
|
|
19
|
+
|
|
20
|
+
/// How a [`Gcra`] admits: one call per `emission_interval`, with up to
|
|
21
|
+
/// `delay_tolerance` of calls ahead of schedule allowed as a burst.
|
|
22
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
23
|
+
pub struct GcraPolicy {
|
|
24
|
+
emission_interval: Duration,
|
|
25
|
+
delay_tolerance: Duration,
|
|
26
|
+
/// `delay_tolerance + emission_interval`: how far ahead of `now` the TAT
|
|
27
|
+
/// may run after an admission.
|
|
28
|
+
ceiling: Duration,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
impl GcraPolicy {
|
|
32
|
+
/// `None` for a zero `emission_interval`, which would admit without
|
|
33
|
+
/// bound, and for a burst the gate could not count exactly: a burst
|
|
34
|
+
/// ceiling (`delay_tolerance + emission_interval`) past `Duration::MAX`,
|
|
35
|
+
/// or one holding more than `u64::MAX` emission intervals.
|
|
36
|
+
///
|
|
37
|
+
/// ```
|
|
38
|
+
/// use core::time::Duration;
|
|
39
|
+
/// use throttle_machines::GcraPolicy;
|
|
40
|
+
///
|
|
41
|
+
/// assert!(GcraPolicy::new(Duration::from_millis(100), Duration::ZERO).is_some());
|
|
42
|
+
/// assert!(GcraPolicy::new(Duration::ZERO, Duration::ZERO).is_none());
|
|
43
|
+
/// assert!(GcraPolicy::new(Duration::MAX, Duration::from_nanos(1)).is_none());
|
|
44
|
+
/// assert!(GcraPolicy::new(Duration::from_nanos(1), Duration::from_nanos(u64::MAX)).is_none());
|
|
45
|
+
/// ```
|
|
46
|
+
#[must_use]
|
|
47
|
+
pub const fn new(emission_interval: Duration, delay_tolerance: Duration) -> Option<Self> {
|
|
48
|
+
if emission_interval.is_zero() {
|
|
49
|
+
return None;
|
|
50
|
+
}
|
|
51
|
+
let Some(ceiling) = delay_tolerance.checked_add(emission_interval) else {
|
|
52
|
+
return None;
|
|
53
|
+
};
|
|
54
|
+
// The capacity, the most a gate answers, must be a `u64`.
|
|
55
|
+
if ceiling.as_nanos() / emission_interval.as_nanos() > u64::MAX as u128 {
|
|
56
|
+
return None;
|
|
57
|
+
}
|
|
58
|
+
Some(Self {
|
|
59
|
+
emission_interval,
|
|
60
|
+
delay_tolerance,
|
|
61
|
+
ceiling,
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// `limit` calls per `period`, `burst` of them back to back from idle
|
|
66
|
+
/// (one means no burst). The interval is `period / limit` rounded up to
|
|
67
|
+
/// the nanosecond, so the rate never exceeds the one asked for. `None`
|
|
68
|
+
/// for a zero `period`, or a burst ceiling (`burst` intervals) past
|
|
69
|
+
/// `Duration::MAX`.
|
|
70
|
+
///
|
|
71
|
+
/// ```
|
|
72
|
+
/// use core::num::NonZeroU64;
|
|
73
|
+
/// use core::time::Duration;
|
|
74
|
+
/// use throttle_machines::GcraPolicy;
|
|
75
|
+
///
|
|
76
|
+
/// let ten = NonZeroU64::new(10).unwrap();
|
|
77
|
+
/// let policy = GcraPolicy::per(Duration::from_secs(1), ten, NonZeroU64::new(3).unwrap()).unwrap();
|
|
78
|
+
/// assert_eq!(policy.emission_interval(), Duration::from_millis(100));
|
|
79
|
+
/// assert_eq!(policy.delay_tolerance(), Duration::from_millis(200));
|
|
80
|
+
/// ```
|
|
81
|
+
#[must_use]
|
|
82
|
+
pub fn per(period: Duration, limit: NonZeroU64, burst: NonZeroU64) -> Option<Self> {
|
|
83
|
+
let emission_interval = share(period, limit)?;
|
|
84
|
+
let delay_tolerance = times(emission_interval, u128::from(burst.get() - 1))?;
|
|
85
|
+
Self::new(emission_interval, delay_tolerance)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// The span one admission pushes the TAT on.
|
|
89
|
+
#[must_use]
|
|
90
|
+
pub const fn emission_interval(&self) -> Duration {
|
|
91
|
+
self.emission_interval
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// How far ahead of `now` the TAT may be while calls are still admitted.
|
|
95
|
+
#[must_use]
|
|
96
|
+
pub const fn delay_tolerance(&self) -> Duration {
|
|
97
|
+
self.delay_tolerance
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// Calls the tolerance admits for a TAT running `ahead` of `now`: how
|
|
101
|
+
/// far below the burst ceiling it sits, in emission intervals. At most
|
|
102
|
+
/// the capacity, which `new` proved fits a `u64`.
|
|
103
|
+
fn room(&self, ahead: Duration) -> u128 {
|
|
104
|
+
fits(self.ceiling.saturating_sub(ahead), self.emission_interval)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// A GCRA limiter: a [`GcraPolicy`] and the TAT it has reached.
|
|
109
|
+
///
|
|
110
|
+
/// ```
|
|
111
|
+
/// use core::time::Duration;
|
|
112
|
+
/// use throttle_machines::{Gate, Gcra, GcraPolicy, Refusal};
|
|
113
|
+
///
|
|
114
|
+
/// let policy = GcraPolicy::new(Duration::from_secs(1), Duration::ZERO).unwrap();
|
|
115
|
+
/// let mut gcra = Gcra::new(policy);
|
|
116
|
+
/// let now = Duration::from_secs(10);
|
|
117
|
+
/// assert_eq!(gcra.check(now), Ok(0));
|
|
118
|
+
/// assert_eq!(gcra.check(now), Err(Refusal::Throttled));
|
|
119
|
+
/// assert_eq!(gcra.retry_after(now), Duration::from_secs(1));
|
|
120
|
+
/// ```
|
|
121
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
122
|
+
pub struct Gcra {
|
|
123
|
+
policy: GcraPolicy,
|
|
124
|
+
tat: Duration,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
impl Gcra {
|
|
128
|
+
/// A limiter that has admitted nothing: its TAT is the epoch.
|
|
129
|
+
#[must_use]
|
|
130
|
+
pub const fn new(policy: GcraPolicy) -> Self {
|
|
131
|
+
Self {
|
|
132
|
+
policy,
|
|
133
|
+
tat: Duration::ZERO,
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// A limiter resumed at a TAT read from [`tat`](Self::tat), for a caller
|
|
138
|
+
/// that keeps the state elsewhere between calls. Every TAT is valid: one
|
|
139
|
+
/// at or before `now` means fully recovered.
|
|
140
|
+
#[must_use]
|
|
141
|
+
pub const fn restored(policy: GcraPolicy, tat: Duration) -> Self {
|
|
142
|
+
Self { policy, tat }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// The policy this limiter admits by.
|
|
146
|
+
#[must_use]
|
|
147
|
+
pub const fn policy(&self) -> GcraPolicy {
|
|
148
|
+
self.policy
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// The theoretical arrival time of the next call on schedule.
|
|
152
|
+
#[must_use]
|
|
153
|
+
pub const fn tat(&self) -> Duration {
|
|
154
|
+
self.tat
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// What `check` answers at `now`: the calls admitted, at least one, and
|
|
158
|
+
/// the TAT one admission leaves.
|
|
159
|
+
fn decide(&self, now: Duration) -> Result<(u64, Duration), Refusal> {
|
|
160
|
+
let interval = self.policy.emission_interval;
|
|
161
|
+
let ahead = self.tat.saturating_sub(now);
|
|
162
|
+
if ahead > self.policy.delay_tolerance {
|
|
163
|
+
return Err(Refusal::Throttled);
|
|
164
|
+
}
|
|
165
|
+
let next = self
|
|
166
|
+
.tat
|
|
167
|
+
.max(now)
|
|
168
|
+
.checked_add(interval)
|
|
169
|
+
.ok_or(Refusal::Overflow)?;
|
|
170
|
+
// Admissions whose TAT still fits: `next`, then one interval on for
|
|
171
|
+
// each whole interval left before `Duration::MAX`.
|
|
172
|
+
let fit = fits(Duration::MAX.saturating_sub(next), interval).saturating_add(1);
|
|
173
|
+
// Within tolerance, the room is at least one interval and at most
|
|
174
|
+
// the capacity, a `u64`.
|
|
175
|
+
Ok((count(self.policy.room(ahead).min(fit)), next))
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
impl Gate for Gcra {
|
|
180
|
+
fn check(&mut self, now: Duration) -> Result<u64, Refusal> {
|
|
181
|
+
let (admits, next) = self.decide(now)?;
|
|
182
|
+
self.tat = next;
|
|
183
|
+
// `decide` answers at least one, and this admission spends exactly
|
|
184
|
+
// one: the TAT and the room both move one interval.
|
|
185
|
+
Ok(admits - 1)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
fn peek(&self, now: Duration) -> Result<u64, Refusal> {
|
|
189
|
+
self.decide(now).map(|(admits, _)| admits)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// `Duration::MAX` when the next admission's TAT cannot fit a
|
|
193
|
+
/// `Duration`, at any later instant.
|
|
194
|
+
fn retry_after(&self, now: Duration) -> Duration {
|
|
195
|
+
let wait = self
|
|
196
|
+
.tat
|
|
197
|
+
.saturating_sub(now)
|
|
198
|
+
.saturating_sub(self.policy.delay_tolerance);
|
|
199
|
+
// `now + wait` is at most the TAT, so it fits.
|
|
200
|
+
let at = now.saturating_add(wait);
|
|
201
|
+
if self
|
|
202
|
+
.tat
|
|
203
|
+
.max(at)
|
|
204
|
+
.checked_add(self.policy.emission_interval)
|
|
205
|
+
.is_none()
|
|
206
|
+
{
|
|
207
|
+
return Duration::MAX;
|
|
208
|
+
}
|
|
209
|
+
wait
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// Pulls the TAT back one emission interval, never before the epoch.
|
|
213
|
+
fn refund(&mut self) {
|
|
214
|
+
self.tat = self.tat.saturating_sub(self.policy.emission_interval);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#[cfg(test)]
|
|
219
|
+
mod tests;
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
//! Keyed GCRA: one TAT per key in a sharded, mutex-guarded map.
|
|
2
|
+
//!
|
|
3
|
+
//! A TAT at or before `now` is equivalent to no entry (the key has fully
|
|
4
|
+
//! recovered), which is what eviction relies on. The caller supplies `now`,
|
|
5
|
+
//! the same epoch for every call on one limiter; threads racing on one shard
|
|
6
|
+
//! may present slightly out-of-order instants, which GCRA answers no more
|
|
7
|
+
//! generously than in order.
|
|
8
|
+
|
|
9
|
+
use std::borrow::{Borrow, ToOwned};
|
|
10
|
+
use std::boxed::Box;
|
|
11
|
+
use std::collections::HashMap;
|
|
12
|
+
use std::hash::{BuildHasher, Hash, RandomState};
|
|
13
|
+
use std::num::NonZeroUsize;
|
|
14
|
+
use std::sync::{Mutex, MutexGuard, PoisonError};
|
|
15
|
+
use std::time::Duration;
|
|
16
|
+
use std::vec::Vec;
|
|
17
|
+
|
|
18
|
+
use crate::{Gate, Gcra, GcraPolicy, Refusal};
|
|
19
|
+
|
|
20
|
+
const DEFAULT_SHARDS: NonZeroUsize = NonZeroUsize::MIN.saturating_add(15);
|
|
21
|
+
const DEFAULT_MAX_KEYS_PER_SHARD: NonZeroUsize = NonZeroUsize::MIN.saturating_add(4095);
|
|
22
|
+
/// Start sweeping a shard of recovered keys at this many entries.
|
|
23
|
+
const DEFAULT_EVICT_AT: usize = 4096;
|
|
24
|
+
/// An automatic sweep waits until this fraction of the shard could have
|
|
25
|
+
/// recovered, so each one reclaims a batch instead of rescanning for one key.
|
|
26
|
+
const SWEEP_BATCH: usize = 8;
|
|
27
|
+
|
|
28
|
+
#[derive(Debug)]
|
|
29
|
+
struct Shard<K> {
|
|
30
|
+
tats: HashMap<K, Duration>,
|
|
31
|
+
// When the next automatic sweep may run; `None` runs it at once.
|
|
32
|
+
next_sweep: Option<Duration>,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
impl<K> Shard<K> {
|
|
36
|
+
fn sweep_open(&self, now: Duration) -> bool {
|
|
37
|
+
self.next_sweep.is_none_or(|deadline| deadline <= now)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Reclaim recovered keys, unless too few could have recovered yet.
|
|
41
|
+
fn sweep_due(&mut self, now: Duration) {
|
|
42
|
+
if self.sweep_open(now) {
|
|
43
|
+
self.sweep(now);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Whether [`sweep_due`](Self::sweep_due) at `now` would free a slot.
|
|
48
|
+
fn reclaimable(&self, now: Duration) -> bool {
|
|
49
|
+
self.sweep_open(now) && self.tats.values().any(|tat| *tat <= now)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// Reclaim every recovered key and schedule the next automatic sweep
|
|
53
|
+
/// for when an eighth of those left could have recovered.
|
|
54
|
+
fn sweep(&mut self, now: Duration) {
|
|
55
|
+
self.tats.retain(|_, tat| *tat > now);
|
|
56
|
+
let mut tats: Vec<Duration> = self.tats.values().copied().collect();
|
|
57
|
+
self.next_sweep = (!tats.is_empty()).then(|| {
|
|
58
|
+
// 1 <= batch <= len for a non-empty set, so `batch - 1` is in bounds.
|
|
59
|
+
let batch = (tats.len() / SWEEP_BATCH).max(1);
|
|
60
|
+
*tats.select_nth_unstable(batch - 1).1
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// What a key finds in its shard, for the queries.
|
|
66
|
+
enum Seen {
|
|
67
|
+
/// The key is tracked at this TAT.
|
|
68
|
+
Tracked(Duration),
|
|
69
|
+
/// The key is untracked and `check` would refuse it as full; the shard's
|
|
70
|
+
/// next sweep, if one is scheduled.
|
|
71
|
+
Full(Option<Duration>),
|
|
72
|
+
/// The key is untracked and would be admitted from a fresh TAT.
|
|
73
|
+
Room,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// A GCRA limiter that keeps per-key state itself.
|
|
77
|
+
///
|
|
78
|
+
/// Every key is limited by one [`GcraPolicy`]. A refused call leaves every
|
|
79
|
+
/// key's TAT as it was; a [`Refusal::Full`] may still reschedule the shard's
|
|
80
|
+
/// next sweep, which is bookkeeping, not limiter state.
|
|
81
|
+
///
|
|
82
|
+
/// ```
|
|
83
|
+
/// use core::num::NonZeroU64;
|
|
84
|
+
/// use std::time::Duration;
|
|
85
|
+
/// use throttle_machines::{GcraPolicy, KeyedGcra, Refusal};
|
|
86
|
+
///
|
|
87
|
+
/// let one = NonZeroU64::MIN;
|
|
88
|
+
/// let policy = GcraPolicy::per(Duration::from_secs(1), one, one).unwrap();
|
|
89
|
+
/// let limiter = KeyedGcra::<String>::new(policy);
|
|
90
|
+
/// let now = Duration::from_secs(3);
|
|
91
|
+
/// assert_eq!(limiter.check("alice", now), Ok(0));
|
|
92
|
+
/// assert_eq!(limiter.check("alice", now), Err(Refusal::Throttled));
|
|
93
|
+
/// assert_eq!(limiter.check("bob", now), Ok(0));
|
|
94
|
+
/// ```
|
|
95
|
+
#[derive(Debug)]
|
|
96
|
+
pub struct KeyedGcra<K, S = RandomState> {
|
|
97
|
+
policy: GcraPolicy,
|
|
98
|
+
shards: Box<[Mutex<Shard<K>>]>,
|
|
99
|
+
hasher: S,
|
|
100
|
+
evict_at: usize,
|
|
101
|
+
max_keys_per_shard: NonZeroUsize,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
impl<K: Hash + Eq> KeyedGcra<K> {
|
|
105
|
+
/// A limiter with 16 shards of up to 4096 keys and a randomly seeded
|
|
106
|
+
/// hasher.
|
|
107
|
+
#[must_use]
|
|
108
|
+
pub fn new(policy: GcraPolicy) -> Self {
|
|
109
|
+
Self::with_hasher(
|
|
110
|
+
policy,
|
|
111
|
+
DEFAULT_SHARDS,
|
|
112
|
+
DEFAULT_MAX_KEYS_PER_SHARD,
|
|
113
|
+
RandomState::new(),
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
impl<K: Hash + Eq, S: BuildHasher> KeyedGcra<K, S> {
|
|
119
|
+
/// A limiter with `shards` independently locked maps of up to
|
|
120
|
+
/// `max_keys_per_shard` keys each, hashed by `hasher`.
|
|
121
|
+
///
|
|
122
|
+
/// Recovered keys are reclaimed first, in batches: a full shard sweeps
|
|
123
|
+
/// once an eighth of it could have recovered, and refuses unknown keys
|
|
124
|
+
/// with [`Refusal::Full`] until then without allocating; tracked keys
|
|
125
|
+
/// keep their limits. Unused capacity in another shard is not borrowed.
|
|
126
|
+
#[must_use]
|
|
127
|
+
pub fn with_hasher(
|
|
128
|
+
policy: GcraPolicy,
|
|
129
|
+
shards: NonZeroUsize,
|
|
130
|
+
max_keys_per_shard: NonZeroUsize,
|
|
131
|
+
hasher: S,
|
|
132
|
+
) -> Self {
|
|
133
|
+
Self {
|
|
134
|
+
policy,
|
|
135
|
+
shards: (0..shards.get())
|
|
136
|
+
.map(|_| {
|
|
137
|
+
Mutex::new(Shard {
|
|
138
|
+
tats: HashMap::new(),
|
|
139
|
+
next_sweep: None,
|
|
140
|
+
})
|
|
141
|
+
})
|
|
142
|
+
.collect(),
|
|
143
|
+
hasher,
|
|
144
|
+
evict_at: DEFAULT_EVICT_AT,
|
|
145
|
+
max_keys_per_shard,
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// Sweep recovered keys after an admission leaves a shard with at least
|
|
150
|
+
/// `evict_at` entries (default 4096). A cleanup trigger, not a cap.
|
|
151
|
+
/// Sweeps are skipped until an eighth of the shard could have recovered.
|
|
152
|
+
#[must_use]
|
|
153
|
+
pub const fn evict_at(mut self, evict_at: usize) -> Self {
|
|
154
|
+
self.evict_at = evict_at;
|
|
155
|
+
self
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/// The policy every key is limited by.
|
|
159
|
+
#[must_use]
|
|
160
|
+
pub const fn policy(&self) -> GcraPolicy {
|
|
161
|
+
self.policy
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// Admit one call for `key` at `now`. Honoured: how many more calls the
|
|
165
|
+
/// key would be admitted at the same instant.
|
|
166
|
+
///
|
|
167
|
+
/// # Errors
|
|
168
|
+
///
|
|
169
|
+
/// [`Refusal::Throttled`] when the key's limit is spent at `now`;
|
|
170
|
+
/// [`Refusal::Overflow`] when admitting would push its TAT past
|
|
171
|
+
/// `Duration::MAX`; [`Refusal::Full`] when the key is untracked and its
|
|
172
|
+
/// shard is full of keys that have not recovered.
|
|
173
|
+
pub fn check<Q>(&self, key: &Q, now: Duration) -> Result<u64, Refusal>
|
|
174
|
+
where
|
|
175
|
+
K: Borrow<Q>,
|
|
176
|
+
Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
|
|
177
|
+
{
|
|
178
|
+
let mut shard = self.shard(key);
|
|
179
|
+
let left = if let Some(tat) = shard.tats.get_mut(key) {
|
|
180
|
+
let mut gcra = Gcra::restored(self.policy, *tat);
|
|
181
|
+
let left = gcra.check(now)?;
|
|
182
|
+
*tat = gcra.tat();
|
|
183
|
+
left
|
|
184
|
+
} else {
|
|
185
|
+
if shard.tats.len() >= self.max_keys_per_shard.get() {
|
|
186
|
+
// Frees a slot exactly when a key has recovered; otherwise
|
|
187
|
+
// it only reschedules the next sweep.
|
|
188
|
+
shard.sweep_due(now);
|
|
189
|
+
if shard.tats.len() >= self.max_keys_per_shard.get() {
|
|
190
|
+
return Err(Refusal::Full);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
let mut gcra = Gcra::new(self.policy);
|
|
194
|
+
let left = gcra.check(now)?;
|
|
195
|
+
shard.tats.insert(key.to_owned(), gcra.tat());
|
|
196
|
+
left
|
|
197
|
+
};
|
|
198
|
+
if shard.tats.len() >= self.evict_at {
|
|
199
|
+
shard.sweep_due(now);
|
|
200
|
+
}
|
|
201
|
+
drop(shard);
|
|
202
|
+
Ok(left)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// How many calls [`check`](Self::check) would admit `key` at `now`, at
|
|
206
|
+
/// least one, without consuming or reclaiming anything.
|
|
207
|
+
///
|
|
208
|
+
/// # Errors
|
|
209
|
+
///
|
|
210
|
+
/// The refusal `check` would answer at `now`.
|
|
211
|
+
pub fn peek<Q>(&self, key: &Q, now: Duration) -> Result<u64, Refusal>
|
|
212
|
+
where
|
|
213
|
+
K: Borrow<Q>,
|
|
214
|
+
Q: Hash + Eq + ?Sized,
|
|
215
|
+
{
|
|
216
|
+
match self.seen(key, now) {
|
|
217
|
+
Seen::Tracked(tat) => Gcra::restored(self.policy, tat).peek(now),
|
|
218
|
+
Seen::Full(_) => Err(Refusal::Full),
|
|
219
|
+
Seen::Room => Gcra::new(self.policy).peek(now),
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// How long after `now` `key` is admitted: zero when it is admitted at
|
|
224
|
+
/// `now`. For an untracked key refused as full, the wait until its shard
|
|
225
|
+
/// next sweeps, a hint rather than a promise of a free slot.
|
|
226
|
+
pub fn retry_after<Q>(&self, key: &Q, now: Duration) -> Duration
|
|
227
|
+
where
|
|
228
|
+
K: Borrow<Q>,
|
|
229
|
+
Q: Hash + Eq + ?Sized,
|
|
230
|
+
{
|
|
231
|
+
match self.seen(key, now) {
|
|
232
|
+
Seen::Tracked(tat) => Gcra::restored(self.policy, tat).retry_after(now),
|
|
233
|
+
Seen::Full(next_sweep) => {
|
|
234
|
+
next_sweep.map_or(Duration::ZERO, |deadline| deadline.saturating_sub(now))
|
|
235
|
+
}
|
|
236
|
+
Seen::Room => Gcra::new(self.policy).retry_after(now),
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/// Give back one admission [`check`](Self::check) granted `key`, as if
|
|
241
|
+
/// it had been refused: for admitting a call only when every limiter it
|
|
242
|
+
/// spends admits it. A key left fully recovered at `now` is dropped,
|
|
243
|
+
/// freeing its slot; an untracked key has nothing to give back.
|
|
244
|
+
pub fn refund<Q>(&self, key: &Q, now: Duration)
|
|
245
|
+
where
|
|
246
|
+
K: Borrow<Q>,
|
|
247
|
+
Q: Hash + Eq + ?Sized,
|
|
248
|
+
{
|
|
249
|
+
let mut shard = self.shard(key);
|
|
250
|
+
let Some(tat) = shard.tats.get_mut(key) else {
|
|
251
|
+
return;
|
|
252
|
+
};
|
|
253
|
+
let mut gcra = Gcra::restored(self.policy, *tat);
|
|
254
|
+
gcra.refund();
|
|
255
|
+
*tat = gcra.tat();
|
|
256
|
+
if *tat <= now {
|
|
257
|
+
shard.tats.remove(key);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/// Drop every key that has fully recovered at `now`; answers how many.
|
|
262
|
+
pub fn evict(&self, now: Duration) -> usize {
|
|
263
|
+
self.shards
|
|
264
|
+
.iter()
|
|
265
|
+
.map(|shard| {
|
|
266
|
+
let mut shard = lock(shard);
|
|
267
|
+
let before = shard.tats.len();
|
|
268
|
+
shard.sweep(now);
|
|
269
|
+
// A sweep only removes keys.
|
|
270
|
+
before - shard.tats.len()
|
|
271
|
+
})
|
|
272
|
+
.sum()
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// Keys currently tracked, including recovered ones not yet evicted.
|
|
276
|
+
pub fn len(&self) -> usize {
|
|
277
|
+
self.shards.iter().map(|shard| lock(shard).tats.len()).sum()
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/// Whether no key is tracked.
|
|
281
|
+
pub fn is_empty(&self) -> bool {
|
|
282
|
+
self.shards.iter().all(|shard| lock(shard).tats.is_empty())
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// What `key` finds in its shard at `now`, read under one short lock.
|
|
286
|
+
fn seen<Q>(&self, key: &Q, now: Duration) -> Seen
|
|
287
|
+
where
|
|
288
|
+
K: Borrow<Q>,
|
|
289
|
+
Q: Hash + Eq + ?Sized,
|
|
290
|
+
{
|
|
291
|
+
let shard = self.shard(key);
|
|
292
|
+
let seen = match shard.tats.get(key) {
|
|
293
|
+
Some(tat) => Seen::Tracked(*tat),
|
|
294
|
+
None if shard.tats.len() >= self.max_keys_per_shard.get()
|
|
295
|
+
&& !shard.reclaimable(now) =>
|
|
296
|
+
{
|
|
297
|
+
Seen::Full(shard.next_sweep)
|
|
298
|
+
}
|
|
299
|
+
None => Seen::Room,
|
|
300
|
+
};
|
|
301
|
+
drop(shard);
|
|
302
|
+
seen
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
fn shard<Q: Hash + ?Sized>(&self, key: &Q) -> MutexGuard<'_, Shard<K>> {
|
|
306
|
+
// Built from a `NonZeroUsize`, so `count` is never zero.
|
|
307
|
+
let count = self.shards.len() as u64;
|
|
308
|
+
// Reduced modulo the shard count, so the index fits a usize.
|
|
309
|
+
let index = usize::try_from(self.hasher.hash_one(key) % count).unwrap_or(0);
|
|
310
|
+
#[allow(
|
|
311
|
+
clippy::indexing_slicing,
|
|
312
|
+
reason = "index < count = shards.len(): reduced modulo the length just above"
|
|
313
|
+
)]
|
|
314
|
+
let shard = &self.shards[index];
|
|
315
|
+
lock(shard)
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/// TATs are plain durations, so a poisoned shard is still consistent.
|
|
320
|
+
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
|
321
|
+
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
#[cfg(test)]
|
|
325
|
+
mod tests;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
//! Rate limiting on a caller-supplied clock: GCRA, token bucket and fixed
|
|
2
|
+
//! window, each a small `Copy` value behind the shared [`Gate`] contract.
|
|
3
|
+
//!
|
|
4
|
+
//! The crate is `no_std` and allocation-free; it reads no clock. `now` is a
|
|
5
|
+
//! [`Duration`](core::time::Duration) since an epoch the caller picks, and so
|
|
6
|
+
//! is every span. A refused call answers [`Refusal`] and changes nothing.
|
|
7
|
+
//!
|
|
8
|
+
//! The `std` feature adds [`KeyedGcra`], which keeps per-key GCRA state in a
|
|
9
|
+
//! sharded, mutex-guarded map.
|
|
10
|
+
//!
|
|
11
|
+
//! ```
|
|
12
|
+
//! use core::num::NonZeroU64;
|
|
13
|
+
//! use core::time::Duration;
|
|
14
|
+
//! use throttle_machines::{Gate, Gcra, GcraPolicy, Refusal};
|
|
15
|
+
//!
|
|
16
|
+
//! let policy = GcraPolicy::per(Duration::from_secs(1), NonZeroU64::new(2).unwrap(), NonZeroU64::MIN)
|
|
17
|
+
//! .unwrap();
|
|
18
|
+
//! let mut gcra = Gcra::new(policy);
|
|
19
|
+
//! let now = Duration::from_secs(100);
|
|
20
|
+
//! assert_eq!(gcra.check(now), Ok(0));
|
|
21
|
+
//! assert_eq!(gcra.check(now), Err(Refusal::Throttled));
|
|
22
|
+
//! assert_eq!(gcra.retry_after(now), Duration::from_millis(500));
|
|
23
|
+
//! ```
|
|
24
|
+
|
|
25
|
+
#![no_std]
|
|
26
|
+
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
|
27
|
+
|
|
28
|
+
#[cfg(feature = "std")]
|
|
29
|
+
extern crate std;
|
|
30
|
+
|
|
31
|
+
mod fixed_window;
|
|
32
|
+
mod gate;
|
|
33
|
+
mod gcra;
|
|
34
|
+
#[cfg(feature = "std")]
|
|
35
|
+
mod keyed;
|
|
36
|
+
mod refusal;
|
|
37
|
+
mod token_bucket;
|
|
38
|
+
|
|
39
|
+
/// Compiles and runs the README's examples as doctests.
|
|
40
|
+
#[cfg(doctest)]
|
|
41
|
+
#[doc = include_str!("../README.md")]
|
|
42
|
+
struct ReadmeDoctests;
|
|
43
|
+
|
|
44
|
+
pub use fixed_window::{FixedWindow, FixedWindowPolicy};
|
|
45
|
+
pub use gate::Gate;
|
|
46
|
+
pub use gcra::{Gcra, GcraPolicy};
|
|
47
|
+
#[cfg(feature = "std")]
|
|
48
|
+
pub use keyed::KeyedGcra;
|
|
49
|
+
pub use refusal::Refusal;
|
|
50
|
+
pub use token_bucket::{TokenBucket, TokenBucketPolicy};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
use core::fmt;
|
|
2
|
+
|
|
3
|
+
/// Why a call was not honoured. A refused call changed nothing: not a TAT,
|
|
4
|
+
/// not a token, not a count, not a tracked key.
|
|
5
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
6
|
+
pub enum Refusal {
|
|
7
|
+
/// The limit is spent at the instant supplied; `retry_after` says how
|
|
8
|
+
/// long until the next admission. It is an answer about that instant, not
|
|
9
|
+
/// a recorded fact: the same call at another instant may be honoured.
|
|
10
|
+
Throttled,
|
|
11
|
+
/// Only [`KeyedGcra`](crate::KeyedGcra) answers it: the key is not
|
|
12
|
+
/// tracked, its shard holds as many keys as it may, and none of them has
|
|
13
|
+
/// recovered yet.
|
|
14
|
+
Full,
|
|
15
|
+
/// Only GCRA answers it: admitting the call would push the TAT past
|
|
16
|
+
/// `Duration::MAX`. No later instant lifts it: the TAT only advances.
|
|
17
|
+
Overflow,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
impl fmt::Display for Refusal {
|
|
21
|
+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
22
|
+
formatter.write_str(match self {
|
|
23
|
+
Self::Throttled => "the limit is spent at this instant",
|
|
24
|
+
Self::Full => "the shard tracks as many keys as it may",
|
|
25
|
+
Self::Overflow => "the TAT would pass Duration::MAX",
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
impl core::error::Error for Refusal {}
|