use std::{
collections::{btree_map::Entry, BTreeMap},
fmt,
fs::{File, OpenOptions},
num::NonZeroUsize,
path::{Path, PathBuf},
sync::{Mutex, PoisonError},
};
use super::{id_match::short_id, layout};
static HELD: Mutex<BTreeMap<PathBuf, HeldLock>> = Mutex::new(BTreeMap::new());
struct HeldLock {
file: File,
hold: Hold,
}
#[derive(Clone, Copy)]
enum Hold {
Open { holders: NonZeroUsize },
Delete,
}
#[derive(Clone, Copy, Debug)]
pub(super) enum LeasePurpose {
Open,
Delete,
}
#[derive(Debug)]
pub(crate) struct SessionLease {
path: PathBuf,
}
#[derive(Debug)]
pub(crate) struct SessionInUse {
id: String,
by: InUseBy,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InUseBy {
OtherProcess,
OpenHere,
DeletingHere,
}
impl SessionInUse {
#[cfg(test)]
pub(crate) fn by(&self) -> InUseBy {
self.by
}
}
impl fmt::Display for SessionInUse {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let id = short_id(&self.id);
match self.by {
InUseBy::OtherProcess => write!(
formatter,
"session '{id}' is open in another Rho process; close it there first"
),
InUseBy::OpenHere => write!(formatter, "session '{id}' is open; close it first"),
InUseBy::DeletingHere => write!(
formatter,
"session '{id}' is being deleted; refresh the session list"
),
}
}
}
impl std::error::Error for SessionInUse {}
fn lock_file_name(id: &str) -> String {
format!(".{id}.active.lock")
}
fn lock_path(session_root: &Path, cwd: &Path, id: &str) -> PathBuf {
layout::session_dir_in_root(session_root, cwd).join(lock_file_name(id))
}
pub(super) fn acquire(
session_root: &Path,
cwd: &Path,
id: &str,
purpose: LeasePurpose,
) -> anyhow::Result<SessionLease> {
let path = lock_path(session_root, cwd, id);
let in_use = |by| SessionInUse {
id: id.to_owned(),
by,
};
let mut held = HELD.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(lock) = held.get_mut(&path) {
return match (lock.hold, purpose) {
(Hold::Open { holders }, LeasePurpose::Open) => {
lock.hold = Hold::Open {
holders: holders.saturating_add(1),
};
Ok(SessionLease { path })
}
(Hold::Open { .. }, LeasePurpose::Delete) => Err(in_use(InUseBy::OpenHere).into()),
(Hold::Delete, _) => Err(in_use(InUseBy::DeletingHere).into()),
};
}
let dir = layout::ensure_session_dir(session_root, cwd)?;
let file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(dir.join(lock_file_name(id)))?;
layout::set_private_file_permissions(&file)?;
if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) {
let contended = error.kind() == std::io::ErrorKind::WouldBlock
|| error.raw_os_error() == fs2::lock_contended_error().raw_os_error();
return Err(if contended {
in_use(InUseBy::OtherProcess).into()
} else {
error.into()
});
}
let hold = match purpose {
LeasePurpose::Open => Hold::Open {
holders: NonZeroUsize::MIN,
},
LeasePurpose::Delete => Hold::Delete,
};
held.insert(path.clone(), HeldLock { file, hold });
Ok(SessionLease { path })
}
impl SessionLease {
#[cfg(test)]
pub(crate) fn inherited_handle_for_tests(&self) -> File {
let held = HELD.lock().unwrap_or_else(PoisonError::into_inner);
held[&self.path].file.try_clone().unwrap()
}
}
impl Clone for SessionLease {
fn clone(&self) -> Self {
let mut held = HELD.lock().unwrap_or_else(PoisonError::into_inner);
let lock = held
.get_mut(&self.path)
.expect("a live lease's lock is held");
match lock.hold {
Hold::Open { holders } => {
lock.hold = Hold::Open {
holders: holders.saturating_add(1),
};
}
Hold::Delete => unreachable!("a delete lease is never cloned"),
}
Self {
path: self.path.clone(),
}
}
}
impl Drop for SessionLease {
fn drop(&mut self) {
let mut held = HELD.lock().unwrap_or_else(PoisonError::into_inner);
let Entry::Occupied(mut lock) = held.entry(std::mem::take(&mut self.path)) else {
debug_assert!(false, "a live lease's lock is held");
return;
};
let remaining = match lock.get().hold {
Hold::Open { holders } => NonZeroUsize::new(holders.get() - 1),
Hold::Delete => None,
};
match remaining {
Some(holders) => lock.get_mut().hold = Hold::Open { holders },
None => {
let _ = fs2::FileExt::unlock(&lock.remove().file);
}
}
}
}
#[cfg(test)]
#[path = "lease_tests.rs"]
mod tests;