lean_ctx_cloud/metrics_v2/
gate.rs1use std::collections::BTreeSet;
26use std::path::Path;
27
28use lean_ctx_time::{OffsetDateTime, UtcDateTime};
29use serde::{Deserialize, Serialize};
30
31use crate::config::CloudConfig;
32use crate::effective_floor;
33use crate::state::{CloudStore, InstanceRecord};
34use lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1;
35use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, CloudPlan, CloudRight};
36use lean_ctx_protocol::cloud::metrics_v2::{
37 PlanDefault, PolicyLevel, SharingStateV2, SharingValue, TimeStamp,
38};
39
40const MEMBER: &str = "share_instance_metrics";
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum OffReason {
46 Engine,
48 Lease,
50 Workspace,
52 Revoked,
54 Policy,
56 PolicyUnavailable,
58 NotConfirmed,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Sharing {
65 On {
66 vaults_off: BTreeSet<String>,
68 unattributed: bool,
70 policy_version: u64,
72 since: Option<UtcDateTime>,
74 level: Option<PolicyLevel>,
76 },
77 Off {
78 reason: OffReason,
79 level: Option<PolicyLevel>,
80 },
81}
82
83impl Sharing {
84 pub fn is_on(&self) -> bool {
85 matches!(self, Self::On { .. })
86 }
87
88 pub fn waits_for_confirmation(&self) -> bool {
91 matches!(
92 self,
93 Self::Off {
94 reason: OffReason::NotConfirmed,
95 ..
96 }
97 )
98 }
99
100 pub fn describe(&self) -> String {
102 match self {
103 Self::On { level, .. } => match level {
104 Some(level) => format!("on (set by {})", level.label()),
105 None => "on (plan default)".into(),
106 },
107 Self::Off { reason, level } => {
108 let why = match reason {
109 OffReason::Engine => "this instance, [cloud] metrics_upload = false",
110 OffReason::Lease => "the lease does not include metrics.upload",
111 OffReason::Workspace => "switched off by the workspace",
112 OffReason::Revoked => "this instance was revoked",
113 OffReason::Policy => "policy",
114 OffReason::PolicyUnavailable => "policy, no valid bundle in force",
115 OffReason::NotConfirmed => {
116 "waiting for your confirmation: run `lean-ctx cloud metrics confirm` in a terminal"
117 }
118 };
119 match level {
120 Some(level) => format!("off ({why}, set by {})", level.label()),
121 None => format!("off ({why})"),
122 }
123 }
124 }
125 }
126
127 pub fn now_words(&self) -> String {
129 match self {
130 Self::On { level, .. } => format!(
131 "on, set by {}",
132 level.map_or("plan default", PolicyLevel::label)
133 ),
134 Self::Off {
135 reason: OffReason::NotConfirmed,
136 ..
137 } => "waiting for your confirmation, set by plan default".into(),
138 Self::Off { level, .. } => format!(
139 "off, set by {}",
140 level.map_or("this instance", PolicyLevel::label)
141 ),
142 }
143 }
144}
145
146pub fn needs_confirmation(_plan: CloudPlan) -> bool {
150 false
151}
152
153fn rule(policy: &EffectivePolicyV1) -> Option<bool> {
157 serde_json::to_value(&policy.sharing)
158 .ok()?
159 .get(MEMBER)?
160 .as_bool()
161}
162
163pub(crate) fn policy(
166 cloud_data: &Path,
167 now: UtcDateTime,
168) -> Result<(BTreeSet<String>, u64), OffReason> {
169 let dir = effective_floor::floor_dir_in(cloud_data);
170 let (floor, required) =
171 effective_floor::read(&dir).map_err(|_| OffReason::PolicyUnavailable)?;
172 let Some(floor) = effective_floor::check(floor.as_deref(), required.as_deref())
173 .map_err(|_| OffReason::PolicyUnavailable)?
174 else {
175 return Err(OffReason::PolicyUnavailable);
177 };
178 let expired =
179 OffsetDateTime::parse_from_rfc3339(&floor.not_after).map_or(true, |t| t.to_utc() <= now);
180 if expired {
181 return Err(OffReason::PolicyUnavailable);
182 }
183 if rule(&floor.policy.effective) == Some(false) {
184 return Err(OffReason::Policy);
185 }
186 let vaults_off = floor
187 .policy
188 .vaults
189 .iter()
190 .filter(|v| rule(&v.effective) == Some(false))
191 .map(|v| v.vault_id.clone())
192 .collect();
193 Ok((vaults_off, floor.version))
194}
195
196pub fn decide_with(
199 store: &CloudStore,
200 config: &CloudConfig,
201 instance: &InstanceRecord,
202 lease: &CloudLeaseV1,
203 sharing: Option<&SharingStateV2>,
204 now: UtcDateTime,
205) -> Sharing {
206 let off = |reason, level| Sharing::Off { reason, level };
207 if !config.metrics_upload {
208 return off(OffReason::Engine, Some(PolicyLevel::Instance));
209 }
210 if crate::revoked::recorded(store, instance).is_some() {
211 return off(OffReason::Revoked, None);
212 }
213 if !lease.grants(CloudRight::MetricsUpload) {
214 return off(OffReason::Lease, None);
215 }
216 if !lease.org_allows_metrics_upload() {
217 return off(OffReason::Workspace, None);
218 }
219 let (since, level) = match sharing {
221 Some(s) => match s.state {
222 SharingValue::On => (
223 s.since.as_ref().map(TimeStamp::at),
224 s.policy.map(|p| p.level),
225 ),
226 SharingValue::Off => {
227 return off(OffReason::Policy, s.policy.map(|p| p.level));
228 }
229 SharingValue::NeedsConfirmation => return off(OffReason::NotConfirmed, None),
230 },
231 None if needs_confirmation(lease.plan) => return off(OffReason::NotConfirmed, None),
232 None => (None, None),
233 };
234 let (vaults_off, policy_version) = match policy(store.data_dir(), now) {
235 Ok(found) => found,
236 Err(OffReason::Policy) => {
237 return off(
238 OffReason::Policy,
239 sharing.and_then(|s| s.policy).map(|p| p.level),
240 );
241 }
242 Err(reason) => return off(reason, None),
243 };
244 let state = super::buffer::State::load(store.data_dir());
245 if let Some((reason, level)) = state.refused(&lease.lease_id, policy_version) {
246 return off(reason, level);
247 }
248 Sharing::On {
249 vaults_off,
250 unattributed: instance.org_kind.as_deref() == Some("personal"),
251 policy_version,
252 since,
253 level,
254 }
255}
256
257pub fn decide(
259 store: &CloudStore,
260 config: &CloudConfig,
261 instance: &InstanceRecord,
262 lease: &CloudLeaseV1,
263 now: UtcDateTime,
264) -> Sharing {
265 let state = super::buffer::State::load(store.data_dir());
266 let sharing = state.sharing.filter(|_| state.org_id == instance.org_id);
267 decide_with(store, config, instance, lease, sharing.as_ref(), now)
268}
269
270pub fn plan_state(plan: CloudPlan) -> SharingStateV2 {
272 let default_on = !needs_confirmation(plan);
273 SharingStateV2 {
274 state: if default_on {
275 SharingValue::On
276 } else {
277 SharingValue::NeedsConfirmation
278 },
279 plan_default: if default_on {
280 PlanDefault::On
281 } else {
282 PlanDefault::Off
283 },
284 policy: None,
285 confirmed_at: None,
286 since: None,
287 }
288}