use std::collections::BTreeMap;
use lean_ctx_time::{OffsetDateTime, UtcDateTime};
use serde::{Deserialize, Serialize};
use super::CloudError;
use super::state::{CloudStore, 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;
const TOKEN_KEY: &str = "rate:token";
pub const TOKEN_SCOPE: &str = "token";
pub const RATE_FIRST_S: i64 = 60;
pub const RATE_MAX_WAIT_S: i64 = 3600;
pub const RATE_FLOOR_MAX_S: i64 = 86_400;
pub const RATE_MEMORY_S: i64 = 6 * 3600;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Scope {
Sync,
Bus,
Tasks,
Connect,
Models,
}
impl Scope {
pub fn as_str(self) -> &'static str {
match self {
Self::Sync => "sync",
Self::Bus => "bus",
Self::Tasks => "tasks",
Self::Connect => "connect",
Self::Models => "models",
}
}
}
fn resource_scopes(resource: &str) -> &'static [Scope] {
match resource {
"transfer_bytes" => &[Scope::Sync],
"bus_messages" => &[Scope::Bus],
"registered_instances" => &[Scope::Connect],
"model_credit_usd_micros" => &[Scope::Models],
_ => &[],
}
}
#[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>,
#[serde(default, skip_serializing_if = "is_zero")]
pub strikes: u32,
}
#[allow(clippy::trivially_copy_pass_by_ref)] fn is_zero(n: &u32) -> bool {
*n == 0
}
impl Throttle {
fn holds(&self, scope: Scope) -> bool {
self.scopes.iter().any(|s| s == scope.as_str())
}
fn active_at(&self, now: UtcDateTime) -> bool {
OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| until > now)
}
fn kept_at(&self, key: &str, now: UtcDateTime) -> bool {
if key == TOKEN_KEY {
return !self.token_stale(now)
&& OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| {
until.to_utc() + lean_ctx_time::Duration::seconds(RATE_MEMORY_S) > now
});
}
self.active_at(now)
}
fn token_stale(&self, now: UtcDateTime) -> bool {
OffsetDateTime::parse_from_rfc3339(&self.until)
.is_ok_and(|until| (until.to_utc() - now).num_seconds() > RATE_FLOOR_MAX_S)
}
#[must_use]
pub fn refusal(&self) -> CloudError {
CloudError::Refused(format!(
"waiting for LeanCTX Cloud until {}: {}",
self.until, self.line
))
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Throttles {
#[serde(default)]
items: BTreeMap<String, Throttle>,
}
fn stamp(at: UtcDateTime) -> String {
at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
}
fn next_month(now: UtcDateTime) -> UtcDateTime {
let (year, month) = if now.month() == 12 {
(now.year() + 1, 1)
} else {
(now.year(), now.month() + 1)
};
UtcDateTime::with_ymd_and_hms(year, month, 1, 0, 0, 0)
.unwrap_or(now + lean_ctx_time::Duration::days(31))
}
fn clamp(now: UtcDateTime, until: UtcDateTime) -> UtcDateTime {
let wait = (until - now).num_seconds();
if (MIN_WAIT_S..=MAX_WAIT_S).contains(&wait) {
until
} else {
now + lean_ctx_time::Duration::seconds(wait.clamp(MIN_WAIT_S, MAX_WAIT_S))
}
}
#[must_use]
pub fn of_error(
scope: Option<Scope>,
error: &CloudError,
now: UtcDateTime,
) -> Option<(String, Throttle)> {
let (key, scopes, until) = match error {
CloudError::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 + lean_ctx_time::Duration::seconds(wait)
}
None => next_month(now),
};
(
format!("quota:{}", q.resource),
resource_scopes(&q.resource),
clamp(now, until),
)
}
CloudError::QuotaExceeded(q) if q.cooling_slot() => {
let reset = OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
.ok()?
.to_utc();
(
format!("quota:{}", q.resource),
resource_scopes(&q.resource),
clamp(now, reset),
)
}
CloudError::PolicyDenied(d) => (
format!(
"policy:{}:{}",
d.member.as_deref().unwrap_or("unknown"),
scope?.as_str()
),
&[][..],
now + lean_ctx_time::Duration::seconds(POLICY_HOLD_S),
),
CloudError::PlanRequired(_) if scope == Some(Scope::Models) => (
"plan:models".to_string(),
&[][..],
now + lean_ctx_time::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 + lean_ctx_time::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,
strikes: 0,
},
))
}
fn read(store: &CloudStore) -> Throttles {
load_or_quarantine(&store.data_dir().join(THROTTLE_FILE), |_: &Throttles| true)
.ok()
.flatten()
.unwrap_or_default()
}
fn change(store: &CloudStore, edit: impl FnOnce(&mut Throttles)) -> Result<(), CloudError> {
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| CloudError::Local(e.to_string()))?;
write_private(dir, THROTTLE_FILE, &bytes)
}
pub fn note(store: &CloudStore, scope: Scope, error: CloudError, now: UtcDateTime) -> CloudError {
note_on(store, Some(scope), error, now)
}
pub fn note_on(
store: &CloudStore,
scope: Option<Scope>,
error: CloudError,
now: UtcDateTime,
) -> CloudError {
if let Some((key, throttle)) = of_error(scope, &error, now)
&& let Err(e) = change(store, |t| {
t.items.retain(|k, v| v.kept_at(k, now));
t.items.insert(key, throttle);
})
{
tracing::warn!("cloud: could not record a throttle: {e}");
}
error
}
#[must_use]
pub fn rate_wait(strikes: u32, floor: Option<u64>) -> i64 {
let backoff = RATE_FIRST_S
.saturating_mul(1i64 << strikes.saturating_sub(1).min(16))
.min(RATE_MAX_WAIT_S);
let floor = floor.map_or(0, |s| {
i64::try_from(s)
.unwrap_or(RATE_FLOOR_MAX_S)
.min(RATE_FLOOR_MAX_S)
});
backoff.max(floor).max(1)
}
pub fn note_token_limit(store: &CloudStore, error: CloudError, now: UtcDateTime) -> CloudError {
let CloudError::RateLimited { retry_after } = &error else {
return error;
};
let floor = *retry_after;
let line = error.to_string();
if let Err(e) = change(store, |t| {
let strikes = t
.items
.get(TOKEN_KEY)
.filter(|prev| prev.kept_at(TOKEN_KEY, now))
.map_or(0, |prev| prev.strikes)
.saturating_add(1);
let until = now + lean_ctx_time::Duration::seconds(rate_wait(strikes, floor));
t.items.retain(|k, v| v.kept_at(k, now));
t.items.insert(
TOKEN_KEY.to_string(),
Throttle {
scopes: vec![TOKEN_SCOPE.to_string()],
until: stamp(until),
line,
probe_at: None,
strikes,
},
);
}) {
tracing::warn!("cloud: could not record the token rate limit: {e}");
}
error
}
#[must_use]
pub fn token_hold(store: &CloudStore, now: UtcDateTime) -> Option<CloudError> {
let held = read(store).items.remove(TOKEN_KEY)?;
let until = OffsetDateTime::parse_from_rfc3339(&held.until).ok()?;
let left = (until.to_utc() - now).num_seconds();
(left > 0 && left <= RATE_FLOOR_MAX_S).then(|| CloudError::RateLimited {
retry_after: u64::try_from(left).ok(),
})
}
pub fn token_minted(store: &CloudStore) {
if read(store).items.contains_key(TOKEN_KEY) {
let _ = change(store, |t| {
t.items.remove(TOKEN_KEY);
});
}
}
#[must_use]
pub fn holding(store: &CloudStore, scope: Scope, now: UtcDateTime) -> 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: &CloudStore, scope: Scope, now: UtcDateTime) -> Result<(), CloudError> {
let Some(held) = holding(store, scope, now) else {
return Ok(());
};
let due = |t: &Throttle| {
t.probe_at
.as_deref()
.and_then(|p| OffsetDateTime::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 + lean_ctx_time::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: &CloudStore, scope: Scope, now: UtcDateTime) -> bool {
read(store)
.items
.iter()
.any(|(k, t)| k.starts_with("quota:") && t.holds(scope) && t.active_at(now))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HoldKind {
Quota,
Plan,
Policy,
}
#[must_use]
pub fn models_hold_kind(store: &CloudStore, now: UtcDateTime) -> HoldKind {
read(store)
.items
.iter()
.filter(|(_, t)| t.holds(Scope::Models) && t.active_at(now))
.max_by(|a, b| a.1.until.cmp(&b.1.until))
.map_or(HoldKind::Policy, |(k, _)| {
if k.starts_with("quota:") {
HoldKind::Quota
} else if k.starts_with("plan:") {
HoldKind::Plan
} else {
HoldKind::Policy
}
})
}
pub fn quota_lifted(store: &CloudStore, 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: &CloudStore, 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: &CloudStore) {
let old_plan = |k: &str| k.starts_with("quota:") || k.starts_with("plan:");
if read(store).items.keys().any(|k| old_plan(k)) {
let _ = change(store, |t| t.items.retain(|k, _| !old_plan(k)));
}
}
pub fn policy_changed(store: &CloudStore) {
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: &CloudStore) {
let _ = change(store, |t| {
t.items.retain(|_, v| !v.holds(Scope::Connect));
});
}
#[must_use]
pub fn status_lines(store: &CloudStore, now: UtcDateTime) -> Vec<String> {
read(store)
.items
.iter()
.filter(|(key, t)| t.active_at(now) && !(key.as_str() == TOKEN_KEY && t.token_stale(now)))
.map(|(_, t)| {
format!(
"Throttled: {} until {}: {}",
t.scopes.join(", "),
t.until,
t.line
)
})
.collect()
}
#[cfg(test)]
#[path = "throttle_tests.rs"]
mod tests;