use crate::CloudConfigExt as _;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
use crate::CloudError;
use crate::auth::Session;
use crate::config::{CloudBusMode, CloudConfig};
use crate::state::{CloudStore, load_or_quarantine, lock_state, write_private};
use lean_ctx_protocol::cloud::bus::{
BUS_LEASE_RENEW_REQUEST_SCHEMA, BUS_LEASE_REQUEST_SCHEMA, BusLeaseV1, MAX_BUS_LEASE_MS,
};
use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
pub const BUDGET: Duration = Duration::from_secs(3);
const LEASES_FILE: &str = "leases.json";
const MAX_RELEASES: usize = 256;
const STALE_BINDING: lean_ctx_time::Duration = lean_ctx_time::Duration::days(1);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Granted {
lease_id: String,
fencing_token: u64,
expires_at: String,
},
Held {
agent_id: String,
instance_id: String,
expires_at: String,
},
Vetoed,
Superseded,
Local(String),
Pending,
}
static PENDING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
fn pending() -> MutexGuard<'static, BTreeSet<String>> {
PENDING.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn caller(agent_id: &str) -> String {
format!("ctx_agent:{agent_id}")
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Binding {
pub lease_id: String,
pub fencing_token: u64,
#[serde(rename = "project_id", alias = "vault_id")]
pub vault_id: String,
pub expires_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Release {
pub lease_id: String,
pub fencing_token: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Bindings {
#[serde(default)]
pub leases: BTreeMap<String, Binding>,
#[serde(default)]
pub releases: Vec<Release>,
}
impl Bindings {
pub fn load(data_dir: &Path) -> Self {
load_or_quarantine(&data_dir.join("bus").join(LEASES_FILE), |_: &Self| true)
.unwrap_or_else(|error| {
tracing::warn!("cloud lease bindings: {error}");
None
})
.unwrap_or_default()
}
fn save(&self, data_dir: &Path) -> Result<(), CloudError> {
let bytes = serde_json::to_vec(self).map_err(|e| CloudError::Local(e.to_string()))?;
write_private(&data_dir.join("bus"), LEASES_FILE, &bytes)
}
pub fn mutate<T>(
data_dir: &Path,
change: impl FnOnce(&mut Self) -> T,
) -> Result<T, CloudError> {
let _lock = lock_state(&data_dir.join("bus"), LEASES_FILE)?;
let mut bindings = Self::load(data_dir);
let before = bindings.clone();
let out = change(&mut bindings);
bindings.prune(lean_ctx_time::UtcDateTime::now());
if bindings != before {
bindings.save(data_dir)?;
}
Ok(out)
}
fn prune(&mut self, now: lean_ctx_time::UtcDateTime) {
self.leases.retain(|_, b| {
lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&b.expires_at)
.map_or(true, |at| at.to_utc() + STALE_BINDING > now)
});
let excess = self.releases.len().saturating_sub(MAX_RELEASES);
self.releases.drain(..excess);
}
}
pub fn resource_ref(vault_id: &str, kind: &str, target: &str) -> String {
let digest = Sha256::digest(
format!("leanctx.cloud.bus-lease.v1\n{vault_id}\n{kind}\n{target}").as_bytes(),
);
hex::encode(digest)
}
pub fn normalize_target(project_root: &Path, raw: &str) -> Option<(&'static str, String)> {
let raw = raw.trim();
if let Some(symbol) = raw.strip_prefix("symbol:") {
let symbol = symbol.trim();
return (!symbol.is_empty()).then(|| ("symbol", symbol.to_string()));
}
let path = Path::new(raw);
let anchored = path.has_root()
|| matches!(
path.components().next(),
Some(std::path::Component::Prefix(_))
);
let relative = if anchored {
path.strip_prefix(project_root).ok()?
} else {
path
};
let mut parts: Vec<String> = Vec::new();
for component in relative.components() {
match component {
std::path::Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
parts.pop()?;
}
_ => return None,
}
}
(!parts.is_empty()).then(|| ("file", parts.join("/")))
}
pub(super) struct Connected {
pub(super) store: CloudStore,
pub(super) session: Session,
pub(super) vault_id: String,
}
pub(super) fn connected(project_root: &Path) -> Result<Connected, String> {
let config = lean_ctx::core::config::Config::load().cloud.clone();
connected_with(
&config,
CloudStore::open().map_err(|e| e.to_string())?,
project_root,
)
}
fn connected_with(
config: &CloudConfig,
store: CloudStore,
project_root: &Path,
) -> Result<Connected, String> {
if config.bus == CloudBusMode::Off || config.enabled == Some(false) {
return Err("the LeanCTX Cloud bus is off".into());
}
let instance = store
.instance()
.ok()
.flatten()
.ok_or_else(|| "this machine is not connected to LeanCTX Cloud".to_string())?;
let vault_id = crate::resolution::vault_for_root(store.data_dir(), project_root)
.map_err(|e| e.to_string())?
.map(|p| p.vault_id)
.ok_or_else(|| "this repository is not linked to a vault".to_string())?;
let session = config
.root_key(&instance.url)
.and_then(|root| Session::load(store.clone(), root))
.map_err(|e| e.to_string())?;
if !matches!(
session.lease.state_at(lean_ctx_time::UtcDateTime::now()),
LeaseState::Valid | LeaseState::Grace
) {
return Err("the LeanCTX Cloud lease has lapsed".into());
}
if !session.lease.lease.grants(CloudRight::BusRelay) {
return Err("the LeanCTX Cloud lease does not include the bus".into());
}
Ok(Connected {
store,
session,
vault_id,
})
}
fn decode_lease(value: serde_json::Value) -> Result<BusLeaseV1, CloudError> {
let lease: BusLeaseV1 = serde_json::from_value(value)
.map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
lease
.validate()
.map_err(|e| CloudError::Protocol(format!("bus lease: {e}")))?;
Ok(lease)
}
fn outcome(answer: Result<BusLeaseV1, CloudError>) -> Outcome {
match answer {
Ok(BusLeaseV1 {
granted: true,
lease_id: Some(lease_id),
fencing_token: Some(fencing_token),
expires_at: Some(expires_at),
..
}) => Outcome::Granted {
lease_id,
fencing_token,
expires_at: expires_at.as_str().to_string(),
},
Ok(BusLeaseV1 {
holder: Some(holder),
..
}) => Outcome::Held {
agent_id: holder.agent_id,
instance_id: holder.instance_id,
expires_at: holder.expires_at.as_str().to_string(),
},
Ok(_) => Outcome::Local("LeanCTX Cloud sent an incomplete lease".into()),
Err(CloudError::Vetoed) => Outcome::Vetoed,
Err(CloudError::NotFound) => Outcome::Superseded,
Err(CloudError::Offline(why)) => {
Outcome::Local(format!("LeanCTX Cloud unreachable ({why})"))
}
Err(error) => Outcome::Local(error.to_string()),
}
}
pub fn acquire(
project_root: &Path,
agent_id: &str,
target: &str,
duration_ms: u64,
local_ref: &str,
settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
) -> Outcome {
let connected = match connected(project_root) {
Ok(connected) => connected,
Err(why) => return Outcome::Local(why),
};
if normalize_target(project_root, target).is_none() {
return Outcome::Local("the target is outside the project".into());
}
let (root, agent, target, local) = (
project_root.to_path_buf(),
agent_id.to_string(),
target.to_string(),
local_ref.to_string(),
);
pending().insert(local.clone());
crate::background::submit(&caller(agent_id), move || {
let outcome = acquire_with(&connected, &root, &agent, &target, duration_ms, &local);
pending().remove(&local);
settle(outcome)
});
Outcome::Pending
}
fn acquire_with(
c: &Connected,
project_root: &Path,
agent_id: &str,
target: &str,
duration_ms: u64,
local_ref: &str,
) -> Outcome {
let Some((kind, normalized)) = normalize_target(project_root, target) else {
return Outcome::Local("the target is outside the project".into());
};
let deadline = Instant::now() + BUDGET;
let body = json!({
"schema": BUS_LEASE_REQUEST_SCHEMA,
"resource_kind": kind,
"resource_ref": resource_ref(&c.vault_id, kind, &normalized),
"vault_id": c.vault_id,
"owner_agent_id": agent_id,
"duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
});
let answer = c
.session
.bounded_client(deadline)
.and_then(|client| client.post("/bus/leases", &body))
.and_then(decode_lease);
let result = outcome(answer);
if let Outcome::Granted {
lease_id,
fencing_token,
expires_at,
} = &result
{
let binding = Binding {
lease_id: lease_id.clone(),
fencing_token: *fencing_token,
vault_id: c.vault_id.clone(),
expires_at: expires_at.clone(),
};
if let Err(error) = Bindings::mutate(c.store.data_dir(), |b| {
b.leases.insert(local_ref.to_string(), binding);
}) {
return Outcome::Local(format!("could not record the LeanCTX Cloud lease: {error}"));
}
}
result
}
pub fn renew(
project_root: &Path,
agent_id: &str,
local_ref: &str,
duration_ms: u64,
settle: impl FnOnce(Outcome) -> Option<String> + Send + 'static,
) -> Outcome {
let Ok(store) = CloudStore::open() else {
return Outcome::Local("no LeanCTX Cloud state".into());
};
let bound = Bindings::load(store.data_dir())
.leases
.contains_key(local_ref);
if !bound && !pending().contains(local_ref) {
return Outcome::Local("this lease is local only".into());
}
let connected = match connected(project_root) {
Ok(connected) => connected,
Err(why) => return Outcome::Local(why),
};
let local = local_ref.to_string();
crate::background::submit(&caller(agent_id), move || {
settle(renew_with(&connected, &local, duration_ms))
});
Outcome::Pending
}
fn renew_with(c: &Connected, local_ref: &str, duration_ms: u64) -> Outcome {
let data = c.store.data_dir();
let Some(binding) = Bindings::load(data).leases.get(local_ref).cloned() else {
return Outcome::Local("LeanCTX Cloud did not grant this lease".into());
};
let deadline = Instant::now() + BUDGET;
let body = json!({
"schema": BUS_LEASE_RENEW_REQUEST_SCHEMA,
"fencing_token": binding.fencing_token,
"duration_ms": duration_ms.clamp(1, MAX_BUS_LEASE_MS),
});
let path = format!("/bus/leases/{}/renew", binding.lease_id);
let result = outcome(
c.session
.bounded_client(deadline)
.and_then(|client| client.post(&path, &body))
.and_then(decode_lease),
);
let applied = Bindings::mutate(data, |bindings| {
let same = |b: &Binding| b.lease_id == binding.lease_id;
match &result {
Outcome::Granted { expires_at, .. } => {
if let Some(b) = bindings.leases.get_mut(local_ref).filter(|b| same(b)) {
b.expires_at.clone_from(expires_at);
}
}
Outcome::Superseded | Outcome::Vetoed
if bindings.leases.get(local_ref).is_some_and(same) =>
{
bindings.leases.remove(local_ref);
}
_ => {}
}
});
if let Err(error) = applied {
tracing::debug!("cloud lease bindings not saved: {error}");
}
result
}
pub fn binding(local_ref: &str) -> Option<Binding> {
let store = CloudStore::open().ok()?;
Bindings::load(store.data_dir())
.leases
.get(local_ref)
.cloned()
}
pub fn release(agent_id: &str, local_ref: &str) {
let Ok(store) = CloudStore::open() else {
return;
};
let was_pending = pending().contains(local_ref);
queue_release_in(store.data_dir(), local_ref);
if was_pending {
let (data, local) = (store.data_dir().to_path_buf(), local_ref.to_string());
crate::background::submit(&caller(agent_id), move || {
queue_release_in(&data, &local);
None
});
}
}
fn queue_release_in(data_dir: &Path, local_ref: &str) {
let queued = Bindings::mutate(data_dir, |bindings| {
if let Some(b) = bindings.leases.remove(local_ref) {
bindings.releases.push(Release {
lease_id: b.lease_id,
fencing_token: b.fencing_token,
});
}
});
if let Err(error) = queued {
tracing::debug!("cloud lease release not queued: {error}");
}
}
pub fn send_releases(store: &CloudStore, session: &Session) {
let data = store.data_dir();
let done: Vec<Release> = Bindings::load(data)
.releases
.into_iter()
.filter(|r| {
let path = format!(
"/bus/leases/{}?fencing_token={}",
r.lease_id, r.fencing_token
);
match session.with_client(|client| client.delete(&path)) {
Ok(()) | Err(CloudError::NotFound) => true,
Err(error) => matches!(
error,
CloudError::Forbidden | CloudError::Vetoed | CloudError::Protocol(_)
),
}
})
.collect();
if done.is_empty() {
return;
}
if let Err(error) = Bindings::mutate(data, |b| b.releases.retain(|r| !done.contains(r))) {
tracing::debug!("cloud lease releases not saved: {error}");
}
}
pub fn scope_line(outcome: &Outcome) -> String {
match outcome {
Outcome::Granted { .. } | Outcome::Held { .. } | Outcome::Vetoed | Outcome::Superseded => {
"scope=cloud".into()
}
Outcome::Local(why) => {
format!("scope=local ({why}; other machines are not excluded)")
}
Outcome::Pending => {
"scope=pending (LeanCTX Cloud is asked off this call; until it grants, \
other machines are not excluded; its answer comes with your next ctx_agent call)"
.into()
}
}
}
#[cfg(test)]
mod vault_rename_tests {
use super::*;
#[derive(Deserialize)]
#[allow(dead_code)]
struct PreVaBinding {
lease_id: String,
fencing_token: u64,
project_id: String,
expires_at: String,
}
#[test]
fn lease_bindings_keep_pre_va_names() {
let old = r#"{"lease_id":"lse_1","fencing_token":4,"project_id":"v1","expires_at":"2026-10-22T10:00:00Z"}"#;
let read = crate::vault::assert_pre_va_round_trip::<Binding, PreVaBinding>(
old,
"project_id",
"vault_id",
);
assert_eq!((read.vault_id.as_str(), read.fencing_token), ("v1", 4));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_checkout_names_a_file_the_same_way() {
let a = Path::new("/home/ada/src/payments");
let b = Path::new("/Users/bob/work/payments-clone");
let (kind, ta) = normalize_target(a, "/home/ada/src/payments/src/lib.rs").unwrap();
let (_, tb) = normalize_target(b, "./src/../src/lib.rs").unwrap();
assert_eq!((kind, ta.as_str()), ("file", "src/lib.rs"));
assert_eq!(ta, tb);
let pid = "0123456789abcdef0123456789abcdef";
let ref_a = resource_ref(pid, kind, &ta);
assert_eq!(ref_a, resource_ref(pid, kind, &tb));
assert_eq!(ref_a.len(), 64);
assert!(!ref_a.contains("lib"));
assert_ne!(
ref_a,
resource_ref("fedcba9876543210fedcba9876543210", kind, &ta)
);
assert_ne!(ref_a, resource_ref(pid, "symbol", &ta));
assert_eq!(
normalize_target(a, "symbol: Parser::parse"),
Some(("symbol", "Parser::parse".into()))
);
assert_eq!(
normalize_target(a, "/etc/passwd"),
None,
"outside the project"
);
assert_eq!(normalize_target(a, "../other/x.rs"), None);
assert_eq!(normalize_target(a, "symbol:"), None);
}
#[test]
fn answers_map_to_outcomes_and_the_scope_is_always_named() {
let granted = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": true,
"lease_id": "bl_1", "fencing_token": 4, "expires_at": "2026-10-21T12:10:00Z",
"server_time": "2026-10-21T12:00:00Z"});
let out = outcome(decode_lease(granted));
assert!(matches!(
out,
Outcome::Granted {
fencing_token: 4,
..
}
));
assert_eq!(
scope_line(&out),
"scope=cloud",
"the token is never printed"
);
let held = serde_json::json!({"schema": "leanctx.cloud.bus-lease/v1", "granted": false,
"holder": {"agent_id": "beta", "instance_id": "inst_b", "expires_at": "2026-10-21T12:10:00Z"},
"server_time": "2026-10-21T12:00:00Z"});
assert!(
matches!(outcome(decode_lease(held)), Outcome::Held { agent_id, .. } if agent_id == "beta")
);
assert_eq!(outcome(Err(CloudError::Vetoed)), Outcome::Vetoed);
assert_eq!(outcome(Err(CloudError::NotFound)), Outcome::Superseded);
let offline = outcome(Err(CloudError::Offline("timeout".into())));
assert!(
scope_line(&offline).starts_with("scope=local (LeanCTX Cloud unreachable (timeout)")
);
assert!(scope_line(&offline).ends_with("other machines are not excluded)"));
let pending = scope_line(&Outcome::Pending);
assert!(pending.starts_with("scope=pending (") && !pending.contains("fencing"));
}
#[test]
fn without_an_enrollment_no_request_is_made() {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let err = connected_with(&CloudConfig::default(), store.clone(), dir.path())
.err()
.unwrap();
assert_eq!(err, "this machine is not connected to LeanCTX Cloud");
let off = CloudConfig {
bus: CloudBusMode::Off,
..CloudConfig::default()
};
assert_eq!(
connected_with(&off, store, dir.path()).err().unwrap(),
"the LeanCTX Cloud bus is off"
);
}
#[test]
fn bindings_round_trip_and_queue_releases() {
let dir = tempfile::tempdir().unwrap();
let mut b = Bindings::default();
b.leases.insert(
"lease-ref:1".into(),
Binding {
lease_id: "bl_1".into(),
fencing_token: 2,
vault_id: "p".into(),
expires_at: "2026-10-21T12:10:00Z".into(),
},
);
b.save(dir.path()).unwrap();
assert_eq!(Bindings::load(dir.path()), b);
}
}