1use std::collections::BTreeMap;
19use std::time::Duration;
20
21use lean_ctx_protocol::cloud::usage::{CloudQuotaStateV1, CloudQuotaV1, CloudUsageV1};
22use lean_ctx_time::UtcDateTime;
23use serde::{Deserialize, Serialize};
24
25pub use lean_ctx_protocol::cloud::usage::FEATURE_USAGE;
26
27use crate::CloudError;
28use crate::auth::Session;
29use crate::config::CloudConfig;
30use crate::error::{FREE_CONNECTED, FREE_REGISTERED, NextStep, amount_text, quota_label};
31use crate::gateway::BALANCE_RESOURCE;
32use crate::state::{CloudStore, write_private};
33
34const USAGE_FILE: &str = "usage.json";
36
37pub const REFRESH_EVERY: Duration = Duration::from_mins(10);
39
40const ORDER: [&str; 7] = [
42 "storage_bytes",
43 "transfer_bytes",
44 "bus_messages",
45 BALANCE_RESOURCE,
46 "private_vaults",
47 "registered_instances",
48 "connected_instances",
49];
50
51const LABEL_WIDTH: usize = 24;
54
55#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(default)]
57struct Cache {
58 server: String,
60 fetched_at: Option<String>,
62 tried_at: Option<String>,
64 usage: Option<CloudUsageV1>,
65 logged: BTreeMap<String, CloudQuotaStateV1>,
67}
68
69fn load(store: &CloudStore) -> Cache {
70 std::fs::read(store.data_dir().join(USAGE_FILE))
71 .ok()
72 .and_then(|b| serde_json::from_slice(&b).ok())
73 .unwrap_or_default()
74}
75
76fn save(store: &CloudStore, cache: &Cache) {
77 if let Ok(bytes) = serde_json::to_vec_pretty(cache) {
78 let _ = write_private(store.data_dir(), USAGE_FILE, &bytes);
79 }
80}
81
82fn load_for(store: &CloudStore, server: &str) -> Cache {
84 let cache = load(store);
85 if cache.server == server {
86 cache
87 } else {
88 Cache {
89 server: server.to_string(),
90 ..Cache::default()
91 }
92 }
93}
94
95fn stamp(at: UtcDateTime) -> String {
96 at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
97}
98
99#[must_use]
101pub fn announced(store: &CloudStore) -> bool {
102 crate::session_ref::announced(store, FEATURE_USAGE)
103}
104
105pub fn fetch(session: &Session) -> Result<Option<CloudUsageV1>, CloudError> {
107 if !announced(&session.store) {
108 return Ok(None);
109 }
110 let answer = session.with_client(|client| client.get("/usage"))?;
111 decode(answer).map(Some)
112}
113
114fn decode(answer: serde_json::Value) -> Result<CloudUsageV1, CloudError> {
115 let usage: CloudUsageV1 =
116 serde_json::from_value(answer).map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
117 usage
118 .validate()
119 .map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
120 Ok(usage)
121}
122
123pub(crate) fn background(session: &Session, now: UtcDateTime) {
130 if !announced(&session.store) {
131 return;
132 }
133 let store = &session.store;
134 let mut cache = load_for(store, &session.instance.url);
135 if !due(cache.tried_at.as_deref(), now) {
136 return;
137 }
138 cache.tried_at = Some(stamp(now));
139 match fetch(session) {
140 Ok(Some(usage)) => {
141 for line in note(&mut cache, usage, now) {
142 tracing::warn!("{line}");
143 }
144 }
145 Ok(None) => {}
146 Err(error) => tracing::debug!("cloud: usage not read: {error}"),
147 }
148 save(store, &cache);
149}
150
151fn due(tried_at: Option<&str>, now: UtcDateTime) -> bool {
153 tried_at
154 .and_then(|t| UtcDateTime::parse_from_rfc3339(t).ok())
155 .is_none_or(|at| {
156 (now - at)
157 .to_std()
158 .map_or(true, |since| since >= REFRESH_EVERY)
159 })
160}
161
162fn note(cache: &mut Cache, usage: CloudUsageV1, now: UtcDateTime) -> Vec<String> {
167 let lines = rises(&cache.logged, &usage);
168 cache.logged = ordered(&usage)
169 .map(|(r, q)| (r.to_owned(), q.state))
170 .collect();
171 cache.usage = Some(usage);
172 cache.fetched_at = Some(stamp(now));
173 lines
174}
175
176#[must_use]
180pub fn rises(seen: &BTreeMap<String, CloudQuotaStateV1>, usage: &CloudUsageV1) -> Vec<String> {
181 ordered(usage)
182 .filter(|(r, q)| q.state.level() > seen.get(*r).map_or(0, |s| s.level()))
183 .map(|(r, q)| rise_line(r, q))
184 .collect()
185}
186
187#[must_use]
190pub fn rise_line(resource: &str, q: &CloudQuotaV1) -> String {
191 let what = quota_label(resource);
192 if is_host_count(resource) {
193 return host_rise_line(what, resource, q);
194 }
195 let amounts = format!(
196 "{} of {}",
197 amount_text(resource, q.used),
198 amount_text(resource, q.limit)
199 );
200 let mut line = if q.state == CloudQuotaStateV1::Full {
201 format!("Cloud: all of your {what} is used ({amounts}); nothing is charged for more")
202 } else {
203 format!("Cloud: {} % of your {what} is used ({amounts})", percent(q))
204 };
205 if let Some(at) = reset_text(q) {
206 line.push_str(&format!("; it frees at {at}"));
207 }
208 if let Some(hint) = hint(q) {
209 line.push_str("; ");
210 line.push_str(hint);
211 }
212 line
213}
214
215fn is_host_count(resource: &str) -> bool {
217 matches!(resource, "registered_instances" | "connected_instances")
218}
219
220fn host_rise_line(what: &str, resource: &str, q: &CloudQuotaV1) -> String {
223 let head = format!("{what} {} of {}", q.used, q.limit);
224 if q.state == CloudQuotaStateV1::Full {
225 format!(
226 "{head}: all in use; nothing is charged for more{}",
227 host_full_tail(resource, q)
228 )
229 } else {
230 let mut line = format!("{head}: {} % in use", percent(q));
231 if let Some(hint) = hint(q) {
232 line.push_str("; ");
233 line.push_str(hint);
234 }
235 line
236 }
237}
238
239fn host_full_tail(resource: &str, q: &CloudQuotaV1) -> String {
242 let mut tail = String::new();
243 if resource == "registered_instances" {
244 if let Some(at) = reset_text(q) {
245 tail.push_str(&format!("; the next registration frees at {at}"));
246 }
247 tail.push_str("; ");
248 tail.push_str(FREE_REGISTERED);
249 } else {
250 tail.push_str("; ");
251 tail.push_str(FREE_CONNECTED);
252 }
253 if let Some(hint) = hint(q) {
254 tail.push_str("; ");
255 tail.push_str(hint);
256 }
257 tail
258}
259
260pub fn status(store: &CloudStore, config: &CloudConfig, now: UtcDateTime) -> Vec<String> {
267 if !announced(store) || !matches!(store.instance(), Ok(Some(_))) {
268 return Vec::new();
269 }
270 match read(store, config, now) {
271 Ok(Some(r)) if r.live => status_lines(&r.usage, None),
272 Ok(Some(r)) => status_lines(&r.usage, r.as_of.as_deref()),
273 Ok(None) => Vec::new(),
274 Err(error) => vec![format!(
275 "Usage: not read now ({})",
276 why_not_read(&error)
277 )],
278 }
279}
280
281fn why_not_read(error: &CloudError) -> &'static str {
284 match error {
285 CloudError::Offline(_) => "The Cloud did not answer",
286 CloudError::NotConnected => "this machine is not connected; run `lean-ctx cloud connect`",
287 CloudError::Unauthorized | CloudError::LeaseLapsed | CloudError::Revoked(_) => {
288 "The Cloud no longer accepts this machine; run `lean-ctx cloud connect` again"
289 }
290 CloudError::Forbidden | CloudError::PlanRequired(_) => {
291 "your role or plan does not show usage"
292 }
293 _ if error.is_transient() => "The Cloud is busy; try again shortly",
294 _ => "The Cloud refused the request",
295 }
296}
297
298#[derive(Debug, Clone, PartialEq)]
300pub struct UsageRead {
301 pub usage: CloudUsageV1,
302 pub as_of: Option<String>,
304 pub live: bool,
306}
307
308pub fn read(
312 store: &CloudStore,
313 config: &CloudConfig,
314 now: UtcDateTime,
315) -> Result<Option<UsageRead>, CloudError> {
316 if !announced(store) {
317 return Ok(None);
318 }
319 let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
320 let live = crate::scheduler::connected_session(store, config).and_then(|s| fetch(&s));
321 let mut cache = load_for(store, &instance.url);
322 match live {
323 Ok(Some(usage)) => {
324 cache.usage = Some(usage.clone());
326 cache.fetched_at = Some(stamp(now));
327 save(store, &cache);
328 Ok(Some(UsageRead {
329 usage,
330 as_of: cache.fetched_at,
331 live: true,
332 }))
333 }
334 Ok(None) => Ok(None),
335 Err(error) => match cache.usage {
336 Some(usage) => Ok(Some(UsageRead {
337 usage,
338 as_of: cache.fetched_at,
339 live: false,
340 })),
341 None => Err(error),
342 },
343 }
344}
345
346#[must_use]
349pub fn status_lines(usage: &CloudUsageV1, as_of: Option<&str>) -> Vec<String> {
350 let plan = match usage.plan.as_str() {
351 "personal" => "Personal",
352 "team" => "Team",
353 "enterprise" => "Enterprise",
354 _ => "no plan",
355 };
356 let mut head = format!("Usage: Cloud, {plan}");
357 if usage.read_only || usage.plan == "locked" {
358 head.push_str(" (read and export only)");
359 }
360 if let Some(at) = as_of {
361 head.push_str(&format!(" (as of {at})"));
362 }
363 let mut lines = vec![head];
364 lines.extend(ordered(usage).map(|(r, q)| quota_line(r, q)));
365 lines
366}
367
368#[must_use]
370pub fn quota_line(resource: &str, q: &CloudQuotaV1) -> String {
371 let mut line = format!(
372 " {:<LABEL_WIDTH$}{} of {}",
373 quota_label(resource),
374 amount_text(resource, q.used),
375 amount_text(resource, q.limit)
376 );
377 match q.state {
378 CloudQuotaStateV1::Full if is_host_count(resource) => {
379 line.push_str(" · FULL");
380 line.push_str(&host_full_tail(resource, q));
381 return line;
382 }
383 CloudQuotaStateV1::Full => {
384 line.push_str(" · FULL");
385 if let Some(at) = reset_text(q) {
386 line.push_str(&format!(" until {at}"));
387 }
388 }
389 CloudQuotaStateV1::Warn => line.push_str(&format!(" · warn ({} %)", percent(q))),
390 CloudQuotaStateV1::Ok | CloudQuotaStateV1::Unknown => return line,
391 }
392 if let Some(hint) = hint(q) {
393 line.push_str("; ");
394 line.push_str(hint);
395 }
396 line
397}
398
399fn ordered(usage: &CloudUsageV1) -> impl Iterator<Item = (&str, &CloudQuotaV1)> {
405 let known = ORDER.iter().filter_map(|r| usage.quotas.get_key_value(*r));
406 let rest = usage
407 .quotas
408 .iter()
409 .filter(|(r, _)| !ORDER.contains(&r.as_str()));
410 known
411 .chain(rest)
412 .map(|(r, q)| (r.as_str(), q))
413 .filter(|(r, q)| !(*r == BALANCE_RESOURCE && q.limit == 0))
414}
415
416fn percent(q: &CloudQuotaV1) -> u128 {
418 if q.limit == 0 {
419 return 100;
420 }
421 u128::from(q.used) * 100 / u128::from(q.limit)
422}
423
424fn hint(q: &CloudQuotaV1) -> Option<&'static str> {
426 NextStep::of_wire(q.next_step.as_deref()).and_then(NextStep::hint)
427}
428
429fn reset_text(q: &CloudQuotaV1) -> Option<String> {
431 let at = UtcDateTime::parse_from_rfc3339(q.reset_at.as_deref()?).ok()?;
432 Some(stamp(at))
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use serde_json::json;
439
440 #[test]
441 fn order_lists_the_balance_resource_from_the_gateway() {
442 assert!(ORDER.contains(&BALANCE_RESOURCE));
443 assert_eq!(BALANCE_RESOURCE, "model_credit_usd_micros");
444 }
445
446 fn fixture() -> serde_json::Value {
447 serde_json::from_str(include_str!(
448 "../../lean-ctx-protocol/tests/fixtures/cloud/usage.response.json"
449 ))
450 .unwrap()
451 }
452
453 fn usage() -> CloudUsageV1 {
454 decode(fixture()).unwrap()
455 }
456
457 fn now() -> UtcDateTime {
458 UtcDateTime::parse_from_rfc3339("2026-11-17T12:00:00Z").unwrap()
459 }
460
461 fn enrolled(dir: &std::path::Path, features: &[&str]) -> CloudStore {
462 let store = CloudStore::at(dir.join("config"), dir.join("cloud"));
463 let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
464 "instance_id": "inst_1", "org_id": "org_acme", "org_name": "Platform",
465 "label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
466 "enrolled_at": "2026-11-16T12:00:00Z"
467 }))
468 .unwrap();
469 store
470 .write_config(crate::state::INSTANCE_FILE, &instance)
471 .unwrap();
472 crate::session_ref::record(
473 &store,
474 "https://cloud.example",
475 features.iter().map(|f| (*f).to_string()).collect(),
476 )
477 .unwrap();
478 store
479 }
480
481 #[test]
482 fn status_shows_every_quota_in_its_unit_with_warn_and_full_marked() {
483 let lines = status_lines(&usage(), None);
484 assert_eq!(
485 lines,
486 [
487 "Usage: Cloud, Personal",
488 " storage 34 GiB of 40 GiB · warn (85 %); Team gives every seat its own allowance",
489 " monthly transfer 40 GiB of 40 GiB · FULL until 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
490 " monthly bus messages 1200 of 200000",
491 " model credit $1.25 of $8.00",
492 " private vaults 3 of 20",
493 " hosts registered 2 of 3",
494 " hosts connected at once 1 of 2",
495 ]
496 );
497 for line in &lines {
498 for word in ["engine", "Queen", "workspace", "instance", "slot"] {
499 assert!(!line.contains(word), "{line}");
500 }
501 }
502 }
503
504 #[test]
505 fn a_model_credit_of_nothing_is_neither_shown_nor_warned() {
506 let mut raw = fixture();
507 raw["quotas"]["model_credit_usd_micros"] =
508 json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
509 let usage = decode(raw).unwrap();
510 let lines = status_lines(&usage, None);
511 assert!(
512 lines.iter().all(|l| !l.contains("model credit")),
513 "{lines:?}"
514 );
515 assert_eq!(lines.len(), 7, "{lines:?}");
516 let rises = rises(&BTreeMap::new(), &usage);
517 assert!(
518 rises.iter().all(|l| !l.contains("model credit")),
519 "{rises:?}"
520 );
521 }
522
523 #[test]
524 fn a_model_credit_without_balance_stays_hidden_with_use_reported() {
525 let mut raw = fixture();
526 raw["quotas"]["model_credit_usd_micros"] =
527 json!({"limit": 0, "used": 1_250_000, "state": "full", "next_step": "top_up"});
528 let usage = decode(raw).unwrap();
529 let lines = status_lines(&usage, None);
530 assert!(
531 lines.iter().all(|l| !l.contains("model credit")),
532 "{lines:?}"
533 );
534 assert!(
535 rises(&BTreeMap::new(), &usage)
536 .iter()
537 .all(|l| !l.contains("model credit"))
538 );
539 }
540
541 #[test]
542 fn a_model_credit_that_gets_a_balance_and_runs_out_is_said_then() {
543 let mut cache = Cache::default();
544 let mut raw = fixture();
545 raw["quotas"]["model_credit_usd_micros"] =
546 json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
547 let first = note(&mut cache, decode(raw.clone()).unwrap(), now());
548 assert!(
549 first.iter().all(|l| !l.contains("model credit")),
550 "{first:?}"
551 );
552 assert!(
553 !cache.logged.contains_key(BALANCE_RESOURCE),
554 "a hidden quota is no baseline"
555 );
556 raw["quotas"]["model_credit_usd_micros"] =
558 json!({"limit": 8_000_000, "used": 8_000_000, "state": "full", "next_step": "top_up"});
559 let topped = note(&mut cache, decode(raw).unwrap(), now());
560 assert_eq!(
561 topped
562 .iter()
563 .filter(|l| l.contains("all of your model credit is used ($8.00 of $8.00)"))
564 .count(),
565 1,
566 "{topped:?}"
567 );
568 }
569
570 #[test]
571 fn a_locked_or_cached_answer_says_so_and_unknown_resources_follow() {
572 let mut raw = fixture();
573 raw["plan"] = "locked".into();
574 raw["read_only"] = true.into();
575 raw["quotas"]["agent_seats"] = json!({"limit": 4, "used": 4, "state": "full",
576 "next_step": "contact", "reset_at": "soon"});
577 let lines = status_lines(&decode(raw).unwrap(), Some("2026-11-17T11:00:00Z"));
578 assert_eq!(
579 lines[0],
580 "Usage: Cloud, no plan (read and export only) (as of 2026-11-17T11:00:00Z)"
581 );
582 assert_eq!(
584 lines.last().unwrap(),
585 " agent_seats 4 of 4 · FULL; contact us to extend your Enterprise contract"
586 );
587 }
588
589 #[test]
590 fn a_rise_is_logged_once_and_again_only_after_falling_back() {
591 let mut cache = Cache::default();
592 let first = note(&mut cache, usage(), now());
593 assert_eq!(
594 first,
595 [
596 "Cloud: 85 % of your storage is used (34 GiB of 40 GiB); Team gives every seat its own allowance",
597 "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",
598 ]
599 );
600 for line in &first {
601 for word in ["workspace", "engine", "Queen"] {
602 assert!(!line.contains(word), "{word} in {line}");
603 }
604 }
605 assert!(note(&mut cache, usage(), now()).is_empty());
607 let mut raw = fixture();
609 raw["quotas"]["storage_bytes"]["used"] = (40_u64 << 30).into();
610 raw["quotas"]["storage_bytes"]["state"] = "full".into();
611 let full = note(&mut cache, decode(raw.clone()).unwrap(), now());
612 assert_eq!(
613 full,
614 [
615 "Cloud: all of your storage is used (40 GiB of 40 GiB); nothing is charged for more; Team gives every seat its own allowance"
616 ]
617 );
618 raw["quotas"]["storage_bytes"]["state"] = "ok".into();
620 raw["quotas"]["transfer_bytes"]["state"] = "ok".into();
621 assert!(note(&mut cache, decode(raw).unwrap(), now()).is_empty());
622 assert_eq!(note(&mut cache, usage(), now()).len(), 2);
623 }
624
625 #[test]
626 fn model_credit_and_counts_keep_their_units_in_a_rise() {
627 let credit = CloudQuotaV1 {
628 limit: 8_000_000,
629 used: 6_500_000,
630 reset_at: Some("2026-12-01T00:00:00Z".into()),
631 state: CloudQuotaStateV1::Warn,
632 next_step: Some("top_up".into()),
633 };
634 assert_eq!(
635 rise_line("model_credit_usd_micros", &credit),
636 "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"
637 );
638 let seats = CloudQuotaV1 {
639 limit: 4,
640 used: 4,
641 reset_at: None,
642 state: CloudQuotaStateV1::Full,
643 next_step: Some("add_seats".into()),
644 };
645 assert_eq!(
646 quota_line("connected_instances", &seats),
647 " 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"
648 );
649 }
650
651 #[test]
655 fn host_counts_read_as_the_web_names_them() {
656 let registered = CloudQuotaV1 {
657 limit: 3,
658 used: 3,
659 reset_at: Some("2026-12-01T00:00:00Z".into()),
660 state: CloudQuotaStateV1::Full,
661 next_step: Some("upgrade_team".into()),
662 };
663 assert_eq!(
664 quota_line("registered_instances", ®istered),
665 " hosts registered 3 of 3 · FULL; the next registration frees at 2026-12-01T00:00:00Z; \
666 to free one, revoke a host you no longer use on the Hosts page; Team gives every seat its own allowance"
667 );
668 assert_eq!(
669 rise_line("registered_instances", ®istered),
670 "hosts registered 3 of 3: all in use; nothing is charged for more; the next registration frees \
671 at 2026-12-01T00:00:00Z; to free one, revoke a host you no longer use on the Hosts page; \
672 Team gives every seat its own allowance"
673 );
674 let connected = CloudQuotaV1 {
675 limit: 2,
676 used: 2,
677 reset_at: None,
678 state: CloudQuotaStateV1::Full,
679 next_step: None,
680 };
681 assert_eq!(
682 rise_line("connected_instances", &connected),
683 "hosts connected at once 2 of 2: all in use; nothing is charged for more; \
684 to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
685 );
686 let warn = CloudQuotaV1 {
687 used: 1,
688 state: CloudQuotaStateV1::Warn,
689 ..connected
690 };
691 assert_eq!(
692 rise_line("connected_instances", &warn),
693 "hosts connected at once 1 of 2: 50 % in use"
694 );
695 for line in [
696 quota_line("registered_instances", ®istered),
697 rise_line("registered_instances", ®istered),
698 rise_line("connected_instances", &warn),
699 ] {
700 for word in ["instance", "slot", "seat is free"] {
702 assert!(!line.contains(word), "{word} in {line}");
703 }
704 }
705 }
706
707 #[test]
708 fn the_cache_survives_a_restart_and_another_server_starts_empty() {
709 let dir = tempfile::tempdir().unwrap();
710 let store = enrolled(dir.path(), &[FEATURE_USAGE]);
711 let mut cache = load_for(&store, "https://cloud.example");
712 assert!(!note(&mut cache, usage(), now()).is_empty());
713 save(&store, &cache);
714 let mut again = load_for(&store, "https://cloud.example");
715 assert!(
716 note(&mut again, usage(), now()).is_empty(),
717 "no repeat after a restart"
718 );
719 let other = load_for(&store, "https://other.example");
720 assert!(other.logged.is_empty() && other.usage.is_none());
721 }
722
723 #[test]
724 fn the_background_look_is_spaced() {
725 assert!(due(None, now()));
726 assert!(!due(Some("2026-11-17T11:55:00Z"), now()));
727 assert!(due(Some("2026-11-17T11:50:00Z"), now()));
728 assert!(due(Some("garbage"), now()));
729 }
730
731 #[test]
732 fn an_older_server_gets_no_request_and_no_status_lines() {
733 let dir = tempfile::tempdir().unwrap();
734 let store = enrolled(dir.path(), &["session_ref"]);
738 assert!(!announced(&store));
739 assert!(status(&store, &CloudConfig::default(), now()).is_empty());
740 assert!(!store.data_dir().join(USAGE_FILE).exists());
741 let store = enrolled(dir.path(), &[FEATURE_USAGE]);
743 assert!(announced(&store));
744 let lines = status(&store, &CloudConfig::default(), now());
745 assert_eq!(lines.len(), 1, "{lines:?}");
746 assert!(
747 lines[0].starts_with("Usage: not read now ("),
748 "{lines:?}"
749 );
750 }
751}