use std::collections::BTreeMap;
use chrono::{DateTime, Datelike as _, TimeZone as _, Utc};
use serde::{Deserialize, Serialize};
use super::HiveError;
use super::state::{HiveStore, load_or_quarantine, lock_state, write_private};
pub(crate) const THROTTLE_FILE: &str = "throttles.json";
pub const MIN_WAIT_S: i64 = 60;
pub const MAX_WAIT_S: i64 = 32 * 86_400;
pub const POLICY_HOLD_S: i64 = 15 * 60;
pub const QUOTA_PROBE_S: i64 = 3600;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Scope {
Sync,
Bus,
Tasks,
Connect,
}
impl Scope {
pub fn as_str(self) -> &'static str {
match self {
Self::Sync => "sync",
Self::Bus => "bus",
Self::Tasks => "tasks",
Self::Connect => "connect",
}
}
}
fn resource_scopes(resource: &str) -> &'static [Scope] {
match resource {
"transfer_bytes" => &[Scope::Sync],
"bus_messages" => &[Scope::Bus],
"registered_engines" => &[Scope::Connect],
_ => &[],
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Throttle {
pub scopes: Vec<String>,
pub until: String,
pub line: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub probe_at: Option<String>,
}
impl Throttle {
fn holds(&self, scope: Scope) -> bool {
self.scopes.iter().any(|s| s == scope.as_str())
}
fn active_at(&self, now: DateTime<Utc>) -> bool {
DateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| until > now)
}
#[must_use]
pub fn refusal(&self) -> HiveError {
HiveError::Refused(format!(
"waiting for Hive until {}: {}",
self.until, self.line
))
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Throttles {
#[serde(default)]
items: BTreeMap<String, Throttle>,
}
fn stamp(at: DateTime<Utc>) -> String {
at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
fn next_month(now: DateTime<Utc>) -> DateTime<Utc> {
let (year, month) = if now.month() == 12 {
(now.year() + 1, 1)
} else {
(now.year(), now.month() + 1)
};
Utc.with_ymd_and_hms(year, month, 1, 0, 0, 0)
.single()
.unwrap_or(now + chrono::Duration::days(31))
}
fn clamp(now: DateTime<Utc>, until: DateTime<Utc>) -> DateTime<Utc> {
let wait = (until - now).num_seconds();
if (MIN_WAIT_S..=MAX_WAIT_S).contains(&wait) {
until
} else {
now + chrono::Duration::seconds(wait.clamp(MIN_WAIT_S, MAX_WAIT_S))
}
}
#[must_use]
pub fn of_error(
scope: Option<Scope>,
error: &HiveError,
now: DateTime<Utc>,
) -> Option<(String, Throttle)> {
let (key, scopes, until) = match error {
HiveError::QuotaExceeded(q) if q.waits() => {
let until = match error.retry_after_at(now) {
Some(seconds) => {
let wait = i64::try_from(seconds)
.unwrap_or(MAX_WAIT_S)
.clamp(MIN_WAIT_S, MAX_WAIT_S);
now + chrono::Duration::seconds(wait)
}
None => next_month(now),
};
(
format!("quota:{}", q.resource),
resource_scopes(&q.resource),
clamp(now, until),
)
}
HiveError::QuotaExceeded(q) if q.cooling_slot() => {
let reset = DateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
.ok()?
.with_timezone(&Utc);
(
format!("quota:{}", q.resource),
resource_scopes(&q.resource),
clamp(now, reset),
)
}
HiveError::PolicyDenied(d) => (
format!(
"policy:{}:{}",
d.member.as_deref().unwrap_or("unknown"),
scope?.as_str()
),
&[][..],
now + chrono::Duration::seconds(POLICY_HOLD_S),
),
_ => return None,
};
let mut names: Vec<String> = scope
.into_iter()
.chain(scopes.iter().copied())
.map(|s| s.as_str().to_string())
.collect();
names.sort();
names.dedup();
if names.is_empty() {
return None;
}
let probe = now + chrono::Duration::seconds(QUOTA_PROBE_S);
let probe_at = (key.starts_with("quota:") && until > probe).then(|| stamp(probe));
Some((
key,
Throttle {
scopes: names,
until: stamp(until),
line: error.to_string(),
probe_at,
},
))
}
fn read(store: &HiveStore) -> Throttles {
load_or_quarantine(&store.data_dir().join(THROTTLE_FILE), |_: &Throttles| true)
.ok()
.flatten()
.unwrap_or_default()
}
fn change(store: &HiveStore, edit: impl FnOnce(&mut Throttles)) -> Result<(), HiveError> {
let dir = store.data_dir();
let _lock = lock_state(dir, THROTTLE_FILE)?;
let mut throttles = read(store);
edit(&mut throttles);
let bytes = serde_json::to_vec(&throttles).map_err(|e| HiveError::Local(e.to_string()))?;
write_private(dir, THROTTLE_FILE, &bytes)
}
pub fn note(store: &HiveStore, scope: Scope, error: HiveError, now: DateTime<Utc>) -> HiveError {
note_on(store, Some(scope), error, now)
}
pub fn note_on(
store: &HiveStore,
scope: Option<Scope>,
error: HiveError,
now: DateTime<Utc>,
) -> HiveError {
if let Some((key, throttle)) = of_error(scope, &error, now)
&& let Err(e) = change(store, |t| {
t.items.retain(|_, v| v.active_at(now));
t.items.insert(key, throttle);
})
{
tracing::warn!("hive: could not record a throttle: {e}");
}
error
}
#[must_use]
pub fn holding(store: &HiveStore, scope: Scope, now: DateTime<Utc>) -> Option<Throttle> {
read(store)
.items
.into_values()
.filter(|t| t.holds(scope) && t.active_at(now))
.max_by(|a, b| a.until.cmp(&b.until))
}
pub fn check(store: &HiveStore, scope: Scope, now: DateTime<Utc>) -> Result<(), HiveError> {
let Some(held) = holding(store, scope, now) else {
return Ok(());
};
let due = |t: &Throttle| {
t.probe_at
.as_deref()
.and_then(|p| DateTime::parse_from_rfc3339(p).ok())
.is_some_and(|p| p <= now)
};
let throttles = read(store);
let active: Vec<(&String, &Throttle)> = throttles
.items
.iter()
.filter(|(_, t)| t.holds(scope) && t.active_at(now))
.collect();
if !active
.iter()
.all(|(k, t)| k.starts_with("quota:") && due(t))
{
return Err(held.refusal());
}
let next = stamp(now + chrono::Duration::seconds(QUOTA_PROBE_S));
let keys: Vec<String> = active.iter().map(|(k, _)| (*k).clone()).collect();
let _ = change(store, |t| {
for k in &keys {
if let Some(v) = t.items.get_mut(k) {
v.probe_at = Some(next.clone());
}
}
});
Ok(())
}
#[must_use]
pub fn quota_holds(store: &HiveStore, scope: Scope, now: DateTime<Utc>) -> bool {
read(store)
.items
.iter()
.any(|(k, t)| k.starts_with("quota:") && t.holds(scope) && t.active_at(now))
}
pub fn quota_lifted(store: &HiveStore, scope: Scope) {
if read(store)
.items
.iter()
.any(|(k, t)| k.starts_with("quota:") && t.holds(scope))
{
let _ = change(store, |t| {
t.items
.retain(|k, v| !(k.starts_with("quota:") && v.holds(scope)));
});
}
}
pub fn passed(store: &HiveStore, scope: Scope) {
let suffix = format!(":{}", scope.as_str());
if read(store)
.items
.keys()
.any(|k| k.starts_with("policy:") && k.ends_with(&suffix))
{
let _ = change(store, |t| {
t.items
.retain(|k, _| !(k.starts_with("policy:") && k.ends_with(&suffix)));
});
}
quota_lifted(store, scope);
}
pub fn plan_changed(store: &HiveStore) {
if read(store).items.keys().any(|k| k.starts_with("quota:")) {
let _ = change(store, |t| t.items.retain(|k, _| !k.starts_with("quota:")));
}
}
pub fn policy_changed(store: &HiveStore) {
if read(store).items.keys().any(|k| k.starts_with("policy:")) {
let _ = change(store, |t| t.items.retain(|k, _| !k.starts_with("policy:")));
}
super::outbox::Outbox::at(store.data_dir()).release_policy_holds();
}
pub fn clear_connect(store: &HiveStore) {
let _ = change(store, |t| {
t.items.retain(|_, v| !v.holds(Scope::Connect));
});
}
#[must_use]
pub fn status_lines(store: &HiveStore, now: DateTime<Utc>) -> Vec<String> {
read(store)
.items
.values()
.filter(|t| t.active_at(now))
.map(|t| {
format!(
"Throttled: {} until {}: {}",
t.scopes.join(", "),
t.until,
t.line
)
})
.collect()
}
#[cfg(test)]
#[path = "throttle_tests.rs"]
mod tests;