use std::collections::BTreeSet;
use std::path::Path;
use lean_ctx_time::{OffsetDateTime, UtcDateTime};
use serde::{Deserialize, Serialize};
use crate::config::CloudConfig;
use crate::effective_floor;
use crate::state::{CloudStore, InstanceRecord};
use lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1;
use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, CloudPlan, CloudRight};
use lean_ctx_protocol::cloud::metrics_v2::{
PlanDefault, PolicyLevel, SharingStateV2, SharingValue, TimeStamp,
};
const MEMBER: &str = "share_instance_metrics";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OffReason {
Engine,
Lease,
Workspace,
Revoked,
Policy,
PolicyUnavailable,
NotConfirmed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Sharing {
On {
vaults_off: BTreeSet<String>,
unattributed: bool,
policy_version: u64,
since: Option<UtcDateTime>,
level: Option<PolicyLevel>,
},
Off {
reason: OffReason,
level: Option<PolicyLevel>,
},
}
impl Sharing {
pub fn is_on(&self) -> bool {
matches!(self, Self::On { .. })
}
pub fn describe(&self) -> String {
match self {
Self::On { level, .. } => match level {
Some(level) => format!("on (set by {})", level.label()),
None => "on (plan default)".into(),
},
Self::Off { reason, level } => {
let why = match reason {
OffReason::Engine => "this instance, [cloud] metrics_upload = false",
OffReason::Lease => "the lease does not include metrics.upload",
OffReason::Workspace => "switched off by the workspace",
OffReason::Revoked => "this instance was revoked",
OffReason::Policy => "policy",
OffReason::PolicyUnavailable => "policy, no valid bundle in force",
OffReason::NotConfirmed => {
"waiting for your confirmation: run `lean-ctx cloud metrics confirm` in a terminal"
}
};
match level {
Some(level) => format!("off ({why}, set by {})", level.label()),
None => format!("off ({why})"),
}
}
}
}
pub fn now_words(&self) -> String {
match self {
Self::On { level, .. } => format!(
"on, set by {}",
level.map_or("plan default", PolicyLevel::label)
),
Self::Off {
reason: OffReason::NotConfirmed,
..
} => "waiting for your confirmation, set by plan default".into(),
Self::Off { level, .. } => format!(
"off, set by {}",
level.map_or("this instance", PolicyLevel::label)
),
}
}
}
pub fn needs_confirmation(plan: CloudPlan) -> bool {
!matches!(plan, CloudPlan::Team | CloudPlan::Enterprise)
}
fn rule(policy: &EffectivePolicyV1) -> Option<bool> {
serde_json::to_value(&policy.sharing)
.ok()?
.get(MEMBER)?
.as_bool()
}
pub(crate) fn policy(
cloud_data: &Path,
now: UtcDateTime,
) -> Result<(BTreeSet<String>, u64), OffReason> {
let dir = effective_floor::floor_dir_in(cloud_data);
let (floor, required) =
effective_floor::read(&dir).map_err(|_| OffReason::PolicyUnavailable)?;
let Some(floor) = effective_floor::check(floor.as_deref(), required.as_deref())
.map_err(|_| OffReason::PolicyUnavailable)?
else {
return Err(OffReason::PolicyUnavailable);
};
let expired =
OffsetDateTime::parse_from_rfc3339(&floor.not_after).map_or(true, |t| t.to_utc() <= now);
if expired {
return Err(OffReason::PolicyUnavailable);
}
if rule(&floor.policy.effective) == Some(false) {
return Err(OffReason::Policy);
}
let vaults_off = floor
.policy
.vaults
.iter()
.filter(|v| rule(&v.effective) == Some(false))
.map(|v| v.vault_id.clone())
.collect();
Ok((vaults_off, floor.version))
}
pub fn decide_with(
store: &CloudStore,
config: &CloudConfig,
instance: &InstanceRecord,
lease: &CloudLeaseV1,
sharing: Option<&SharingStateV2>,
now: UtcDateTime,
) -> Sharing {
let off = |reason, level| Sharing::Off { reason, level };
if !config.metrics_upload {
return off(OffReason::Engine, Some(PolicyLevel::Instance));
}
if crate::revoked::recorded(store, instance).is_some() {
return off(OffReason::Revoked, None);
}
if !lease.grants(CloudRight::MetricsUpload) {
return off(OffReason::Lease, None);
}
if !lease.org_allows_metrics_upload() {
return off(OffReason::Workspace, None);
}
let (since, level) = match sharing {
Some(s) => match s.state {
SharingValue::On => (
s.since.as_ref().map(TimeStamp::at),
s.policy.map(|p| p.level),
),
SharingValue::Off => {
return off(OffReason::Policy, s.policy.map(|p| p.level));
}
SharingValue::NeedsConfirmation => return off(OffReason::NotConfirmed, None),
},
None if needs_confirmation(lease.plan) => return off(OffReason::NotConfirmed, None),
None => (None, None),
};
let (vaults_off, policy_version) = match policy(store.data_dir(), now) {
Ok(found) => found,
Err(OffReason::Policy) => {
return off(
OffReason::Policy,
sharing.and_then(|s| s.policy).map(|p| p.level),
);
}
Err(reason) => return off(reason, None),
};
let state = super::buffer::State::load(store.data_dir());
if let Some((reason, level)) = state.refused(&lease.lease_id, policy_version) {
return off(reason, level);
}
Sharing::On {
vaults_off,
unattributed: instance.org_kind.as_deref() == Some("personal"),
policy_version,
since,
level,
}
}
pub fn decide(
store: &CloudStore,
config: &CloudConfig,
instance: &InstanceRecord,
lease: &CloudLeaseV1,
now: UtcDateTime,
) -> Sharing {
let state = super::buffer::State::load(store.data_dir());
let sharing = state.sharing.filter(|_| state.org_id == instance.org_id);
decide_with(store, config, instance, lease, sharing.as_ref(), now)
}
pub fn plan_state(plan: CloudPlan) -> SharingStateV2 {
let default_on = !needs_confirmation(plan);
SharingStateV2 {
state: if default_on {
SharingValue::On
} else {
SharingValue::NeedsConfirmation
},
plan_default: if default_on {
PlanDefault::On
} else {
PlanDefault::Off
},
policy: None,
confirmed_at: None,
since: None,
}
}