1use crate::CloudConfigExt as _;
30use std::collections::{BTreeMap, BTreeSet};
31use std::path::Path;
32use std::sync::{Mutex, MutexGuard, PoisonError};
33use std::time::{Duration, Instant};
34
35use serde::{Deserialize, Serialize};
36use serde_json::json;
37use sha2::{Digest, Sha256};
38
39use crate::CloudError;
40use crate::auth::Session;
41use crate::config::{CloudBusMode, CloudConfig};
42use crate::state::{CloudStore, load_or_quarantine, lock_state, write_private};
43use lean_ctx_protocol::cloud::bus::{
44 BUS_LEASE_RENEW_REQUEST_SCHEMA, BUS_LEASE_REQUEST_SCHEMA, BusLeaseV1, MAX_BUS_LEASE_MS,
45};
46use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
47
48pub const BUDGET: Duration = Duration::from_secs(3);
50const LEASES_FILE: &str = "leases.json";
51const MAX_RELEASES: usize = 256;
54const STALE_BINDING: lean_ctx_time::Duration = lean_ctx_time::Duration::days(1);
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Outcome {
60 Granted {
61 lease_id: String,
62 fencing_token: u64,
63 expires_at: String,
64 },
65 Held {
67 agent_id: String,
68 instance_id: String,
69 expires_at: String,
70 },
71 Vetoed,
73 Superseded,
75 Local(String),
77 Pending,
80}
81
82static PENDING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
85
86fn pending() -> MutexGuard<'static, BTreeSet<String>> {
87 PENDING.lock().unwrap_or_else(PoisonError::into_inner)
88}
89
90pub fn caller(agent_id: &str) -> String {
93 format!("ctx_agent:{agent_id}")
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct Binding {
99 pub lease_id: String,
100 pub fencing_token: u64,
101 #[serde(rename = "project_id", alias = "vault_id")]
103 pub vault_id: String,
104 pub expires_at: String,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Release {
110 pub lease_id: String,
111 pub fencing_token: u64,
112}
113
114#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
116pub struct Bindings {
117 #[serde(default)]
118 pub leases: BTreeMap<String, Binding>,
119 #[serde(default)]
120 pub releases: Vec<Release>,
121}
122
123impl Bindings {
124 pub fn load(data_dir: &Path) -> Self {
127 load_or_quarantine(&data_dir.join("bus").join(LEASES_FILE), |_: &Self| true)
128 .unwrap_or_else(|error| {
129 tracing::warn!("cloud lease bindings: {error}");
130 None
131 })
132 .unwrap_or_default()
133 }
134
135 fn save(&self, data_dir: &Path) -> Result<(), CloudError> {
136 let bytes = serde_json::to_vec(self).map_err(|e| CloudError::Local(e.to_string()))?;
137 write_private(&data_dir.join("bus"), LEASES_FILE, &bytes)
138 }
139
140 pub fn mutate<T>(
144 data_dir: &Path,
145 change: impl FnOnce(&mut Self) -> T,
146 ) -> Result<T, CloudError> {
147 let _lock = lock_state(&data_dir.join("bus"), LEASES_FILE)?;
148 let mut bindings = Self::load(data_dir);
149 let before = bindings.clone();
150 let out = change(&mut bindings);
151 bindings.prune(lean_ctx_time::UtcDateTime::now());
152 if bindings != before {
153 bindings.save(data_dir)?;
154 }
155 Ok(out)
156 }
157
158 fn prune(&mut self, now: lean_ctx_time::UtcDateTime) {
159 self.leases.retain(|_, b| {
160 lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&b.expires_at)
161 .map_or(true, |at| at.to_utc() + STALE_BINDING > now)
162 });
163 let excess = self.releases.len().saturating_sub(MAX_RELEASES);
164 self.releases.drain(..excess);
165 }
166}
167
168pub fn resource_ref(vault_id: &str, kind: &str, target: &str) -> String {
172 let digest = Sha256::digest(
173 format!("leanctx.cloud.bus-lease.v1\n{vault_id}\n{kind}\n{target}").as_bytes(),
174 );
175 hex::encode(digest)
176}
177
178pub fn normalize_target(project_root: &Path, raw: &str) -> Option<(&'static str, String)> {
182 let raw = raw.trim();
183 if let Some(symbol) = raw.strip_prefix("symbol:") {
184 let symbol = symbol.trim();
185 return (!symbol.is_empty()).then(|| ("symbol", symbol.to_string()));
186 }
187 let path = Path::new(raw);
188 let anchored = path.has_root()
192 || matches!(
193 path.components().next(),
194 Some(std::path::Component::Prefix(_))
195 );
196 let relative = if anchored {
197 path.strip_prefix(project_root).ok()?
198 } else {
199 path
200 };
201 let mut parts: Vec<String> = Vec::new();
202 for component in relative.components() {
203 match component {
204 std::path::Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
205 std::path::Component::CurDir => {}
206 std::path::Component::ParentDir => {
207 parts.pop()?;
208 }
209 _ => return None,
210 }
211 }
212 (!parts.is_empty()).then(|| ("file", parts.join("/")))
213}
214
215pub(super) struct Connected {
217 pub(super) store: CloudStore,
218 pub(super) session: Session,
219 pub(super) vault_id: String,
220}
221
222pub(super) fn connected(project_root: &Path) -> Result<Connected, String> {
224 let config = lean_ctx::core::config::Config::load().cloud.clone();
225 connected_with(
226 &config,
227 CloudStore::open().map_err(|e| e.to_string())?,
228 project_root,
229 )
230}
231
232fn connected_with(
233 config: &CloudConfig,
234 store: CloudStore,
235 project_root: &Path,
236) -> Result<Connected, String> {
237 if config.bus == CloudBusMode::Off || config.enabled == Some(false) {
238 return Err("the Cloud bus is off".into());
239 }
240 let instance = store
241 .instance()
242 .ok()
243 .flatten()
244 .ok_or_else(|| "this machine is not connected to the Cloud".to_string())?;
245 let vault_id = crate::resolution::vault_for_root(&store, project_root)
246 .map_err(|e| e.to_string())?
247 .map(|p| p.vault_id)
248 .ok_or_else(|| "this repository is not linked to a vault".to_string())?;
249 let session = config
250 .root_key(&instance.url)
251 .and_then(|root| Session::load(store.clone(), root))
252 .map_err(|e| e.to_string())?;
253 if !matches!(
254 session.lease.state_at(lean_ctx_time::UtcDateTime::now()),
255 LeaseState::Valid | LeaseState::Grace
256 ) {
257 return Err("the Cloud lease has lapsed".into());
258 }
259 if !session.lease.lease.grants(CloudRight::BusRelay) {
260 return Err("the Cloud lease does not include the bus".into());
261 }
262 Ok(Connected {
263 store,
264 session,
265 vault_id,
266 })
267}
268
269fn decode_lease(value: serde_json::Value) -> Result<BusLeaseV1, CloudError> {
270 let lease: BusLeaseV1 = serde_json::from_value(value)
271 .map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
272 lease
273 .validate()
274 .map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
275 Ok(lease)
276}
277
278fn outcome(answer: Result<BusLeaseV1, CloudError>) -> Outcome {
279 match answer {
280 Ok(BusLeaseV1 {
281 granted: true,
282 lease_id: Some(lease_id),
283 fencing_token: Some(fencing_token),
284 expires_at: Some(expires_at),
285 ..
286 }) => Outcome::Granted {
287 lease_id,
288 fencing_token,
289 expires_at: expires_at.as_str().to_string(),
290 },
291 Ok(BusLeaseV1 {
292 holder: Some(holder),
293 ..
294 }) => Outcome::Held {
295 agent_id: holder.agent_id,
296 instance_id: holder.instance_id,
297 expires_at: holder.expires_at.as_str().to_string(),
298 },
299 Ok(_) => Outcome::Local("the Cloud sent an incomplete lease".into()),
300 Err(CloudError::Vetoed) => Outcome::Vetoed,
301 Err(CloudError::NotFound) => Outcome::Superseded,
302 Err(CloudError::Offline(why)) => {
303 Outcome::Local(format!("the Cloud is not reachable ({why})"))
304 }
305 Err(error) => Outcome::Local(error.to_string()),
306 }
307}
308
309pub fn acquire(
316 project_root: &Path,
317 agent_id: &str,
318 target: &str,
319 duration_ms: u64,
320 local_ref: &str,
321 settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
322) -> Outcome {
323 let connected = match connected(project_root) {
324 Ok(connected) => connected,
325 Err(why) => return Outcome::Local(why),
326 };
327 if normalize_target(project_root, target).is_none() {
328 return Outcome::Local("the target is outside the project".into());
329 }
330 let (root, agent, target, local) = (
331 project_root.to_path_buf(),
332 agent_id.to_string(),
333 target.to_string(),
334 local_ref.to_string(),
335 );
336 pending().insert(local.clone());
337 crate::background::submit(&caller(agent_id), move || {
338 let outcome = acquire_with(&connected, &root, &agent, &target, duration_ms, &local);
339 pending().remove(&local);
340 settle(outcome)
341 });
342 Outcome::Pending
343}
344
345fn acquire_with(
346 c: &Connected,
347 project_root: &Path,
348 agent_id: &str,
349 target: &str,
350 duration_ms: u64,
351 local_ref: &str,
352) -> Outcome {
353 let Some((kind, normalized)) = normalize_target(project_root, target) else {
354 return Outcome::Local("the target is outside the project".into());
355 };
356 let deadline = Instant::now() + BUDGET;
357 let body = json!({
358 "schema": BUS_LEASE_REQUEST_SCHEMA,
359 "resource_kind": kind,
360 "resource_ref": resource_ref(&c.vault_id, kind, &normalized),
361 "vault_id": c.vault_id,
362 "owner_agent_id": agent_id,
363 "duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
364 });
365 let answer = c
366 .session
367 .bounded_client(deadline)
368 .and_then(|client| client.post("/bus/leases", &body))
369 .and_then(decode_lease);
370 let result = outcome(answer);
371 if let Outcome::Granted {
372 lease_id,
373 fencing_token,
374 expires_at,
375 } = &result
376 {
377 let binding = Binding {
378 lease_id: lease_id.clone(),
379 fencing_token: *fencing_token,
380 vault_id: c.vault_id.clone(),
381 expires_at: expires_at.clone(),
382 };
383 if let Err(error) = Bindings::mutate(c.store.data_dir(), |b| {
384 b.leases.insert(local_ref.to_string(), binding);
385 }) {
386 return Outcome::Local(format!("could not record the Cloud lease: {error}"));
389 }
390 }
391 result
392}
393
394pub fn renew(
399 project_root: &Path,
400 agent_id: &str,
401 local_ref: &str,
402 duration_ms: u64,
403 settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
404) -> Outcome {
405 let Ok(store) = CloudStore::open() else {
406 return Outcome::Local("no Cloud state".into());
407 };
408 let bound = Bindings::load(store.data_dir())
409 .leases
410 .contains_key(local_ref);
411 if !bound && !pending().contains(local_ref) {
412 return Outcome::Local("this lease is local only".into());
413 }
414 let connected = match connected(project_root) {
415 Ok(connected) => connected,
416 Err(why) => return Outcome::Local(why),
417 };
418 let local = local_ref.to_string();
419 crate::background::submit(&caller(agent_id), move || {
420 settle(renew_with(&connected, &local, duration_ms))
421 });
422 Outcome::Pending
423}
424
425fn renew_with(c: &Connected, local_ref: &str, duration_ms: u64) -> Outcome {
426 let data = c.store.data_dir();
427 let Some(binding) = Bindings::load(data).leases.get(local_ref).cloned() else {
428 return Outcome::Local("the Cloud did not grant this lease".into());
429 };
430 let deadline = Instant::now() + BUDGET;
431 let body = json!({
432 "schema": BUS_LEASE_RENEW_REQUEST_SCHEMA,
433 "fencing_token": binding.fencing_token,
434 "duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
435 });
436 let path = format!("/bus/leases/{}/renew", binding.lease_id);
437 let result = outcome(
438 c.session
439 .bounded_client(deadline)
440 .and_then(|client| client.post(&path, &body))
441 .and_then(decode_lease),
442 );
443 let applied = Bindings::mutate(data, |bindings| {
446 let same = |b: &Binding| b.lease_id == binding.lease_id;
447 match &result {
448 Outcome::Granted { expires_at, .. } => {
449 if let Some(b) = bindings.leases.get_mut(local_ref).filter(|b| same(b)) {
450 b.expires_at.clone_from(expires_at);
451 }
452 }
453 Outcome::Superseded | Outcome::Vetoed
454 if bindings.leases.get(local_ref).is_some_and(same) =>
455 {
456 bindings.leases.remove(local_ref);
457 }
458 _ => {}
459 }
460 });
461 if let Err(error) = applied {
462 tracing::debug!("cloud lease bindings not saved: {error}");
463 }
464 result
465}
466
467pub fn binding(local_ref: &str) -> Option<Binding> {
469 let store = CloudStore::open().ok()?;
470 Bindings::load(store.data_dir())
471 .leases
472 .get(local_ref)
473 .cloned()
474}
475
476pub fn release(agent_id: &str, local_ref: &str) {
480 let Ok(store) = CloudStore::open() else {
481 return;
482 };
483 let was_pending = pending().contains(local_ref);
486 queue_release_in(store.data_dir(), local_ref);
487 if was_pending {
488 let (data, local) = (store.data_dir().to_path_buf(), local_ref.to_string());
489 crate::background::submit(&caller(agent_id), move || {
490 queue_release_in(&data, &local);
491 None
492 });
493 }
494}
495
496fn queue_release_in(data_dir: &Path, local_ref: &str) {
497 let queued = Bindings::mutate(data_dir, |bindings| {
498 if let Some(b) = bindings.leases.remove(local_ref) {
499 bindings.releases.push(Release {
500 lease_id: b.lease_id,
501 fencing_token: b.fencing_token,
502 });
503 }
504 });
505 if let Err(error) = queued {
506 tracing::debug!("cloud lease release not queued: {error}");
507 }
508}
509
510pub fn send_releases(store: &CloudStore, session: &Session) {
513 let data = store.data_dir();
514 let done: Vec<Release> = Bindings::load(data)
517 .releases
518 .into_iter()
519 .filter(|r| {
520 let path = format!(
521 "/bus/leases/{}?fencing_token={}",
522 r.lease_id, r.fencing_token
523 );
524 match session.with_client(|client| client.delete(&path)) {
525 Ok(()) | Err(CloudError::NotFound) => true,
526 Err(error) => matches!(
527 error,
528 CloudError::Forbidden | CloudError::Vetoed | CloudError::Protocol(_)
529 ),
530 }
531 })
532 .collect();
533 if done.is_empty() {
534 return;
535 }
536 if let Err(error) = Bindings::mutate(data, |b| b.releases.retain(|r| !done.contains(r))) {
537 tracing::debug!("cloud lease releases not saved: {error}");
538 }
539}
540
541pub fn scope_line(outcome: &Outcome) -> String {
544 match outcome {
545 Outcome::Granted { .. } | Outcome::Held { .. } | Outcome::Vetoed | Outcome::Superseded => {
546 "scope=cloud".into()
547 }
548 Outcome::Local(why) => {
549 format!("scope=local ({why}; other machines are not excluded)")
550 }
551 Outcome::Pending => "scope=pending (the Cloud is asked off this call; until it grants, \
552 other machines are not excluded; its answer comes with your next ctx_agent call)"
553 .into(),
554 }
555}
556
557#[cfg(test)]
558mod vault_rename_tests {
559 use super::*;
560
561 #[derive(Deserialize)]
563 #[allow(dead_code)]
564 struct PreVaBinding {
565 lease_id: String,
566 fencing_token: u64,
567 project_id: String,
568 expires_at: String,
569 }
570
571 #[test]
572 fn lease_bindings_keep_pre_va_names() {
573 let old = r#"{"lease_id":"lse_1","fencing_token":4,"project_id":"v1","expires_at":"2026-10-22T10:00:00Z"}"#;
574 let read = crate::vault::assert_pre_va_round_trip::<Binding, PreVaBinding>(
575 old,
576 "project_id",
577 "vault_id",
578 );
579 assert_eq!((read.vault_id.as_str(), read.fencing_token), ("v1", 4));
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586
587 #[test]
588 fn every_checkout_names_a_file_the_same_way() {
589 let a = Path::new("/home/ada/src/payments");
590 let b = Path::new("/Users/bob/work/payments-clone");
591 let (kind, ta) = normalize_target(a, "/home/ada/src/payments/src/lib.rs").unwrap();
592 let (_, tb) = normalize_target(b, "./src/../src/lib.rs").unwrap();
593 assert_eq!((kind, ta.as_str()), ("file", "src/lib.rs"));
594 assert_eq!(ta, tb);
595 let pid = "0123456789abcdef0123456789abcdef";
596 let ref_a = resource_ref(pid, kind, &ta);
597 assert_eq!(ref_a, resource_ref(pid, kind, &tb));
598 assert_eq!(ref_a.len(), 64);
599 assert!(!ref_a.contains("lib"));
600 assert_ne!(
601 ref_a,
602 resource_ref("fedcba9876543210fedcba9876543210", kind, &ta)
603 );
604 assert_ne!(ref_a, resource_ref(pid, "symbol", &ta));
605 assert_eq!(
606 normalize_target(a, "symbol: Parser::parse"),
607 Some(("symbol", "Parser::parse".into()))
608 );
609 assert_eq!(
610 normalize_target(a, "/etc/passwd"),
611 None,
612 "outside the project"
613 );
614 assert_eq!(normalize_target(a, "../other/x.rs"), None);
615 assert_eq!(normalize_target(a, "symbol:"), None);
616 }
617
618 #[test]
619 fn answers_map_to_outcomes_and_the_scope_is_always_named() {
620 let granted = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": true,
621 "lease_id": "bl_1", "fencing_token": 4, "expires_at": "2026-10-21T12:10:00Z",
622 "server_time": "2026-10-21T12:00:00Z"});
623 let out = outcome(decode_lease(granted));
624 assert!(matches!(
625 out,
626 Outcome::Granted {
627 fencing_token: 4,
628 ..
629 }
630 ));
631 assert_eq!(
632 scope_line(&out),
633 "scope=cloud",
634 "the token is never printed"
635 );
636 let held = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": false,
637 "holder": {"agent_id": "beta", "instance_id": "inst_b", "expires_at": "2026-10-21T12:10:00Z"},
638 "server_time": "2026-10-21T12:00:00Z"});
639 assert!(
640 matches!(outcome(decode_lease(held)), Outcome::Held { agent_id, .. } if agent_id == "beta")
641 );
642 assert_eq!(outcome(Err(CloudError::Vetoed)), Outcome::Vetoed);
643 assert_eq!(outcome(Err(CloudError::NotFound)), Outcome::Superseded);
644 let offline = outcome(Err(CloudError::Offline("timeout".into())));
645 assert!(
646 scope_line(&offline).starts_with("scope=local (the Cloud is not reachable (timeout)")
647 );
648 assert!(scope_line(&offline).ends_with("other machines are not excluded)"));
649 let pending = scope_line(&Outcome::Pending);
650 assert!(pending.starts_with("scope=pending (") && !pending.contains("fencing"));
651 }
652
653 #[test]
654 fn without_an_enrollment_no_request_is_made() {
655 let dir = tempfile::tempdir().unwrap();
656 let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
657 let err = connected_with(&CloudConfig::default(), store.clone(), dir.path())
658 .err()
659 .unwrap();
660 assert_eq!(err, "this machine is not connected to the Cloud");
661 let off = CloudConfig {
662 bus: CloudBusMode::Off,
663 ..CloudConfig::default()
664 };
665 assert_eq!(
666 connected_with(&off, store, dir.path()).err().unwrap(),
667 "the Cloud bus is off"
668 );
669 }
670
671 #[test]
672 fn bindings_round_trip_and_queue_releases() {
673 let dir = tempfile::tempdir().unwrap();
674 let mut b = Bindings::default();
675 b.leases.insert(
676 "lease-ref:1".into(),
677 Binding {
678 lease_id: "bl_1".into(),
679 fencing_token: 2,
680 vault_id: "p".into(),
681 expires_at: "2026-10-21T12:10:00Z".into(),
682 },
683 );
684 b.save(dir.path()).unwrap();
685 assert_eq!(Bindings::load(dir.path()), b);
686 }
687}