use std::collections::BTreeMap;
use std::time::Duration;
use lean_ctx_protocol::cloud::usage::{CloudQuotaStateV1, CloudQuotaV1, CloudUsageV1};
use lean_ctx_time::UtcDateTime;
use serde::{Deserialize, Serialize};
pub use lean_ctx_protocol::cloud::usage::FEATURE_USAGE;
use crate::CloudError;
use crate::auth::Session;
use crate::config::CloudConfig;
use crate::error::{FREE_CONNECTED, FREE_REGISTERED, NextStep, amount_text, quota_label};
use crate::gateway::BALANCE_RESOURCE;
use crate::state::{CloudStore, write_private};
const USAGE_FILE: &str = "usage.json";
pub const REFRESH_EVERY: Duration = Duration::from_mins(10);
const ORDER: [&str; 7] = [
"storage_bytes",
"transfer_bytes",
"bus_messages",
BALANCE_RESOURCE,
"private_vaults",
"registered_instances",
"connected_instances",
];
const LABEL_WIDTH: usize = 24;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
struct Cache {
server: String,
fetched_at: Option<String>,
tried_at: Option<String>,
usage: Option<CloudUsageV1>,
logged: BTreeMap<String, CloudQuotaStateV1>,
}
fn load(store: &CloudStore) -> Cache {
std::fs::read(store.data_dir().join(USAGE_FILE))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default()
}
fn save(store: &CloudStore, cache: &Cache) {
if let Ok(bytes) = serde_json::to_vec_pretty(cache) {
let _ = write_private(store.data_dir(), USAGE_FILE, &bytes);
}
}
fn load_for(store: &CloudStore, server: &str) -> Cache {
let cache = load(store);
if cache.server == server {
cache
} else {
Cache {
server: server.to_string(),
..Cache::default()
}
}
}
fn stamp(at: UtcDateTime) -> String {
at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
}
#[must_use]
pub fn announced(store: &CloudStore) -> bool {
crate::session_ref::announced(store, FEATURE_USAGE)
}
pub fn fetch(session: &Session) -> Result<Option<CloudUsageV1>, CloudError> {
if !announced(&session.store) {
return Ok(None);
}
let answer = session.with_client(|client| client.get("/usage"))?;
decode(answer).map(Some)
}
fn decode(answer: serde_json::Value) -> Result<CloudUsageV1, CloudError> {
let usage: CloudUsageV1 =
serde_json::from_value(answer).map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
usage
.validate()
.map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
Ok(usage)
}
pub(crate) fn background(session: &Session, now: UtcDateTime) {
if !announced(&session.store) {
return;
}
let store = &session.store;
let mut cache = load_for(store, &session.instance.url);
if !due(cache.tried_at.as_deref(), now) {
return;
}
cache.tried_at = Some(stamp(now));
match fetch(session) {
Ok(Some(usage)) => {
for line in note(&mut cache, usage, now) {
tracing::warn!("{line}");
}
}
Ok(None) => {}
Err(error) => tracing::debug!("cloud: usage not read: {error}"),
}
save(store, &cache);
}
fn due(tried_at: Option<&str>, now: UtcDateTime) -> bool {
tried_at
.and_then(|t| UtcDateTime::parse_from_rfc3339(t).ok())
.is_none_or(|at| {
(now - at)
.to_std()
.map_or(true, |since| since >= REFRESH_EVERY)
})
}
fn note(cache: &mut Cache, usage: CloudUsageV1, now: UtcDateTime) -> Vec<String> {
let lines = rises(&cache.logged, &usage);
cache.logged = ordered(&usage)
.map(|(r, q)| (r.to_owned(), q.state))
.collect();
cache.usage = Some(usage);
cache.fetched_at = Some(stamp(now));
lines
}
#[must_use]
pub fn rises(seen: &BTreeMap<String, CloudQuotaStateV1>, usage: &CloudUsageV1) -> Vec<String> {
ordered(usage)
.filter(|(r, q)| q.state.level() > seen.get(*r).map_or(0, |s| s.level()))
.map(|(r, q)| rise_line(r, q))
.collect()
}
#[must_use]
pub fn rise_line(resource: &str, q: &CloudQuotaV1) -> String {
let what = quota_label(resource);
if is_host_count(resource) {
return host_rise_line(what, resource, q);
}
let amounts = format!(
"{} of {}",
amount_text(resource, q.used),
amount_text(resource, q.limit)
);
let mut line = if q.state == CloudQuotaStateV1::Full {
format!("Cloud: all of your {what} is used ({amounts}); nothing is charged for more")
} else {
format!("Cloud: {} % of your {what} is used ({amounts})", percent(q))
};
if let Some(at) = reset_text(q) {
line.push_str(&format!("; it frees at {at}"));
}
if let Some(hint) = hint(q) {
line.push_str("; ");
line.push_str(hint);
}
line
}
fn is_host_count(resource: &str) -> bool {
matches!(resource, "registered_instances" | "connected_instances")
}
fn host_rise_line(what: &str, resource: &str, q: &CloudQuotaV1) -> String {
let head = format!("{what} {} of {}", q.used, q.limit);
if q.state == CloudQuotaStateV1::Full {
format!(
"{head}: all in use; nothing is charged for more{}",
host_full_tail(resource, q)
)
} else {
let mut line = format!("{head}: {} % in use", percent(q));
if let Some(hint) = hint(q) {
line.push_str("; ");
line.push_str(hint);
}
line
}
}
fn host_full_tail(resource: &str, q: &CloudQuotaV1) -> String {
let mut tail = String::new();
if resource == "registered_instances" {
if let Some(at) = reset_text(q) {
tail.push_str(&format!("; the next registration frees at {at}"));
}
tail.push_str("; ");
tail.push_str(FREE_REGISTERED);
} else {
tail.push_str("; ");
tail.push_str(FREE_CONNECTED);
}
if let Some(hint) = hint(q) {
tail.push_str("; ");
tail.push_str(hint);
}
tail
}
pub fn status(store: &CloudStore, config: &CloudConfig, now: UtcDateTime) -> Vec<String> {
if !announced(store) || !matches!(store.instance(), Ok(Some(_))) {
return Vec::new();
}
match read(store, config, now) {
Ok(Some(r)) if r.live => status_lines(&r.usage, None),
Ok(Some(r)) => status_lines(&r.usage, r.as_of.as_deref()),
Ok(None) => Vec::new(),
Err(error) => vec![format!(
"Usage: not read now ({})",
why_not_read(&error)
)],
}
}
fn why_not_read(error: &CloudError) -> &'static str {
match error {
CloudError::Offline(_) => "The Cloud did not answer",
CloudError::NotConnected => "this machine is not connected; run `lean-ctx cloud connect`",
CloudError::Unauthorized | CloudError::LeaseLapsed | CloudError::Revoked(_) => {
"The Cloud no longer accepts this machine; run `lean-ctx cloud connect` again"
}
CloudError::Forbidden | CloudError::PlanRequired(_) => {
"your role or plan does not show usage"
}
_ if error.is_transient() => "The Cloud is busy; try again shortly",
_ => "The Cloud refused the request",
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct UsageRead {
pub usage: CloudUsageV1,
pub as_of: Option<String>,
pub live: bool,
}
pub fn read(
store: &CloudStore,
config: &CloudConfig,
now: UtcDateTime,
) -> Result<Option<UsageRead>, CloudError> {
if !announced(store) {
return Ok(None);
}
let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
let live = crate::scheduler::connected_session(store, config).and_then(|s| fetch(&s));
let mut cache = load_for(store, &instance.url);
match live {
Ok(Some(usage)) => {
cache.usage = Some(usage.clone());
cache.fetched_at = Some(stamp(now));
save(store, &cache);
Ok(Some(UsageRead {
usage,
as_of: cache.fetched_at,
live: true,
}))
}
Ok(None) => Ok(None),
Err(error) => match cache.usage {
Some(usage) => Ok(Some(UsageRead {
usage,
as_of: cache.fetched_at,
live: false,
})),
None => Err(error),
},
}
}
#[must_use]
pub fn status_lines(usage: &CloudUsageV1, as_of: Option<&str>) -> Vec<String> {
let plan = match usage.plan.as_str() {
"personal" => "Personal",
"team" => "Team",
"enterprise" => "Enterprise",
_ => "no plan",
};
let mut head = format!("Usage: Cloud, {plan}");
if usage.read_only || usage.plan == "locked" {
head.push_str(" (read and export only)");
}
if let Some(at) = as_of {
head.push_str(&format!(" (as of {at})"));
}
let mut lines = vec![head];
lines.extend(ordered(usage).map(|(r, q)| quota_line(r, q)));
lines
}
#[must_use]
pub fn quota_line(resource: &str, q: &CloudQuotaV1) -> String {
let mut line = format!(
" {:<LABEL_WIDTH$}{} of {}",
quota_label(resource),
amount_text(resource, q.used),
amount_text(resource, q.limit)
);
match q.state {
CloudQuotaStateV1::Full if is_host_count(resource) => {
line.push_str(" ยท FULL");
line.push_str(&host_full_tail(resource, q));
return line;
}
CloudQuotaStateV1::Full => {
line.push_str(" ยท FULL");
if let Some(at) = reset_text(q) {
line.push_str(&format!(" until {at}"));
}
}
CloudQuotaStateV1::Warn => line.push_str(&format!(" ยท warn ({} %)", percent(q))),
CloudQuotaStateV1::Ok | CloudQuotaStateV1::Unknown => return line,
}
if let Some(hint) = hint(q) {
line.push_str("; ");
line.push_str(hint);
}
line
}
fn ordered(usage: &CloudUsageV1) -> impl Iterator<Item = (&str, &CloudQuotaV1)> {
let known = ORDER.iter().filter_map(|r| usage.quotas.get_key_value(*r));
let rest = usage
.quotas
.iter()
.filter(|(r, _)| !ORDER.contains(&r.as_str()));
known
.chain(rest)
.map(|(r, q)| (r.as_str(), q))
.filter(|(r, q)| !(*r == BALANCE_RESOURCE && q.limit == 0))
}
fn percent(q: &CloudQuotaV1) -> u128 {
if q.limit == 0 {
return 100;
}
u128::from(q.used) * 100 / u128::from(q.limit)
}
fn hint(q: &CloudQuotaV1) -> Option<&'static str> {
NextStep::of_wire(q.next_step.as_deref()).and_then(NextStep::hint)
}
fn reset_text(q: &CloudQuotaV1) -> Option<String> {
let at = UtcDateTime::parse_from_rfc3339(q.reset_at.as_deref()?).ok()?;
Some(stamp(at))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn order_lists_the_balance_resource_from_the_gateway() {
assert!(ORDER.contains(&BALANCE_RESOURCE));
assert_eq!(BALANCE_RESOURCE, "model_credit_usd_micros");
}
fn fixture() -> serde_json::Value {
serde_json::from_str(include_str!(
"../../lean-ctx-protocol/tests/fixtures/cloud/usage.response.json"
))
.unwrap()
}
fn usage() -> CloudUsageV1 {
decode(fixture()).unwrap()
}
fn now() -> UtcDateTime {
UtcDateTime::parse_from_rfc3339("2026-11-17T12:00:00Z").unwrap()
}
fn enrolled(dir: &std::path::Path, features: &[&str]) -> CloudStore {
let store = CloudStore::at(dir.join("config"), dir.join("cloud"));
let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
"instance_id": "inst_1", "org_id": "org_acme", "org_name": "Platform",
"label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
"enrolled_at": "2026-11-16T12:00:00Z"
}))
.unwrap();
store
.write_config(crate::state::INSTANCE_FILE, &instance)
.unwrap();
crate::session_ref::record(
&store,
"https://cloud.example",
features.iter().map(|f| (*f).to_string()).collect(),
)
.unwrap();
store
}
#[test]
fn status_shows_every_quota_in_its_unit_with_warn_and_full_marked() {
let lines = status_lines(&usage(), None);
assert_eq!(
lines,
[
"Usage: Cloud, Personal",
" storage 34 GiB of 40 GiB ยท warn (85 %); Team gives every seat its own allowance",
" monthly transfer 40 GiB of 40 GiB ยท FULL until 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
" monthly bus messages 1200 of 200000",
" model credit $1.25 of $8.00",
" private vaults 3 of 20",
" hosts registered 2 of 3",
" hosts connected at once 1 of 2",
]
);
for line in &lines {
for word in ["engine", "Queen", "workspace", "instance", "slot"] {
assert!(!line.contains(word), "{line}");
}
}
}
#[test]
fn a_model_credit_of_nothing_is_neither_shown_nor_warned() {
let mut raw = fixture();
raw["quotas"]["model_credit_usd_micros"] =
json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
let usage = decode(raw).unwrap();
let lines = status_lines(&usage, None);
assert!(
lines.iter().all(|l| !l.contains("model credit")),
"{lines:?}"
);
assert_eq!(lines.len(), 7, "{lines:?}");
let rises = rises(&BTreeMap::new(), &usage);
assert!(
rises.iter().all(|l| !l.contains("model credit")),
"{rises:?}"
);
}
#[test]
fn a_model_credit_without_balance_stays_hidden_with_use_reported() {
let mut raw = fixture();
raw["quotas"]["model_credit_usd_micros"] =
json!({"limit": 0, "used": 1_250_000, "state": "full", "next_step": "top_up"});
let usage = decode(raw).unwrap();
let lines = status_lines(&usage, None);
assert!(
lines.iter().all(|l| !l.contains("model credit")),
"{lines:?}"
);
assert!(
rises(&BTreeMap::new(), &usage)
.iter()
.all(|l| !l.contains("model credit"))
);
}
#[test]
fn a_model_credit_that_gets_a_balance_and_runs_out_is_said_then() {
let mut cache = Cache::default();
let mut raw = fixture();
raw["quotas"]["model_credit_usd_micros"] =
json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
let first = note(&mut cache, decode(raw.clone()).unwrap(), now());
assert!(
first.iter().all(|l| !l.contains("model credit")),
"{first:?}"
);
assert!(
!cache.logged.contains_key(BALANCE_RESOURCE),
"a hidden quota is no baseline"
);
raw["quotas"]["model_credit_usd_micros"] =
json!({"limit": 8_000_000, "used": 8_000_000, "state": "full", "next_step": "top_up"});
let topped = note(&mut cache, decode(raw).unwrap(), now());
assert_eq!(
topped
.iter()
.filter(|l| l.contains("all of your model credit is used ($8.00 of $8.00)"))
.count(),
1,
"{topped:?}"
);
}
#[test]
fn a_locked_or_cached_answer_says_so_and_unknown_resources_follow() {
let mut raw = fixture();
raw["plan"] = "locked".into();
raw["read_only"] = true.into();
raw["quotas"]["agent_seats"] = json!({"limit": 4, "used": 4, "state": "full",
"next_step": "contact", "reset_at": "soon"});
let lines = status_lines(&decode(raw).unwrap(), Some("2026-11-17T11:00:00Z"));
assert_eq!(
lines[0],
"Usage: Cloud, no plan (read and export only) (as of 2026-11-17T11:00:00Z)"
);
assert_eq!(
lines.last().unwrap(),
" agent_seats 4 of 4 ยท FULL; contact us to extend your Enterprise contract"
);
}
#[test]
fn a_rise_is_logged_once_and_again_only_after_falling_back() {
let mut cache = Cache::default();
let first = note(&mut cache, usage(), now());
assert_eq!(
first,
[
"Cloud: 85 % of your storage is used (34 GiB of 40 GiB); Team gives every seat its own allowance",
"Cloud: all of your monthly transfer is used (40 GiB of 40 GiB); nothing is charged for more; it frees at 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
]
);
for line in &first {
for word in ["workspace", "engine", "Queen"] {
assert!(!line.contains(word), "{word} in {line}");
}
}
assert!(note(&mut cache, usage(), now()).is_empty());
let mut raw = fixture();
raw["quotas"]["storage_bytes"]["used"] = (40_u64 << 30).into();
raw["quotas"]["storage_bytes"]["state"] = "full".into();
let full = note(&mut cache, decode(raw.clone()).unwrap(), now());
assert_eq!(
full,
[
"Cloud: all of your storage is used (40 GiB of 40 GiB); nothing is charged for more; Team gives every seat its own allowance"
]
);
raw["quotas"]["storage_bytes"]["state"] = "ok".into();
raw["quotas"]["transfer_bytes"]["state"] = "ok".into();
assert!(note(&mut cache, decode(raw).unwrap(), now()).is_empty());
assert_eq!(note(&mut cache, usage(), now()).len(), 2);
}
#[test]
fn model_credit_and_counts_keep_their_units_in_a_rise() {
let credit = CloudQuotaV1 {
limit: 8_000_000,
used: 6_500_000,
reset_at: Some("2026-12-01T00:00:00Z".into()),
state: CloudQuotaStateV1::Warn,
next_step: Some("top_up".into()),
};
assert_eq!(
rise_line("model_credit_usd_micros", &credit),
"Cloud: 81 % of your model credit is used ($6.50 of $8.00); it frees at 2026-12-01T00:00:00Z; a top-up in the Cloud adds more"
);
let seats = CloudQuotaV1 {
limit: 4,
used: 4,
reset_at: None,
state: CloudQuotaStateV1::Full,
next_step: Some("add_seats".into()),
};
assert_eq!(
quota_line("connected_instances", &seats),
" hosts connected at once 4 of 4 ยท FULL; to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine); every seat you add in the Cloud brings its own allowance"
);
}
#[test]
fn host_counts_read_as_the_web_names_them() {
let registered = CloudQuotaV1 {
limit: 3,
used: 3,
reset_at: Some("2026-12-01T00:00:00Z".into()),
state: CloudQuotaStateV1::Full,
next_step: Some("upgrade_team".into()),
};
assert_eq!(
quota_line("registered_instances", ®istered),
" hosts registered 3 of 3 ยท FULL; the next registration frees at 2026-12-01T00:00:00Z; \
to free one, revoke a host you no longer use on the Hosts page; Team gives every seat its own allowance"
);
assert_eq!(
rise_line("registered_instances", ®istered),
"hosts registered 3 of 3: all in use; nothing is charged for more; the next registration frees \
at 2026-12-01T00:00:00Z; to free one, revoke a host you no longer use on the Hosts page; \
Team gives every seat its own allowance"
);
let connected = CloudQuotaV1 {
limit: 2,
used: 2,
reset_at: None,
state: CloudQuotaStateV1::Full,
next_step: None,
};
assert_eq!(
rise_line("connected_instances", &connected),
"hosts connected at once 2 of 2: all in use; nothing is charged for more; \
to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
);
let warn = CloudQuotaV1 {
used: 1,
state: CloudQuotaStateV1::Warn,
..connected
};
assert_eq!(
rise_line("connected_instances", &warn),
"hosts connected at once 1 of 2: 50 % in use"
);
for line in [
quota_line("registered_instances", ®istered),
rise_line("registered_instances", ®istered),
rise_line("connected_instances", &warn),
] {
for word in ["instance", "slot", "seat is free"] {
assert!(!line.contains(word), "{word} in {line}");
}
}
}
#[test]
fn the_cache_survives_a_restart_and_another_server_starts_empty() {
let dir = tempfile::tempdir().unwrap();
let store = enrolled(dir.path(), &[FEATURE_USAGE]);
let mut cache = load_for(&store, "https://cloud.example");
assert!(!note(&mut cache, usage(), now()).is_empty());
save(&store, &cache);
let mut again = load_for(&store, "https://cloud.example");
assert!(
note(&mut again, usage(), now()).is_empty(),
"no repeat after a restart"
);
let other = load_for(&store, "https://other.example");
assert!(other.logged.is_empty() && other.usage.is_none());
}
#[test]
fn the_background_look_is_spaced() {
assert!(due(None, now()));
assert!(!due(Some("2026-11-17T11:55:00Z"), now()));
assert!(due(Some("2026-11-17T11:50:00Z"), now()));
assert!(due(Some("garbage"), now()));
}
#[test]
fn an_older_server_gets_no_request_and_no_status_lines() {
let dir = tempfile::tempdir().unwrap();
let store = enrolled(dir.path(), &["session_ref"]);
assert!(!announced(&store));
assert!(status(&store, &CloudConfig::default(), now()).is_empty());
assert!(!store.data_dir().join(USAGE_FILE).exists());
let store = enrolled(dir.path(), &[FEATURE_USAGE]);
assert!(announced(&store));
let lines = status(&store, &CloudConfig::default(), now());
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(
lines[0].starts_with("Usage: not read now ("),
"{lines:?}"
);
}
}