use std::collections::BTreeMap;
use serde::Serialize;
use lean_ctx_hive::status::HiveStatusReport;
use lean_ctx_protocol::hive::lease::{HivePlan, HiveRight, LeaseState};
use lean_ctx_protocol::hive::status::HiveCliStatusV1;
pub(crate) const OPT_IN: &str = "local-read/1";
pub(crate) fn opted_in(args: &[String]) -> bool {
args.iter()
.any(|a| a.strip_prefix("--contract=") == Some(OPT_IN))
|| args
.windows(2)
.any(|w| w[0] == "--contract" && w[1] == OPT_IN)
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub(crate) struct CaptureRow {
pub considered: u64,
pub captured: u64,
pub rejected: BTreeMap<String, u64>,
}
#[derive(Debug, Serialize)]
pub(crate) struct LocalReadStatus {
pub contract: &'static str,
pub kind: &'static str,
#[serde(flatten)]
pub cockpit: HiveCliStatusV1,
pub plan: Option<HivePlan>,
pub lease_state: Option<LeaseState>,
pub lease_valid_until: Option<String>,
pub lease_grace_until: Option<String>,
pub rights: Vec<HiveRight>,
pub locked: Option<String>,
pub trial_ends_at: Option<String>,
pub capture: Option<CaptureRow>,
pub enabled: bool,
pub problem: Option<String>,
pub workspace: Option<WorkspaceRow>,
pub project: Option<ProjectRow>,
pub capture_gate: CaptureGateRow,
pub trial: TrialRow,
pub seats_limit: Option<u32>,
pub org_settings: Option<OrgSettingsRow>,
pub receipts: ReceiptsRow,
pub workers: WorkersRow,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct WorkspaceRow {
pub org_id: String,
pub name: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct ProjectRow {
pub root: String,
pub vault: Option<String>,
pub linked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct CaptureGateRow {
pub enabled: bool,
pub version: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct TrialRow {
pub active: Option<bool>,
pub ends_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct OrgSettingsRow {
pub metrics_upload: bool,
pub receipts_upload: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct ReceiptsRow {
pub queued: usize,
pub off: Option<&'static str>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct WorkersRow {
pub active: usize,
pub retiring: usize,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct LocalFacts {
pub capture: Option<CaptureRow>,
pub project_root: Option<String>,
pub linked_vault: Option<String>,
pub auto_capture: bool,
}
pub(crate) fn capture_counts(counts: &lean_ctx_hive::capture::CountsFile) -> Option<CaptureRow> {
if counts.is_empty() {
return None;
}
let mut out = CaptureRow::default();
for run in counts.values() {
out.considered += u64::from(run.considered);
out.captured += u64::from(run.captured);
for (reason, n) in &run.rejected {
let reason = serde_json::to_value(reason)
.ok()
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_else(|| "unknown".into());
*out.rejected.entry(reason).or_default() += u64::from(*n);
}
}
Some(out)
}
pub(crate) fn of_report(report: &HiveStatusReport, facts: LocalFacts) -> LocalReadStatus {
let lease = report.lease.as_ref();
let locked = report.activity.locked.clone();
LocalReadStatus {
contract: super::CONTRACT,
kind: "hive.status",
cockpit: report.cli_status(),
plan: lease.map(|l| l.plan),
lease_state: lease.and(report.lease_state),
lease_valid_until: lease.map(|l| l.expires_at.as_str().to_owned()),
lease_grace_until: lease.map(|l| l.grace_until.as_str().to_owned()),
rights: lease.map_or_else(Vec::new, |l| {
l.rights
.iter()
.copied()
.filter(|r| *r != HiveRight::Unknown)
.collect()
}),
trial_ends_at: None,
capture: facts.capture,
enabled: report.enabled,
problem: report.problem.clone(),
workspace: lease.map(|l| WorkspaceRow {
org_id: l.org_id.clone(),
name: report.instance.as_ref().map(|i| i.org_name.clone()),
}),
project: facts.project_root.map(|root| ProjectRow {
root,
linked: facts.linked_vault.is_some(),
vault: facts.linked_vault,
}),
capture_gate: CaptureGateRow {
enabled: facts.auto_capture,
version: lean_ctx_hive::capture::GATE_VERSION,
},
trial: TrialRow {
active: None,
ends_at: None,
},
locked,
seats_limit: lease.map(|l| l.seats_limit),
org_settings: lease.and_then(|l| l.org_settings).map(|s| OrgSettingsRow {
metrics_upload: s.metrics_upload,
receipts_upload: s.receipts_upload,
}),
receipts: ReceiptsRow {
queued: report.receipts_queued,
off: report.receipts_off,
},
workers: WorkersRow {
active: report.workers,
retiring: report.workers_retiring,
},
}
}
pub(crate) fn print(
report: &HiveStatusReport,
data_dir: &std::path::Path,
auto_capture: bool,
args: &[String],
) {
let root = super::super::common::detect_project_root(args);
let project = std::path::Path::new(&root);
let project_root = (project.is_dir()
&& !lean_ctx::core::pathutil::is_broad_or_unsafe_root(project))
.then_some(root);
super::print(&of_state(report, data_dir, auto_capture, project_root));
}
fn of_state(
report: &HiveStatusReport,
data_dir: &std::path::Path,
auto_capture: bool,
project_root: Option<String>,
) -> super::Answer {
let linked_vault = project_root.as_deref().and_then(|root| {
lean_ctx_hive::vault::VaultMap::load(data_dir)
.for_root(root)
.map(|record| format!("{}/{}", record.ns, record.name))
});
let facts = LocalFacts {
capture: capture_counts(&lean_ctx_hive::capture::load_counts(data_dir)),
project_root,
linked_vault,
auto_capture,
};
match serde_json::to_string(&of_report(report, facts)) {
Ok(text) => super::Answer {
text,
failed: None,
notice: None,
released: false,
withheld: false,
},
Err(e) => {
super::Answer::failure(&super::Failure::new(super::Code::Internal, e.to_string()))
}
}
}
#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
pub(crate) fn answer(args: &[String]) -> super::Answer {
let project_root = args
.iter()
.any(|a| a == "--project-root")
.then(|| super::super::common::detect_project_root(args));
let store = match lean_ctx_hive::HiveStore::open() {
Ok(store) => store,
Err(error) => return super::Answer::failure(&error.into()),
};
let config = lean_ctx::core::config::Config::load().hive.clone();
let report = lean_ctx_hive::status::report(&store, &config, chrono::Utc::now());
of_state(&report, store.data_dir(), config.auto_capture, project_root)
}