use std::sync::Arc;
use anyhow::{bail, Context, Result};
use trusty_common::memory_core::palace::Palace;
use trusty_common::memory_core::retrieval::PalaceHandle;
use trusty_common::memory_core::store::OpenIntent;
use trusty_common::memory_core::{LeaseStatus, MaintenanceLease};
pub(crate) fn open_purging_under_lease(
palace: &Palace,
intent: OpenIntent,
lease: &MaintenanceLease,
) -> Result<Arc<PalaceHandle>> {
let purge = lease.try_hold().is_held();
PalaceHandle::open_with_intent_purging(palace, intent, purge)
.with_context(|| format!("open palace {}", palace.id))
}
pub(crate) fn require_lease(lease: &MaintenanceLease) -> Result<()> {
let lock = lease.path().display();
match lease.try_hold() {
LeaseStatus::Held => Ok(()),
LeaseStatus::HeldElsewhere { holder_pid } => {
let holder = holder_pid.map_or_else(|| "unknown".to_string(), |p| p.to_string());
bail!(
"another process (pid {holder}) holds this data root's maintenance lease \
({lock}); stop it and re-run (#8733)"
)
}
LeaseStatus::Unavailable { reason } => bail!(
"the maintenance lease {lock} is unavailable ({reason}); refusing to run \
maintenance without it (#8733)"
),
}
}