Skip to main content

lean_ctx_cloud/
status.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local, network-free Cloud status: the cockpit's `cloud status --json`
3//! shape and the human report behind `lean-ctx cloud status`.
4
5use crate::CloudConfigExt as _;
6use lean_ctx_time::UtcDateTime;
7
8use super::auth::Session;
9use super::config::CloudConfig;
10use super::state::{ActivityRecord, CloudStore, InstanceRecord};
11use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, LeaseState};
12use lean_ctx_protocol::cloud::status::{
13    CloudBusControlsInactiveV1, CloudCliStatusV1, CloudStatusBusControlV1, CloudStatusDraftsV1,
14    CloudStatusFilterPackV1, CloudStatusInstanceV1, CloudStatusOrgV1,
15};
16
17/// Everything `lean-ctx cloud status` shows.
18#[derive(Debug, Clone)]
19pub struct CloudStatusReport {
20    pub url: String,
21    pub enabled: bool,
22    pub instance: Option<InstanceRecord>,
23    pub lease: Option<CloudLeaseV1>,
24    pub lease_state: Option<LeaseState>,
25    /// Why the stored enrollment cannot be used, if it cannot.
26    pub problem: Option<String>,
27    pub activity: ActivityRecord,
28    /// Queued drafts `(outbox id, summary, last error)`.
29    pub drafts_pending: Vec<super::knowledge::pull::DraftLine>,
30    /// Drafts Cloud refused for good; kept until removed.
31    pub drafts_failed: Vec<super::knowledge::pull::DraftLine>,
32    /// The last verified policy bundle (and why a newer one was refused).
33    pub policy: super::policy::PolicyState,
34    /// Engine metrics v2 (`None`: no usable lease).
35    pub metrics_v2: Option<super::metrics_v2::upload::MetricsV2Status>,
36    /// Why receipts are not sent (`None`: sent, or no usable lease).
37    pub receipts_off: Option<&'static str>,
38    /// Receipts waiting in the outbox.
39    pub receipts_queued: usize,
40    /// Bus controls in force (filled by the bus control module).
41    pub bus_controls: Vec<CloudStatusBusControlV1>,
42    /// Why recorded bus controls do not apply right now.
43    pub bus_controls_inactive: Option<CloudBusControlsInactiveV1>,
44    /// The Cloud root is `[cloud] root_key`, vouched for by nobody.
45    pub unvouched_root: bool,
46    /// Durable workers in the book (Cloud allows
47    /// [`WORKER_CAP`](super::workers::attach::WORKER_CAP) per instance).
48    pub workers: usize,
49    /// Workers the book gave up that Cloud has not retired yet.
50    pub workers_retiring: usize,
51    /// The machine's managed configuration: each member and its carrier.
52    pub managed: Option<lean_ctx_protocol::cloud::status::CloudStatusManagedV1>,
53}
54
55impl CloudStatusReport {
56    pub fn connected(&self) -> bool {
57        self.instance.is_some()
58            && self.problem.is_none()
59            && matches!(
60                self.lease_state,
61                Some(LeaseState::Valid | LeaseState::Grace)
62            )
63    }
64
65    /// The cockpit shape: exactly six fields, nulls printed.
66    pub fn cli_status(&self) -> CloudCliStatusV1 {
67        let connected = self.connected();
68        CloudCliStatusV1 {
69            available: true,
70            connected,
71            instance: self.instance.as_ref().map(|i| CloudStatusInstanceV1 {
72                id: i.instance_id.clone(),
73                label: i.label.clone(),
74            }),
75            org: self.instance.as_ref().map(|i| CloudStatusOrgV1 {
76                name: i.org_name.clone(),
77            }),
78            last_seen: self
79                .activity
80                .last_seen
81                .as_deref()
82                .and_then(|t| lean_ctx_protocol::UtcTimestamp::new(t).ok()),
83            url: self.url.clone(),
84            drafts: CloudStatusDraftsV1 {
85                queued: u32::try_from(self.drafts_pending.len()).unwrap_or(u32::MAX),
86                refused: u32::try_from(self.drafts_failed.len()).unwrap_or(u32::MAX),
87            },
88            filter_packs: self
89                .policy
90                .filter_packs
91                .iter()
92                .map(|(pack_id, version)| CloudStatusFilterPackV1 {
93                    pack_id: pack_id.clone(),
94                    version: *version,
95                })
96                .collect(),
97            policy_refusal: self.policy.last_refusal.clone(),
98            web_url: Some(
99                self.instance
100                    .as_ref()
101                    .and_then(|i| i.web_url.clone())
102                    .unwrap_or_else(|| self.url.clone()),
103            ),
104            bus_controls: self.bus_controls.clone(),
105            bus_controls_inactive: self.bus_controls_inactive,
106            metrics_v2: self
107                .metrics_v2
108                .as_ref()
109                .map(super::metrics_v2::upload::MetricsV2Status::wire),
110            // Per checkout: the CLI fills it for the project it runs in
111            // ([`super::resolution::Stale::wire`]).
112            vault_mismatch: None,
113            managed: self.managed.clone(),
114            // From the Cloud, not local state: the CLI fills them
115            // ([`super::team_stop::apply`]).
116            team_stop: None,
117            role: None,
118            org_slug: None,
119            company: None,
120            step_up_url: None,
121        }
122    }
123}
124
125/// Build the report from local state at `local_now`. Never touches the network.
126pub fn report(
127    store: &CloudStore,
128    config: &CloudConfig,
129    local_now: UtcDateTime,
130) -> CloudStatusReport {
131    let instance = store.instance().ok().flatten();
132    let url = instance
133        .as_ref()
134        .map(|i| i.url.clone())
135        .or_else(|| config.origin().ok())
136        .unwrap_or_else(|| lean_ctx_protocol::cloud::CLOUD_DEFAULT_URL.to_string());
137    let mut report = CloudStatusReport {
138        url: url.clone(),
139        enabled: config.enabled.unwrap_or(true),
140        instance: instance.clone(),
141        lease: None,
142        lease_state: None,
143        problem: None,
144        activity: store.activity(),
145        drafts_pending: Vec::new(),
146        drafts_failed: Vec::new(),
147        policy: super::policy::load_state(store.data_dir()),
148        metrics_v2: None,
149        receipts_off: None,
150        receipts_queued: super::outbox::Outbox::at(store.data_dir())
151            .depth(super::outbox::CHANNEL_RECEIPTS)
152            .pending,
153        bus_controls: Vec::new(),
154        bus_controls_inactive: None,
155        unvouched_root: super::root_cert::unvouched(store, config),
156        workers: 0,
157        workers_retiring: 0,
158        managed: lean_ctx::core::config::managed::current().map(|managed| managed.wire()),
159    };
160    if let Some(instance) = &instance {
161        let id = &instance.instance_id;
162        report.workers = super::workers::attach::list(store, id).map_or(0, |w| w.len());
163        report.workers_retiring = super::workers::attach::retired(store, id).map_or(0, |r| r.len());
164    }
165    (report.drafts_pending, report.drafts_failed) =
166        super::knowledge::pull::draft_listing(store.data_dir());
167    (report.bus_controls, report.bus_controls_inactive) =
168        super::bus::control::status_view(store, local_now);
169    if instance.is_none() {
170        return report;
171    }
172    // A recorded revocation is the whole story: no lease is shown as valid.
173    let revoked = instance
174        .as_ref()
175        .and_then(|i| super::revoked::recorded(store, i));
176    let session = match revoked {
177        Some(revoked) => Err(revoked),
178        None => super::root_cert::trust_root(store, config, &url)
179            .and_then(|root| Session::load(store.clone(), root)),
180    };
181    match session {
182        Ok(session) => {
183            report.lease_state = Some(session.lease.state_at(local_now));
184            report.metrics_v2 = Some(super::metrics_v2::upload::status(
185                store,
186                config,
187                &session.instance,
188                &session.lease.lease,
189                local_now,
190            ));
191            report.receipts_off =
192                super::receipts::status(store, config, &session.instance, &session.lease.lease);
193            report.lease = Some(session.lease.lease);
194        }
195        Err(error) => report.problem = Some(error.to_string()),
196    }
197    report
198}
199
200/// When the one-step trial of `lease` ends, in second-precision `Z` form:
201/// `None` without a running trial (or with a time that is not RFC 3339).
202#[must_use]
203pub fn trial_ends_at(lease: &CloudLeaseV1) -> Option<String> {
204    super::error::wire_time(lease.trial_ends_at.as_deref())
205}
206
207/// `cloud status`'s trial line, e.g. `Trial ends 2026-12-02 10:00 UTC`.
208#[must_use]
209pub fn trial_line(lease: &CloudLeaseV1) -> Option<String> {
210    let at = trial_ends_at(lease)?;
211    Some(format!("Trial ends {} {} UTC", &at[..10], &at[11..16]))
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    fn lease(trial_ends_at: Option<&str>) -> CloudLeaseV1 {
219        let envelope: serde_json::Value = serde_json::from_str(
220            &std::fs::read_to_string(concat!(
221                env!("CARGO_MANIFEST_DIR"),
222                "/../lean-ctx-protocol/tests/fixtures/cloud/lease_envelope.response.json"
223            ))
224            .unwrap(),
225        )
226        .unwrap();
227        let mut value = envelope["lease"].clone();
228        if let Some(at) = trial_ends_at {
229            value["trial_ends_at"] = at.into();
230        }
231        serde_json::from_value(value).unwrap()
232    }
233
234    #[test]
235    fn trial_line_shows_only_while_a_trial_runs() {
236        assert_eq!(trial_line(&lease(None)), None);
237        assert_eq!(trial_ends_at(&lease(None)), None);
238        let running = lease(Some("2026-12-02T11:00:00+01:00"));
239        assert_eq!(
240            trial_ends_at(&running).as_deref(),
241            Some("2026-12-02T10:00:00Z")
242        );
243        assert_eq!(
244            trial_line(&running).as_deref(),
245            Some("Trial ends 2026-12-02 10:00 UTC")
246        );
247        assert_eq!(trial_line(&lease(Some("next week"))), None);
248    }
249
250    #[test]
251    fn a_fresh_machine_reports_available_but_not_connected() {
252        let dir = tempfile::tempdir().unwrap();
253        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
254        let report = report(&store, &CloudConfig::default(), UtcDateTime::now());
255        assert_eq!(
256            serde_json::to_value(report.cli_status()).unwrap(),
257            serde_json::to_value(CloudCliStatusV1::not_connected(None)).unwrap()
258        );
259    }
260}