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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! Per-host rate governance for release registry traffic.
//!
//! [`HostLimiter`] keeps one token bucket and one `blocked_until` gate per
//! host. [`GovernedHttp`] wraps any [`RegistryHttp`] so every call (JSON, text,
//! HEAD, downloads, POST) takes a token before delegating. A 429, or a 403
//! that carries rate-limit headers, blocks the host for the delay implied by
//! `Retry-After` (seconds or HTTP date) or the reset header, plus jitter.
//!
//! State is persisted to `source_host_state` when a [`DbHandle`] is supplied;
//! without one the governor is in-memory only. Time comes from [`Time`], so
//! tests inject a fake clock instead of sleeping.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::Value;
use crate::db::DbHandle;
use crate::db::model::{SourceHostStateMark, SourceHostStateRow};
use crate::release::http::{HttpStatusError, RegistryHttp};
use crate::time::{RealTime, Time, utc_iso};
/// Token bucket plus backoff gate settings.
#[derive(Debug, Clone, Copy)]
pub struct HostLimiterConfig {
/// Sustained requests per second.
pub requests_per_second: f64,
/// Bucket capacity, also the largest immediate burst.
pub burst: u32,
/// Upper bound of the random delay added to every rate-limit block.
pub jitter_seconds: f64,
}
impl Default for HostLimiterConfig {
fn default() -> Self {
Self {
requests_per_second: 5.0,
burst: 5,
jitter_seconds: 0.25,
}
}
}
/// A host's persisted counters, as written to `source_host_state`.
#[derive(Debug, Clone, PartialEq)]
pub struct HostStateSnapshot {
pub window_start: f64,
pub requests: i64,
pub blocked_until: Option<String>,
}
#[derive(Debug, Clone)]
struct HostState {
tokens: f64,
last_refill: f64,
window_start: f64,
requests: i64,
blocked_until: Option<f64>,
}
impl HostState {
fn new(burst: u32, now: f64) -> Self {
Self {
tokens: burst as f64,
last_refill: now,
window_start: now,
requests: 0,
blocked_until: None,
}
}
}
/// Per-host token buckets and backoff gates. Clone the surrounding `Arc`, not
/// the limiter, so all callers share one bucket per host.
pub struct HostLimiter {
config: HostLimiterConfig,
time: Arc<dyn Time>,
hosts: Mutex<HashMap<String, HostState>>,
}
impl HostLimiter {
/// Production limiter: [`RealTime`] sleeps with `tokio::time`.
pub fn new(config: HostLimiterConfig) -> Self {
Self::with_clock(config, Arc::new(RealTime))
}
/// Limiter with an injectable clock. Tests pass a clock whose `sleep`
/// advances fake time instead of waiting.
pub fn with_clock(config: HostLimiterConfig, time: Arc<dyn Time>) -> Self {
let config = HostLimiterConfig {
requests_per_second: config.requests_per_second.max(0.001),
..config
};
Self {
config,
time,
hosts: Mutex::new(HashMap::new()),
}
}
pub fn now_unix(&self) -> f64 {
self.time.now_unix()
}
/// Take one token for `host`, sleeping while the bucket is empty or the
/// host is blocked.
pub async fn acquire(&self, host: &str) {
loop {
let wait = self.take_token(host);
if wait == 0.0 {
return;
}
self.time.sleep(Duration::from_secs_f64(wait)).await;
}
}
/// Block `host` for at least `delay`, adding the configured jitter. An
/// existing later block is never shortened.
pub fn block(&self, host: &str, delay: Duration) {
let now = self.time.now_unix();
let until = now + delay.as_secs_f64() + self.time.jitter(self.config.jitter_seconds);
let mut hosts = self.hosts.lock().expect("host limiter lock poisoned");
let state = hosts
.entry(host.to_owned())
.or_insert_with(|| HostState::new(self.config.burst, now));
state.blocked_until = Some(state.blocked_until.unwrap_or(0.0).max(until));
}
/// Remaining block, if `host` is currently blocked.
pub fn is_blocked(&self, host: &str) -> Option<Duration> {
let now = self.time.now_unix();
let hosts = self.hosts.lock().expect("host limiter lock poisoned");
let until = hosts.get(host)?.blocked_until?;
(until > now).then(|| Duration::from_secs_f64(until - now))
}
/// Counters to persist for `host`. An expired block is reported as `None`.
pub fn snapshot(&self, host: &str) -> HostStateSnapshot {
let now = self.time.now_unix();
let hosts = self.hosts.lock().expect("host limiter lock poisoned");
match hosts.get(host) {
Some(state) => HostStateSnapshot {
window_start: state.window_start,
requests: state.requests,
blocked_until: state
.blocked_until
.filter(|until| *until > now)
.map(utc_iso),
},
None => HostStateSnapshot {
window_start: now,
requests: 0,
blocked_until: None,
},
}
}
/// Restore persisted rows. Live blocks are kept; expired blocks are
/// dropped. Buckets start full because no token estimate is persisted.
pub fn load_rows(&self, rows: &[SourceHostStateRow]) {
let now = self.time.now_unix();
let mut hosts = self.hosts.lock().expect("host limiter lock poisoned");
for row in rows {
let blocked_until = row
.blocked_until
.as_deref()
.and_then(parse_blocked_until)
.filter(|until| *until > now);
hosts.insert(
row.host.clone(),
HostState {
tokens: self.config.burst as f64,
last_refill: now,
window_start: row.window_start,
requests: row.requests,
blocked_until,
},
);
}
}
/// Returns `0.0` when a token was taken, else the seconds to wait.
fn take_token(&self, host: &str) -> f64 {
let now = self.time.now_unix();
let mut hosts = self.hosts.lock().expect("host limiter lock poisoned");
let state = hosts
.entry(host.to_owned())
.or_insert_with(|| HostState::new(self.config.burst, now));
let elapsed = (now - state.last_refill).max(0.0);
state.tokens = (state.tokens + elapsed * self.config.requests_per_second)
.min(self.config.burst as f64);
state.last_refill = now;
if now - state.window_start >= 1.0 {
state.window_start = now;
state.requests = 0;
}
let blocked_for = state
.blocked_until
.map(|until| (until - now).max(0.0))
.unwrap_or(0.0);
if blocked_for == 0.0 && state.tokens >= 1.0 {
state.tokens -= 1.0;
state.requests += 1;
return 0.0;
}
let token_wait = if state.tokens >= 1.0 {
0.0
} else {
(1.0 - state.tokens) / self.config.requests_per_second
};
token_wait.max(blocked_for).max(0.001)
}
}
/// Registry host for a URL, without userinfo, lowercased, port preserved.
pub fn host_of(url: &str) -> String {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
let host = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host)
.trim();
if host.is_empty() {
"unknown".to_owned()
} else {
host.to_ascii_lowercase()
}
}
fn parse_blocked_until(raw: &str) -> Option<f64> {
if let Ok(time) = chrono::DateTime::parse_from_rfc3339(raw) {
return Some(time.timestamp_millis() as f64 / 1000.0);
}
raw.parse::<f64>().ok()
}
/// A [`RegistryHttp`] wrapper that rate-governs every call per URL host.
pub struct GovernedHttp {
inner: Arc<dyn RegistryHttp>,
limiter: Arc<HostLimiter>,
db: Option<DbHandle>,
repo_did: String,
}
impl GovernedHttp {
/// Wrap `inner`, loading persisted host state when `db` is supplied.
pub async fn new(
inner: Arc<dyn RegistryHttp>,
limiter: Arc<HostLimiter>,
db: Option<DbHandle>,
repo_did: impl Into<String>,
) -> Result<Self> {
if let Some(db) = &db {
limiter.load_rows(&db.list_source_host_states().await?);
}
Ok(Self {
inner,
limiter,
db,
repo_did: repo_did.into(),
})
}
/// In-memory-only governor (no persistence).
pub fn in_memory(
inner: Arc<dyn RegistryHttp>,
limiter: Arc<HostLimiter>,
repo_did: impl Into<String>,
) -> Self {
Self {
inner,
limiter,
db: None,
repo_did: repo_did.into(),
}
}
/// The repo DID this governor was created for. Rate state itself is keyed
/// by host and shared across repos.
pub fn repo_did(&self) -> &str {
&self.repo_did
}
async fn prepare(&self, url: &str) -> String {
let host = host_of(url);
self.limiter.acquire(&host).await;
self.persist(&host).await;
host
}
async fn observe(&self, error: anyhow::Error, host: &str) -> anyhow::Error {
if let Some(status) = error.downcast_ref::<HttpStatusError>()
&& let Some(delay) = status.rate_limit_delay(self.limiter.now_unix())
{
self.limiter.block(host, delay);
self.persist(host).await;
}
error
}
async fn persist(&self, host: &str) {
let Some(db) = &self.db else {
return;
};
let snapshot = self.limiter.snapshot(host);
// Persistence is best-effort: when the cache write fails the
// in-memory gate still applies, so the request is not failed.
let _ = db
.mark_source_host_state(SourceHostStateMark {
host: host.to_owned(),
window_start: snapshot.window_start,
requests: snapshot.requests,
blocked_until: snapshot.blocked_until,
})
.await;
}
}
#[async_trait]
impl RegistryHttp for GovernedHttp {
async fn get_json(&self, url: &str) -> Result<Value> {
let host = self.prepare(url).await;
match self.inner.get_json(url).await {
Ok(value) => Ok(value),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn get_json_with_headers(
&self,
url: &str,
headers: &[(String, String)],
) -> Result<Value> {
let host = self.prepare(url).await;
match self.inner.get_json_with_headers(url, headers).await {
Ok(value) => Ok(value),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn get_text(&self, url: &str) -> Result<String> {
let host = self.prepare(url).await;
match self.inner.get_text(url).await {
Ok(text) => Ok(text),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn head_size(&self, url: &str) -> Result<u64> {
let host = self.prepare(url).await;
match self.inner.head_size(url).await {
Ok(size) => Ok(size),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn download(&self, url: &str) -> Result<Vec<u8>> {
let host = self.prepare(url).await;
match self.inner.download(url).await {
Ok(bytes) => Ok(bytes),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn download_limited(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>> {
let host = self.prepare(url).await;
match self.inner.download_limited(url, max_bytes).await {
Ok(bytes) => Ok(bytes),
Err(error) => Err(self.observe(error, &host).await),
}
}
async fn post_json(&self, url: &str, body: &Value) -> Result<Value> {
let host = self.prepare(url).await;
match self.inner.post_json(url, body).await {
Ok(value) => Ok(value),
Err(error) => Err(self.observe(error, &host).await),
}
}
}