1use serde::{Deserialize, Serialize};
5
6use super::Quota;
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10pub struct PeriodUsage {
11 pub start: String,
13 pub used: u64,
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub limit: Option<u64>,
16}
17
18impl PeriodUsage {
19 fn used_up(&self) -> bool {
20 self.limit.is_some_and(|limit| self.used >= limit)
21 }
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
26pub struct QuotaStatus {
27 pub day: PeriodUsage,
28 pub week: PeriodUsage,
29 pub month: PeriodUsage,
30 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub error: Option<String>,
35}
36
37impl QuotaStatus {
38 pub fn exhausted(&self) -> Option<String> {
40 if let Some(error) = &self.error {
41 return Some(error.clone());
42 }
43 [
44 ("day", &self.day),
45 ("week", &self.week),
46 ("month", &self.month),
47 ]
48 .into_iter()
49 .find(|(_, usage)| usage.used_up())
50 .map(|(period, usage)| {
51 format!(
52 "{period} quota of {} tokens used up ({} since {})",
53 usage.limit.unwrap_or_default(),
54 usage.used,
55 usage.start
56 )
57 })
58 }
59}
60
61pub trait QuotaLedger: Send + Sync {
63 fn status(&self, provider: &str, quota: &Quota) -> QuotaStatus;
64 fn record(&self, provider: &str, tokens: u64) -> Result<(), String>;
67}