Skip to main content

lean_ctx_protocol/cloud/
usage.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! `GET /v1/usage` (LeanCTX Cloud, capability [`FEATURE_USAGE`]): the
4//! workspace's quotas as the Plan page shows them, so an instance warns at
5//! 80 % instead of meeting a refusal.
6//!
7//! The answer is `{schema: leanctx.cloud.usage/v1, plan, read_only, quotas:
8//! {<resource>: {limit, used, reset_at, state, next_step}}, notices,
9//! model_credit, suggest_team}`. Like every response type it accepts unknown
10//! members; `notices`, `model_credit` and `suggest_team` are carried for a
11//! local reader but not interpreted here, and an
12//! unknown `state` reads as [`CloudQuotaStateV1::Unknown`] rather than
13//! failing the whole answer.
14
15use std::collections::BTreeMap;
16
17use serde::{Deserialize, Serialize};
18
19use crate::ValidationError;
20
21/// The `features` entry of a server that serves `GET /v1/usage`.
22pub const FEATURE_USAGE: &str = "usage";
23
24/// `schema` of the usage answer.
25pub const USAGE_SCHEMA: &str = "leanctx.cloud.usage/v1";
26
27/// Bounds what an answer may hold (the service names seven resources).
28const MAX_QUOTAS: usize = 32;
29const MAX_RESOURCE_LEN: usize = 64;
30
31/// How far one quota is used: `warn` from 80 %, `full` at 100 %.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum CloudQuotaStateV1 {
35    Ok,
36    Warn,
37    Full,
38    /// A state a newer service added; shown like `ok`.
39    #[serde(other)]
40    Unknown,
41}
42
43impl CloudQuotaStateV1 {
44    /// `ok` 0, `warn` 1, `full` 2 (an unknown state counts as `ok`).
45    #[must_use]
46    pub fn level(self) -> u8 {
47        match self {
48            Self::Ok | Self::Unknown => 0,
49            Self::Warn => 1,
50            Self::Full => 2,
51        }
52    }
53}
54
55/// One quota of the usage answer. Amounts are in the resource's unit:
56/// bytes for `*_bytes`, millionths of a US dollar for `*_usd_micros`,
57/// counts otherwise.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct CloudQuotaV1 {
60    /// A negative amount (a credit refunded past zero) reads as 0.
61    #[serde(deserialize_with = "non_negative")]
62    pub limit: u64,
63    #[serde(deserialize_with = "non_negative")]
64    pub used: u64,
65    /// When a monthly quota (or a revoked instance slot) frees again.
66    #[serde(default)]
67    pub reset_at: Option<String>,
68    pub state: CloudQuotaStateV1,
69    /// Where more comes from (`subscribe`, `top_up`, `upgrade_team`,
70    /// `add_seats`, `contact`).
71    #[serde(default)]
72    pub next_step: Option<String>,
73}
74
75/// An amount that should never be negative but may arrive so (a refund or
76/// a correction booked past zero): any integer the wire carries is read,
77/// a negative one as 0, so one odd quota does not fail the whole answer.
78pub(crate) fn non_negative<'de, D>(deserializer: D) -> Result<u64, D::Error>
79where
80    D: serde::Deserializer<'de>,
81{
82    struct Amount;
83    impl serde::de::Visitor<'_> for Amount {
84        type Value = u64;
85        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86            f.write_str("an integer amount")
87        }
88        fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<u64, E> {
89            Ok(value)
90        }
91        fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<u64, E> {
92            Ok(u64::try_from(value).unwrap_or(0))
93        }
94    }
95    deserializer.deserialize_i64(Amount)
96}
97
98/// [`non_negative`] for an optional amount.
99pub(crate) fn non_negative_opt<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
100where
101    D: serde::Deserializer<'de>,
102{
103    #[derive(Deserialize)]
104    struct Wrapped(#[serde(deserialize_with = "non_negative")] u64);
105    Ok(Option::<Wrapped>::deserialize(deserializer)?.map(|Wrapped(v)| v))
106}
107
108/// `GET /v1/usage`.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct CloudUsageV1 {
111    pub schema: String,
112    /// `personal`, `team`, `enterprise` or `locked`.
113    pub plan: String,
114    /// The workspace has no plan: read and export only.
115    #[serde(default)]
116    pub read_only: bool,
117    /// By resource name (`storage_bytes`, `transfer_bytes`, …).
118    #[serde(default)]
119    pub quotas: BTreeMap<String, CloudQuotaV1>,
120    /// The cloud's notices for the Plan page, passed through unread to a
121    /// local reader (`lean-ctx cloud usage --json`).
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub notices: Option<serde_json::Value>,
124    /// Agent-hour credit and top-up, passed through unread.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub model_credit: Option<serde_json::Value>,
127    /// The cloud suggests the Team plan, passed through unread.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub suggest_team: Option<bool>,
130}
131
132impl CloudUsageV1 {
133    /// The schema is this one and the quotas stay within bounds.
134    pub fn validate(&self) -> Result<(), ValidationError> {
135        if self.schema != USAGE_SCHEMA {
136            return Err(ValidationError::new(format!(
137                "usage schema must be {USAGE_SCHEMA}"
138            )));
139        }
140        if self.quotas.len() > MAX_QUOTAS {
141            return Err(ValidationError::new("usage names too many quotas"));
142        }
143        if self.quotas.keys().any(|r| {
144            r.is_empty()
145                || r.len() > MAX_RESOURCE_LEN
146                || !r.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
147        }) {
148            return Err(ValidationError::new("usage names an invalid resource"));
149        }
150        Ok(())
151    }
152
153    /// The quotas at `warn` or `full`, by resource name.
154    pub fn pressing(&self) -> impl Iterator<Item = (&str, &CloudQuotaV1)> {
155        self.quotas
156            .iter()
157            .filter(|(_, q)| q.state.level() > 0)
158            .map(|(r, q)| (r.as_str(), q))
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn fixture() -> serde_json::Value {
167        serde_json::from_str(include_str!(
168            "../../tests/fixtures/cloud/usage.response.json"
169        ))
170        .unwrap()
171    }
172
173    #[test]
174    fn the_cloud_answer_decodes_with_states_and_next_steps() {
175        let usage: CloudUsageV1 = serde_json::from_value(fixture()).unwrap();
176        usage.validate().unwrap();
177        assert_eq!(usage.plan, "personal");
178        assert!(!usage.read_only);
179        assert_eq!(usage.quotas.len(), 7);
180        let storage = &usage.quotas["storage_bytes"];
181        assert_eq!(storage.limit, 40 << 30);
182        assert_eq!(storage.state, CloudQuotaStateV1::Warn);
183        assert_eq!(storage.next_step.as_deref(), Some("upgrade_team"));
184        assert_eq!(storage.reset_at, None);
185        let transfer = &usage.quotas["transfer_bytes"];
186        assert_eq!(transfer.state, CloudQuotaStateV1::Full);
187        assert_eq!(transfer.reset_at.as_deref(), Some("2026-12-01T00:00:00Z"));
188        assert_eq!(
189            usage.quotas["model_credit_usd_micros"].next_step.as_deref(),
190            Some("top_up")
191        );
192        let pressing: Vec<&str> = usage.pressing().map(|(r, _)| r).collect();
193        assert_eq!(pressing, ["storage_bytes", "transfer_bytes"]);
194    }
195
196    #[test]
197    fn unknown_members_and_states_do_not_break_the_answer() {
198        let mut raw = fixture();
199        raw["later"] = serde_json::json!({"x": 1});
200        raw["quotas"]["storage_bytes"]["state"] = "almost".into();
201        raw["quotas"]["storage_bytes"]["extra"] = true.into();
202        let usage: CloudUsageV1 = serde_json::from_value(raw).unwrap();
203        usage.validate().unwrap();
204        let storage = &usage.quotas["storage_bytes"];
205        assert_eq!(storage.state, CloudQuotaStateV1::Unknown);
206        assert_eq!(storage.state.level(), 0);
207    }
208
209    #[test]
210    fn another_schema_or_a_bad_resource_is_refused() {
211        let mut raw = fixture();
212        raw["schema"] = "leanctx.cloud.usage/v2".into();
213        let usage: CloudUsageV1 = serde_json::from_value(raw).unwrap();
214        assert!(usage.validate().is_err());
215        let mut raw = fixture();
216        raw["quotas"]["Bad Name"] = raw["quotas"]["storage_bytes"].clone();
217        let usage: CloudUsageV1 = serde_json::from_value(raw).unwrap();
218        assert!(usage.validate().is_err());
219    }
220
221    #[test]
222    fn a_negative_amount_reads_as_zero() {
223        let mut raw = fixture();
224        raw["quotas"]["storage_bytes"]["used"] = (-5).into();
225        raw["quotas"]["storage_bytes"]["limit"] = (-1).into();
226        raw["quotas"]["transfer_bytes"]["used"] = u64::MAX.into();
227        let usage: CloudUsageV1 = serde_json::from_value(raw).unwrap();
228        assert_eq!(usage.quotas["storage_bytes"].used, 0);
229        assert_eq!(usage.quotas["storage_bytes"].limit, 0);
230        assert_eq!(usage.quotas["transfer_bytes"].used, u64::MAX);
231        let mut raw = fixture();
232        raw["quotas"]["storage_bytes"]["used"] = 1.5.into();
233        assert!(serde_json::from_value::<CloudUsageV1>(raw).is_err());
234
235        let task: crate::cloud::tasks::UsageV1 =
236            serde_json::from_value(serde_json::json!({"tokens": -3, "usd_micros": -7})).unwrap();
237        assert_eq!((task.tokens, task.usd_micros), (0, Some(0)));
238        let task: crate::cloud::tasks::UsageV1 =
239            serde_json::from_value(serde_json::json!({"tokens": 12})).unwrap();
240        assert_eq!((task.tokens, task.usd_micros), (12, None));
241    }
242
243    #[test]
244    fn states_order_by_level() {
245        assert!(CloudQuotaStateV1::Ok.level() < CloudQuotaStateV1::Warn.level());
246        assert!(CloudQuotaStateV1::Warn.level() < CloudQuotaStateV1::Full.level());
247    }
248}