use std::fs::{File, TryLockError};
use std::path::PathBuf;
use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail, ensure};
use super::Store;
const LOCK_FILE: &str = "openmoat.lock";
pub const WAIT: Duration = Duration::from_secs(10);
const POLL: Duration = Duration::from_millis(25);
#[derive(Debug)]
pub struct Held {
_file: File,
dir: PathBuf,
}
impl Store {
pub fn lock(&self, wait: Duration) -> Result<Held> {
let path = self.dir.join(LOCK_FILE);
let file = crate::home::private_lock_options()
.open(&path)
.with_context(|| format!("opening {}", path.display()))?;
let started = Instant::now();
loop {
match file.try_lock() {
Ok(()) => {
return Ok(Held {
_file: file,
dir: self.dir.clone(),
});
}
Err(TryLockError::WouldBlock) if started.elapsed() < wait => {
std::thread::sleep(POLL);
}
Err(TryLockError::WouldBlock) => bail!(
"another `openmoat run`, `openmoat snapshot` or `openmoat restore` is using \
the snapshot store of {}; try again when it is done",
self.project.display()
),
Err(TryLockError::Error(e)) => {
return Err(e).context("locking the snapshot store");
}
}
}
}
pub(super) fn check_held(&self, held: &Held) -> Result<()> {
ensure!(
held.dir == self.dir,
"the lock held is another snapshot store's"
);
Ok(())
}
}