use std::collections::BTreeMap;
use std::fs::{File, TryLockError};
use std::path::Path;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::sync::OwnedMutexGuard;
use super::fs;
use crate::Result;
use crate::error::Error;
use crate::name::RunName;
const LOCK_WAIT: Duration = Duration::from_secs(1);
const RETRY: Duration = Duration::from_millis(50);
#[derive(Debug, Default)]
pub(crate) struct RunLocks(Mutex<BTreeMap<RunName, Arc<tokio::sync::Mutex<()>>>>);
#[derive(Debug)]
pub(crate) struct RunLock {
_file: Held,
_here: OwnedMutexGuard<()>,
}
#[derive(Debug)]
struct Held(File);
impl Drop for Held {
fn drop(&mut self) {
if let Err(e) = self.0.unlock() {
tracing::warn!(error = %e, "a lock file wasn't unlocked; it is freed when closed");
}
}
}
impl RunLocks {
pub(crate) async fn acquire(&self, run: &RunName, path: &Path) -> Result<RunLock> {
let mutex = {
let mut runs = self.0.lock().unwrap_or_else(PoisonError::into_inner);
runs.retain(|_, held| Arc::strong_count(held) > 1);
Arc::clone(runs.entry(run.clone()).or_default())
};
let here = mutex.lock_owned().await;
let file = fs::lock_file(path).map_err(Error::io(path, "locked"))?;
match locked_within(&file, LOCK_WAIT).await {
Ok(true) => Ok(RunLock {
_file: Held(file),
_here: here,
}),
Ok(false) => Err(Error::Locked { run: run.to_string() }),
Err(e) => Err(Error::io(path, "locked")(e)),
}
}
}
#[derive(Debug)]
pub(crate) struct HomeLock {
_file: Held,
}
pub(crate) async fn hold(path: &Path, wait: Duration) -> std::io::Result<Option<HomeLock>> {
let file = fs::lock_file(path)?;
Ok(locked_within(&file, wait).await?.then(|| HomeLock { _file: Held(file) }))
}
async fn locked_within(file: &File, wait: Duration) -> std::io::Result<bool> {
let deadline = tokio::time::Instant::now() + wait;
loop {
match file.try_lock() {
Ok(()) => return Ok(true),
Err(TryLockError::WouldBlock) if tokio::time::Instant::now() < deadline => tokio::time::sleep(RETRY).await,
Err(TryLockError::WouldBlock) => return Ok(false),
Err(TryLockError::Error(e)) => return Err(e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn run() -> RunName {
RunName::new("demo").unwrap()
}
#[tokio::test(start_paused = true)]
async fn another_process_holding_the_run_past_the_wait_is_locked() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let other = File::create(&path).unwrap();
other.lock().unwrap();
let locks = RunLocks::default();
assert!(matches!(locks.acquire(&run(), &path).await, Err(Error::Locked { .. })));
drop(other);
let held = locks.acquire(&run(), &path).await.unwrap();
drop(held);
}
#[tokio::test]
async fn a_lock_that_cant_be_taken_fails_closed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
std::fs::create_dir_all(&path).unwrap();
let err = RunLocks::default().acquire(&run(), &path).await.unwrap_err();
assert_eq!(err.code(), crate::ErrorCode::Io, "{err}");
let missing = dir.path().join("gone").join("lock");
let no_folder = RunLocks::default().acquire(&run(), &missing).await.unwrap_err();
assert_eq!(no_folder.code(), crate::ErrorCode::Io, "a lock with no folder to be in: {no_folder}");
}
#[tokio::test(start_paused = true)]
async fn a_second_operation_of_this_runner_waits_for_the_first() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let locks = Arc::new(RunLocks::default());
let first = locks.acquire(&run(), &path).await.unwrap();
let waiting = tokio::spawn({
let (locks, path) = (Arc::clone(&locks), path.clone());
async move { locks.acquire(&run(), &path).await.map(drop) }
});
tokio::time::sleep(Duration::from_secs(5)).await;
assert!(!waiting.is_finished(), "waits while the first holds the run");
drop(first);
waiting.await.unwrap().unwrap();
}
#[tokio::test(start_paused = true)]
async fn the_runs_no_operation_holds_are_let_go() {
let dir = tempfile::tempdir().unwrap();
let locks = RunLocks::default();
for name in ["one", "two", "three"] {
let name = RunName::new(name).unwrap();
drop(locks.acquire(&name, &dir.path().join(format!("{name}.lock"))).await.unwrap());
}
let held = locks.acquire(&run(), &dir.path().join("lock")).await.unwrap();
let kept: Vec<String> = locks.0.lock().unwrap().keys().map(ToString::to_string).collect();
assert_eq!(kept, ["demo"], "only the run held now");
drop(held);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn many_operations_on_a_few_runs_from_several_threads_hold_each_run_one_at_a_time() {
let dir = tempfile::tempdir().unwrap();
let locks = Arc::new(RunLocks::default());
let inside: Arc<[std::sync::atomic::AtomicUsize; 3]> = Arc::default();
let mut ops = tokio::task::JoinSet::new();
for i in 0..64 {
let (locks, inside, dir) = (Arc::clone(&locks), Arc::clone(&inside), dir.path().to_path_buf());
ops.spawn(async move {
let which = i % 3;
let name = RunName::new(&format!("run-{which}")).unwrap();
let path = dir.join(format!("{name}.lock"));
let held = locks.acquire(&name, &path).await.unwrap();
let now = inside[which].fetch_add(1, std::sync::atomic::Ordering::SeqCst);
assert_eq!(now, 0, "two operations held {name} at once");
tokio::time::sleep(Duration::from_millis(2)).await;
inside[which].fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
drop(held);
});
}
while let Some(done) = ops.join_next().await {
done.unwrap();
}
let left = locks.0.lock().unwrap().values().filter(|m| Arc::strong_count(m) > 1).count();
assert_eq!(left, 0, "nothing holds a run once every operation ended");
}
fn spawned_meanwhile(Held(file): &Held) -> File {
file.try_clone().unwrap()
}
#[tokio::test(start_paused = true)]
async fn a_run_released_is_free_at_once_while_a_process_spawned_meanwhile_still_has_its_handle() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
let locks = RunLocks::default();
let held = locks.acquire(&run(), &path).await.unwrap();
let RunLock { _file: file, .. } = &held;
let spawned = spawned_meanwhile(file);
drop(held);
let again = locks.acquire(&run(), &path).await;
assert!(again.is_ok(), "the run is free once released: {again:?}");
drop(spawned);
}
#[tokio::test(start_paused = true)]
async fn a_home_lock_held_elsewhere_past_its_wait_is_not_taken() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ssh.lock");
let other = File::create(&path).unwrap();
other.lock().unwrap();
assert!(hold(&path, Duration::from_secs(30)).await.unwrap().is_none(), "held all along");
drop(other);
let held = hold(&path, Duration::from_secs(30)).await.unwrap().expect("free now");
let again = File::open(&path).unwrap();
assert!(matches!(again.try_lock(), Err(TryLockError::WouldBlock)), "the lock is held while it lives");
drop(held);
again.try_lock().expect("and freed with it");
}
}