1use std::collections::BTreeMap;
9use std::time::{Duration, Instant};
10
11const CREDIT_SCALE: u128 = 1_000_000_000;
12const MAX_PEERS: usize = 32;
13const MAX_ID_BYTES: usize = 128;
14const MAX_RATE: u32 = 100_000;
15
16#[derive(Debug, Clone, Copy)]
17pub struct RelayQuota {
18 pub requests_per_second: u32,
19 pub burst: u32,
20}
21
22impl RelayQuota {
23 fn valid(self) -> bool {
24 (1..=MAX_RATE).contains(&self.requests_per_second) && (1..=MAX_RATE).contains(&self.burst)
25 }
26}
27
28#[derive(Debug, Clone, Copy)]
29pub struct RelayQuotaConfig {
30 pub peer: RelayQuota,
31 pub tenant: RelayQuota,
32 pub project: RelayQuota,
33}
34
35impl Default for RelayQuotaConfig {
36 fn default() -> Self {
37 Self {
38 peer: RelayQuota {
39 requests_per_second: 20,
40 burst: 40,
41 },
42 tenant: RelayQuota {
43 requests_per_second: 40,
44 burst: 80,
45 },
46 project: RelayQuota {
47 requests_per_second: 30,
48 burst: 60,
49 },
50 }
51 }
52}
53
54impl RelayQuotaConfig {
55 pub fn validate(self) -> Result<(), &'static str> {
56 if [self.peer, self.tenant, self.project]
57 .into_iter()
58 .all(RelayQuota::valid)
59 {
60 Ok(())
61 } else {
62 Err("relay quota rates and bursts must be between 1 and 100000")
63 }
64 }
65}
66
67#[derive(Debug, Clone, Copy)]
68struct Bucket {
69 quota: RelayQuota,
70 credit: u128,
71 last: Instant,
72}
73
74impl Bucket {
75 fn new(quota: RelayQuota, now: Instant) -> Self {
76 Self {
77 quota,
78 credit: u128::from(quota.burst) * CREDIT_SCALE,
79 last: now,
80 }
81 }
82
83 fn refill(self, now: Instant) -> Self {
84 let added = now
85 .saturating_duration_since(self.last)
86 .as_nanos()
87 .saturating_mul(u128::from(self.quota.requests_per_second));
88 Self {
89 credit: self
90 .credit
91 .saturating_add(added)
92 .min(u128::from(self.quota.burst) * CREDIT_SCALE),
93 last: self.last.max(now),
94 ..self
95 }
96 }
97
98 fn retry_after(self) -> Duration {
99 let nanos = CREDIT_SCALE
100 .saturating_sub(self.credit)
101 .div_ceil(u128::from(self.quota.requests_per_second));
102 Duration::from_nanos(nanos.min(CREDIT_SCALE) as u64)
104 }
105
106 fn consume(mut self) -> Self {
107 self.credit -= CREDIT_SCALE;
108 self
109 }
110}
111
112#[derive(Debug, PartialEq, Eq)]
113pub(super) enum QuotaRejection {
114 UnknownPeer,
115 WrongScope,
116 Limited { retry_after: Duration },
117}
118
119#[derive(Debug)]
120pub(super) struct RelayQuotaState {
121 peers: BTreeMap<String, Bucket>,
122 tenant_id: String,
123 project_id: String,
124 tenant: Bucket,
125 project: Bucket,
126}
127
128impl RelayQuotaState {
129 pub(super) fn new(
130 config: RelayQuotaConfig,
131 peers: &[String],
132 tenant_id: &str,
133 project_id: &str,
134 now: Instant,
135 ) -> Result<Self, &'static str> {
136 config.validate()?;
137 let valid_id = |id: &str| !id.is_empty() && id.len() <= MAX_ID_BYTES;
138 if peers.is_empty()
139 || peers.len() > MAX_PEERS
140 || !valid_id(tenant_id)
141 || !valid_id(project_id)
142 || peers.iter().any(|id| !valid_id(id))
143 {
144 return Err("relay quota requires bounded configured peer and scope identities");
145 }
146 let buckets: BTreeMap<_, _> = peers
147 .iter()
148 .map(|peer| (peer.clone(), Bucket::new(config.peer, now)))
149 .collect();
150 if buckets.len() != peers.len() {
151 return Err("relay quota peer identities must be unique");
152 }
153 Ok(Self {
154 peers: buckets,
155 tenant_id: tenant_id.into(),
156 project_id: project_id.into(),
157 tenant: Bucket::new(config.tenant, now),
158 project: Bucket::new(config.project, now),
159 })
160 }
161
162 pub(super) fn check_at(
165 &mut self,
166 current_peer: &str,
167 origin_peer: &str,
168 tenant_id: &str,
169 project_id: &str,
170 now: Instant,
171 ) -> Result<(), QuotaRejection> {
172 if tenant_id != self.tenant_id || project_id != self.project_id {
173 return Err(QuotaRejection::WrongScope);
174 }
175 let current = self
176 .peers
177 .get(current_peer)
178 .ok_or(QuotaRejection::UnknownPeer)?
179 .refill(now);
180 let origin = self
181 .peers
182 .get(origin_peer)
183 .ok_or(QuotaRejection::UnknownPeer)?
184 .refill(now);
185 let tenant = self.tenant.refill(now);
186 let project = self.project.refill(now);
187 let retry_after = [current, origin, tenant, project]
188 .into_iter()
189 .map(Bucket::retry_after)
190 .max()
191 .unwrap_or_default();
192 if !retry_after.is_zero() {
193 return Err(QuotaRejection::Limited { retry_after });
194 }
195 if let Some(bucket) = self.peers.get_mut(current_peer) {
197 *bucket = current.consume();
198 }
199 if origin_peer != current_peer
200 && let Some(bucket) = self.peers.get_mut(origin_peer)
201 {
202 *bucket = origin.consume();
203 }
204 self.tenant = tenant.consume();
205 self.project = project.consume();
206 Ok(())
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 fn state(
215 peer_burst: u32,
216 tenant_burst: u32,
217 project_burst: u32,
218 now: Instant,
219 ) -> RelayQuotaState {
220 RelayQuotaState::new(
221 RelayQuotaConfig {
222 peer: RelayQuota {
223 requests_per_second: 1,
224 burst: peer_burst,
225 },
226 tenant: RelayQuota {
227 requests_per_second: 1,
228 burst: tenant_burst,
229 },
230 project: RelayQuota {
231 requests_per_second: 1,
232 burst: project_burst,
233 },
234 },
235 &["a".into(), "b".into(), "c".into()],
236 "tenant",
237 "project",
238 now,
239 )
240 .unwrap()
241 }
242
243 #[test]
244 fn same_peer_is_debited_once_and_refills_without_sleep() {
245 let now = Instant::now();
246 let mut quotas = state(2, 10, 10, now);
247 for _ in 0..2 {
248 assert_eq!(quotas.check_at("a", "a", "tenant", "project", now), Ok(()));
249 }
250 assert_eq!(
251 quotas.check_at("a", "a", "tenant", "project", now),
252 Err(QuotaRejection::Limited {
253 retry_after: Duration::from_secs(1)
254 })
255 );
256 assert_eq!(
257 quotas.check_at(
258 "a",
259 "a",
260 "tenant",
261 "project",
262 now + Duration::from_millis(750)
263 ),
264 Err(QuotaRejection::Limited {
265 retry_after: Duration::from_millis(250)
266 })
267 );
268 assert_eq!(
269 quotas.check_at("a", "a", "tenant", "project", now + Duration::from_secs(1)),
270 Ok(())
271 );
272 }
273
274 #[test]
275 fn origin_limit_survives_changing_forwarder_without_charging_other_buckets() {
276 let now = Instant::now();
277 let mut quotas = state(1, 10, 10, now);
278 assert_eq!(quotas.check_at("a", "a", "tenant", "project", now), Ok(()));
279 let tenant_credit = quotas.tenant.credit;
280 assert!(matches!(
281 quotas.check_at("b", "a", "tenant", "project", now),
282 Err(QuotaRejection::Limited { .. })
283 ));
284 assert_eq!(quotas.tenant.credit, tenant_credit);
285 assert_eq!(quotas.check_at("b", "c", "tenant", "project", now), Ok(()));
286 }
287
288 #[test]
289 fn tenant_and_project_limits_are_atomic_and_independent() {
290 let now = Instant::now();
291 for (tenant, project) in [(1, 10), (10, 1)] {
292 let mut quotas = state(10, tenant, project, now);
293 assert_eq!(quotas.check_at("a", "a", "tenant", "project", now), Ok(()));
294 let before = quotas.peers["b"].credit;
295 assert!(matches!(
296 quotas.check_at("b", "b", "tenant", "project", now),
297 Err(QuotaRejection::Limited { .. })
298 ));
299 assert_eq!(quotas.peers["b"].credit, before);
300 }
301 }
302
303 #[test]
304 fn untrusted_keys_never_allocate_or_debit() {
305 let now = Instant::now();
306 let mut quotas = state(1, 1, 1, now);
307 for i in 0..100 {
308 assert_eq!(
309 quotas.check_at(&format!("unknown-{i}"), "a", "tenant", "project", now),
310 Err(QuotaRejection::UnknownPeer)
311 );
312 }
313 assert_eq!(
314 quotas.check_at("a", "a", "other", "project", now),
315 Err(QuotaRejection::WrongScope)
316 );
317 assert_eq!(quotas.peers.len(), 3);
318 assert_eq!(quotas.check_at("a", "a", "tenant", "project", now), Ok(()));
319 }
320
321 #[test]
322 fn invalid_configuration_fails_closed() {
323 let now = Instant::now();
324 for count in [0, MAX_PEERS + 1] {
325 let peers = (0..count).map(|i| format!("peer-{i}")).collect::<Vec<_>>();
326 assert!(
327 RelayQuotaState::new(RelayQuotaConfig::default(), &peers, "t", "p", now).is_err()
328 );
329 }
330 assert!(
331 RelayQuotaState::new(
332 RelayQuotaConfig::default(),
333 &["a".into(), "a".into()],
334 "t",
335 "p",
336 now
337 )
338 .is_err()
339 );
340 for bad in [0, MAX_RATE + 1] {
341 let mut cfg = RelayQuotaConfig::default();
342 cfg.peer.requests_per_second = bad;
343 assert!(cfg.validate().is_err());
344 cfg = RelayQuotaConfig::default();
345 cfg.project.burst = bad;
346 assert!(cfg.validate().is_err());
347 }
348 }
349
350 #[test]
351 fn reversed_time_does_not_create_credit() {
352 let now = Instant::now();
353 let mut quotas = state(1, 1, 1, now);
354 assert_eq!(quotas.check_at("a", "a", "tenant", "project", now), Ok(()));
355 assert!(matches!(
356 quotas.check_at(
357 "a",
358 "a",
359 "tenant",
360 "project",
361 now.checked_sub(Duration::from_secs(1)).unwrap()
362 ),
363 Err(QuotaRejection::Limited { .. })
364 ));
365 assert!(matches!(
366 quotas.check_at("a", "a", "tenant", "project", now),
367 Err(QuotaRejection::Limited { .. })
368 ));
369 }
370}