Skip to main content

base/provider/
quota.rs

1//! Provider token quotas as the router reads them: a provider's usage in the
2//! day, week and month a call falls in, and where that usage is kept.
3
4use serde::{Deserialize, Serialize};
5
6use super::Quota;
7
8/// One period's usage against its limit.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10pub struct PeriodUsage {
11    /// The period's first day, `YYYY-MM-DD`, local time.
12    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/// A provider's usage in the periods it is in now.
25#[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    /// Why the usage could not be read. The provider counts as used up until
31    /// someone repairs or removes what is kept: reading it as no usage
32    /// would hand the provider a fresh quota.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub error: Option<String>,
35}
36
37impl QuotaStatus {
38    /// Why no more calls go to the provider this period, if none do.
39    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
61/// Where providers' usage is kept.
62pub trait QuotaLedger: Send + Sync {
63    fn status(&self, provider: &str, quota: &Quota) -> QuotaStatus;
64    /// Add `tokens` to what `provider` used in the periods now. An error
65    /// says the usage was not written.
66    fn record(&self, provider: &str, tokens: u64) -> Result<(), String>;
67}