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
use crate::lib::*;
use crate::nanos::Nanos;
use crate::{clock, NegativeMultiDecision, Quota};
pub(crate) struct Tat(AtomicU64);
impl Tat {
fn new(tat: Nanos) -> Tat {
Tat(AtomicU64::new(tat.into()))
}
fn measure_and_replace<T, F, E>(&self, f: F) -> Result<T, E>
where
F: Fn(Nanos) -> Result<(T, Nanos), E>,
{
let mut prev = self.0.load(Ordering::Acquire);
let mut decision = f(prev.into());
while let Ok((result, new_data)) = decision {
match self.0.compare_exchange_weak(
prev,
new_data.into(),
Ordering::Release,
Ordering::Relaxed,
) {
Ok(_) => return Ok(result),
Err(next_prev) => prev = next_prev,
}
decision = f(prev.into());
}
decision.map(|(result, _)| result)
}
}
impl Debug for Tat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
let d = Duration::from_nanos(self.0.load(Ordering::Relaxed));
write!(f, "Tat({:?})", d)
}
}
#[derive(Debug, PartialEq)]
pub struct NotUntil<'a, P: clock::Reference> {
limiter: &'a GCRA<P>,
tat: Nanos,
}
impl<'a, P: clock::Reference> NotUntil<'a, P> {
pub fn earliest_possible(&self) -> P {
let tat: Duration = self.tat.into();
self.limiter.start + tat
}
pub fn wait_time_from(&self, from: P) -> Duration {
let earliest = self.earliest_possible();
earliest.duration_since(earliest.min(from))
}
}
impl<'a, P: clock::Reference> fmt::Display for NotUntil<'a, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let tat: Duration = self.tat.into();
write!(f, "rate-limited until {:?}", self.limiter.start + tat)
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct GCRA<P: clock::Reference = <clock::DefaultClock as clock::Clock>::Instant> {
t: Nanos,
tau: Nanos,
start: P,
}
impl<P: clock::Reference> GCRA<P> {
pub(crate) fn new(start: P, quota: Quota) -> Self {
let tau: Nanos = quota.per.into();
let t: Nanos = (quota.per / quota.max_burst.get()).into();
GCRA { tau, t, start }
}
pub(crate) fn new_state(&self, now: P) -> Tat {
let tat = Nanos::from(now.duration_since(self.start)) + self.t;
Tat::new(tat)
}
pub(crate) fn test_and_update(&self, state: &Tat, t0: P) -> Result<(), NotUntil<P>> {
let t0: Nanos = t0.duration_since(self.start).into();
let tau = self.tau;
let t = self.t;
state.measure_and_replace(|tat| {
if t0 < tat.saturating_sub(tau) {
Err(NotUntil { limiter: self, tat })
} else {
Ok(((), cmp::max(tat, t0) + t))
}
})
}
pub(crate) fn test_n_all_and_update(
&self,
n: NonZeroU32,
state: &Tat,
t0: P,
) -> Result<(), NegativeMultiDecision<NotUntil<P>>> {
let t0: Nanos = t0.duration_since(self.start).into();
let tau = self.tau;
let t = self.t;
let weight = t * (n.get() - 1) as u64;
if weight > tau {
return Err(NegativeMultiDecision::InsufficientCapacity(
(tau.as_u64() / t.as_u64()) as u32,
));
}
state.measure_and_replace(|tat| {
if t0 < (tat + weight).saturating_sub(tau) {
Err(NegativeMultiDecision::BatchNonConforming(
n.get(),
NotUntil { limiter: self, tat },
))
} else {
Ok(((), cmp::max(tat, t0) + t + weight))
}
})
}
}