//! 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, } #[derive(Debug, Clone)] struct HostState { tokens: f64, last_refill: f64, window_start: f64, requests: i64, blocked_until: Option, } 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, hosts: Mutex>, } 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) -> 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 { 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 { if let Ok(time) = chrono::DateTime::parse_from_rfc3339(raw) { return Some(time.timestamp_millis() as f64 / 1000.0); } raw.parse::().ok() } /// A [`RegistryHttp`] wrapper that rate-governs every call per URL host. pub struct GovernedHttp { inner: Arc, limiter: Arc, db: Option, repo_did: String, } impl GovernedHttp { /// Wrap `inner`, loading persisted host state when `db` is supplied. pub async fn new( inner: Arc, limiter: Arc, db: Option, repo_did: impl Into, ) -> Result { 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, limiter: Arc, repo_did: impl Into, ) -> 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::() && 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 { 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 { 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 { 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 { 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> { 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> { 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 { 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), } } }