1use std::collections::BTreeMap;
44
45use lean_ctx_time::{OffsetDateTime, UtcDateTime};
46use serde::{Deserialize, Serialize};
47
48use super::CloudError;
49use super::state::{CloudStore, load_or_quarantine, lock_state, write_private};
50
51pub(crate) const THROTTLE_FILE: &str = "throttles.json";
52pub const MIN_WAIT_S: i64 = 60;
54pub const MAX_WAIT_S: i64 = 32 * 86_400;
56pub const POLICY_HOLD_S: i64 = 15 * 60;
58pub const QUOTA_PROBE_S: i64 = 3600;
62const TOKEN_KEY: &str = "rate:token";
64pub const TOKEN_SCOPE: &str = "token";
66pub const RATE_FIRST_S: i64 = 60;
68pub const RATE_MAX_WAIT_S: i64 = 3600;
70pub const RATE_FLOOR_MAX_S: i64 = 86_400;
72pub const RATE_MEMORY_S: i64 = 6 * 3600;
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
78pub enum Scope {
79 Sync,
81 Bus,
83 Tasks,
85 Connect,
87 Models,
89}
90
91impl Scope {
92 pub fn as_str(self) -> &'static str {
93 match self {
94 Self::Sync => "sync",
95 Self::Bus => "bus",
96 Self::Tasks => "tasks",
97 Self::Connect => "connect",
98 Self::Models => "models",
99 }
100 }
101}
102
103fn resource_scopes(resource: &str) -> &'static [Scope] {
105 match resource {
106 "transfer_bytes" => &[Scope::Sync],
109 "bus_messages" => &[Scope::Bus],
110 "registered_instances" => &[Scope::Connect],
111 "model_credit_usd_micros" => &[Scope::Models],
113 _ => &[],
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct Throttle {
120 pub scopes: Vec<String>,
122 pub until: String,
124 pub line: String,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub probe_at: Option<String>,
130 #[serde(default, skip_serializing_if = "is_zero")]
132 pub strikes: u32,
133}
134
135#[allow(clippy::trivially_copy_pass_by_ref)] fn is_zero(n: &u32) -> bool {
137 *n == 0
138}
139
140impl Throttle {
141 fn holds(&self, scope: Scope) -> bool {
142 self.scopes.iter().any(|s| s == scope.as_str())
143 }
144
145 fn active_at(&self, now: UtcDateTime) -> bool {
146 OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| until > now)
147 }
148
149 fn kept_at(&self, key: &str, now: UtcDateTime) -> bool {
153 if key == TOKEN_KEY {
154 return !self.token_stale(now)
155 && OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| {
156 until.to_utc() + lean_ctx_time::Duration::seconds(RATE_MEMORY_S) > now
157 });
158 }
159 self.active_at(now)
160 }
161
162 fn token_stale(&self, now: UtcDateTime) -> bool {
168 OffsetDateTime::parse_from_rfc3339(&self.until)
169 .is_ok_and(|until| (until.to_utc() - now).num_seconds() > RATE_FLOOR_MAX_S)
170 }
171
172 #[must_use]
174 pub fn refusal(&self) -> CloudError {
175 CloudError::Refused(format!(
176 "waiting for the Cloud until {}: {}",
177 self.until, self.line
178 ))
179 }
180}
181
182#[derive(Debug, Clone, Default, Serialize, Deserialize)]
183struct Throttles {
184 #[serde(default)]
186 items: BTreeMap<String, Throttle>,
187}
188
189fn stamp(at: UtcDateTime) -> String {
190 at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
191}
192
193fn next_month(now: UtcDateTime) -> UtcDateTime {
195 let (year, month) = if now.month() == 12 {
196 (now.year() + 1, 1)
197 } else {
198 (now.year(), now.month() + 1)
199 };
200 UtcDateTime::with_ymd_and_hms(year, month, 1, 0, 0, 0)
201 .unwrap_or(now + lean_ctx_time::Duration::days(31))
202}
203
204fn clamp(now: UtcDateTime, until: UtcDateTime) -> UtcDateTime {
207 let wait = (until - now).num_seconds();
208 if (MIN_WAIT_S..=MAX_WAIT_S).contains(&wait) {
209 until
210 } else {
211 now + lean_ctx_time::Duration::seconds(wait.clamp(MIN_WAIT_S, MAX_WAIT_S))
212 }
213}
214
215#[must_use]
220pub fn of_error(
221 scope: Option<Scope>,
222 error: &CloudError,
223 now: UtcDateTime,
224) -> Option<(String, Throttle)> {
225 let (key, scopes, until) = match error {
226 CloudError::QuotaExceeded(q) if q.waits() => {
227 let until = match error.retry_after_at(now) {
228 Some(seconds) => {
231 let wait = i64::try_from(seconds)
232 .unwrap_or(MAX_WAIT_S)
233 .clamp(MIN_WAIT_S, MAX_WAIT_S);
234 now + lean_ctx_time::Duration::seconds(wait)
235 }
236 None => next_month(now),
237 };
238 (
239 format!("quota:{}", q.resource),
240 resource_scopes(&q.resource),
241 clamp(now, until),
242 )
243 }
244 CloudError::QuotaExceeded(q) if q.cooling_slot() => {
245 let reset = OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
246 .ok()?
247 .to_utc();
248 (
249 format!("quota:{}", q.resource),
250 resource_scopes(&q.resource),
251 clamp(now, reset),
252 )
253 }
254 CloudError::PolicyDenied(d) => (
255 format!(
256 "policy:{}:{}",
257 d.member.as_deref().unwrap_or("unknown"),
258 scope?.as_str()
259 ),
260 &[][..],
261 now + lean_ctx_time::Duration::seconds(POLICY_HOLD_S),
262 ),
263 CloudError::PlanRequired(_) if scope == Some(Scope::Models) => (
267 "plan:models".to_string(),
268 &[][..],
269 now + lean_ctx_time::Duration::seconds(POLICY_HOLD_S),
270 ),
271 _ => return None,
272 };
273 let mut names: Vec<String> = scope
274 .into_iter()
275 .chain(scopes.iter().copied())
276 .map(|s| s.as_str().to_string())
277 .collect();
278 names.sort();
279 names.dedup();
280 if names.is_empty() {
281 return None;
282 }
283 let probe = now + lean_ctx_time::Duration::seconds(QUOTA_PROBE_S);
284 let probe_at = (key.starts_with("quota:") && until > probe).then(|| stamp(probe));
285 Some((
286 key,
287 Throttle {
288 scopes: names,
289 until: stamp(until),
290 line: error.to_string(),
291 probe_at,
292 strikes: 0,
293 },
294 ))
295}
296
297fn read(store: &CloudStore) -> Throttles {
298 load_or_quarantine(&store.data_dir().join(THROTTLE_FILE), |_: &Throttles| true)
299 .ok()
300 .flatten()
301 .unwrap_or_default()
302}
303
304fn change(store: &CloudStore, edit: impl FnOnce(&mut Throttles)) -> Result<(), CloudError> {
305 let dir = store.data_dir();
306 let _lock = lock_state(dir, THROTTLE_FILE)?;
307 let mut throttles = read(store);
308 edit(&mut throttles);
309 let bytes = serde_json::to_vec(&throttles).map_err(|e| CloudError::Local(e.to_string()))?;
310 write_private(dir, THROTTLE_FILE, &bytes)
311}
312
313pub fn note(store: &CloudStore, scope: Scope, error: CloudError, now: UtcDateTime) -> CloudError {
316 note_on(store, Some(scope), error, now)
317}
318
319pub fn note_on(
322 store: &CloudStore,
323 scope: Option<Scope>,
324 error: CloudError,
325 now: UtcDateTime,
326) -> CloudError {
327 if let Some((key, throttle)) = of_error(scope, &error, now)
328 && let Err(e) = change(store, |t| {
329 t.items.retain(|k, v| v.kept_at(k, now));
330 t.items.insert(key, throttle);
331 })
332 {
333 tracing::warn!("cloud: could not record a throttle: {e}");
334 }
335 error
336}
337
338#[must_use]
344pub fn rate_wait(strikes: u32, floor: Option<u64>) -> i64 {
345 let backoff = RATE_FIRST_S
346 .saturating_mul(1i64 << strikes.saturating_sub(1).min(16))
347 .min(RATE_MAX_WAIT_S);
348 let floor = floor.map_or(0, |s| {
349 i64::try_from(s)
350 .unwrap_or(RATE_FLOOR_MAX_S)
351 .min(RATE_FLOOR_MAX_S)
352 });
353 backoff.max(floor).max(1)
354}
355
356pub fn note_token_limit(store: &CloudStore, error: CloudError, now: UtcDateTime) -> CloudError {
360 let CloudError::RateLimited { retry_after } = &error else {
361 return error;
362 };
363 let floor = *retry_after;
364 let line = error.to_string();
365 if let Err(e) = change(store, |t| {
366 let strikes = t
367 .items
368 .get(TOKEN_KEY)
369 .filter(|prev| prev.kept_at(TOKEN_KEY, now))
370 .map_or(0, |prev| prev.strikes)
371 .saturating_add(1);
372 let until = now + lean_ctx_time::Duration::seconds(rate_wait(strikes, floor));
373 t.items.retain(|k, v| v.kept_at(k, now));
374 t.items.insert(
375 TOKEN_KEY.to_string(),
376 Throttle {
377 scopes: vec![TOKEN_SCOPE.to_string()],
378 until: stamp(until),
379 line,
380 probe_at: None,
381 strikes,
382 },
383 );
384 }) {
385 tracing::warn!("cloud: could not record the token rate limit: {e}");
386 }
387 error
388}
389
390#[must_use]
395pub fn token_hold(store: &CloudStore, now: UtcDateTime) -> Option<CloudError> {
396 let held = read(store).items.remove(TOKEN_KEY)?;
397 let until = OffsetDateTime::parse_from_rfc3339(&held.until).ok()?;
398 let left = (until.to_utc() - now).num_seconds();
399 (left > 0 && left <= RATE_FLOOR_MAX_S).then(|| CloudError::RateLimited {
400 retry_after: u64::try_from(left).ok(),
401 })
402}
403
404pub fn token_minted(store: &CloudStore) {
406 if read(store).items.contains_key(TOKEN_KEY) {
407 let _ = change(store, |t| {
408 t.items.remove(TOKEN_KEY);
409 });
410 }
411}
412
413#[must_use]
415pub fn holding(store: &CloudStore, scope: Scope, now: UtcDateTime) -> Option<Throttle> {
416 read(store)
417 .items
418 .into_values()
419 .filter(|t| t.holds(scope) && t.active_at(now))
420 .max_by(|a, b| a.until.cmp(&b.until))
421}
422
423pub fn check(store: &CloudStore, scope: Scope, now: UtcDateTime) -> Result<(), CloudError> {
428 let Some(held) = holding(store, scope, now) else {
429 return Ok(());
430 };
431 let due = |t: &Throttle| {
432 t.probe_at
433 .as_deref()
434 .and_then(|p| OffsetDateTime::parse_from_rfc3339(p).ok())
435 .is_some_and(|p| p <= now)
436 };
437 let throttles = read(store);
438 let active: Vec<(&String, &Throttle)> = throttles
439 .items
440 .iter()
441 .filter(|(_, t)| t.holds(scope) && t.active_at(now))
442 .collect();
443 if !active
444 .iter()
445 .all(|(k, t)| k.starts_with("quota:") && due(t))
446 {
447 return Err(held.refusal());
448 }
449 let next = stamp(now + lean_ctx_time::Duration::seconds(QUOTA_PROBE_S));
450 let keys: Vec<String> = active.iter().map(|(k, _)| (*k).clone()).collect();
451 let _ = change(store, |t| {
452 for k in &keys {
453 if let Some(v) = t.items.get_mut(k) {
454 v.probe_at = Some(next.clone());
455 }
456 }
457 });
458 Ok(())
459}
460
461#[must_use]
463pub fn quota_holds(store: &CloudStore, scope: Scope, now: UtcDateTime) -> bool {
464 read(store)
465 .items
466 .iter()
467 .any(|(k, t)| k.starts_with("quota:") && t.holds(scope) && t.active_at(now))
468}
469
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
472pub enum HoldKind {
473 Quota,
474 Plan,
475 Policy,
476}
477
478#[must_use]
481pub fn models_hold_kind(store: &CloudStore, now: UtcDateTime) -> HoldKind {
482 read(store)
483 .items
484 .iter()
485 .filter(|(_, t)| t.holds(Scope::Models) && t.active_at(now))
486 .max_by(|a, b| a.1.until.cmp(&b.1.until))
487 .map_or(HoldKind::Policy, |(k, _)| {
488 if k.starts_with("quota:") {
489 HoldKind::Quota
490 } else if k.starts_with("plan:") {
491 HoldKind::Plan
492 } else {
493 HoldKind::Policy
494 }
495 })
496}
497
498pub fn quota_lifted(store: &CloudStore, scope: Scope) {
501 if read(store)
502 .items
503 .iter()
504 .any(|(k, t)| k.starts_with("quota:") && t.holds(scope))
505 {
506 let _ = change(store, |t| {
507 t.items
508 .retain(|k, v| !(k.starts_with("quota:") && v.holds(scope)));
509 });
510 }
511}
512
513pub fn passed(store: &CloudStore, scope: Scope) {
516 let suffix = format!(":{}", scope.as_str());
517 if read(store)
518 .items
519 .keys()
520 .any(|k| k.starts_with("policy:") && k.ends_with(&suffix))
521 {
522 let _ = change(store, |t| {
523 t.items
524 .retain(|k, _| !(k.starts_with("policy:") && k.ends_with(&suffix)));
525 });
526 }
527 quota_lifted(store, scope);
528}
529
530pub fn plan_changed(store: &CloudStore) {
534 let old_plan = |k: &str| k.starts_with("quota:") || k.starts_with("plan:");
535 if read(store).items.keys().any(|k| old_plan(k)) {
536 let _ = change(store, |t| t.items.retain(|k, _| !old_plan(k)));
537 }
538}
539
540pub fn policy_changed(store: &CloudStore) {
544 if read(store).items.keys().any(|k| k.starts_with("policy:")) {
545 let _ = change(store, |t| t.items.retain(|k, _| !k.starts_with("policy:")));
546 }
547 super::outbox::Outbox::at(store.data_dir()).release_policy_holds();
548}
549
550pub fn clear_connect(store: &CloudStore) {
552 let _ = change(store, |t| {
553 t.items.retain(|_, v| !v.holds(Scope::Connect));
554 });
555}
556
557#[must_use]
559pub fn status_lines(store: &CloudStore, now: UtcDateTime) -> Vec<String> {
560 read(store)
561 .items
562 .iter()
563 .filter(|(key, t)| t.active_at(now) && !(key.as_str() == TOKEN_KEY && t.token_stale(now)))
564 .map(|(_, t)| {
565 format!(
566 "Throttled: {} until {}: {}",
567 t.scopes.join(", "),
568 t.until,
569 t.line
570 )
571 })
572 .collect()
573}
574
575#[cfg(test)]
576#[path = "throttle_tests.rs"]
577mod tests;