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 GRACE: Duration = Duration::from_secs(1);
const RETRY: Duration = Duration::from_millis(50);
const SLOTS_WAIT: Duration = Duration::from_secs(30);
#[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 = Arc::clone(self.0.lock().unwrap_or_else(PoisonError::into_inner).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, GRACE).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)),
}
}
}
pub(crate) fn held(path: &Path) -> std::io::Result<bool> {
let Some(file) = fs::if_there(std::fs::OpenOptions::new().read(true).open(path))? else {
return Ok(false);
};
match file.try_lock() {
Ok(()) => {
drop(Held(file));
Ok(false)
}
Err(TryLockError::WouldBlock) => Ok(true),
Err(TryLockError::Error(e)) => Err(e),
}
}
#[derive(Debug)]
pub(crate) struct SlotsLock {
_file: Held,
}
pub(crate) async fn hold_slots(path: &Path) -> Result<SlotsLock> {
let file = fs::lock_file(path).map_err(Error::io(path, "locked"))?;
match locked_within(&file, SLOTS_WAIT).await {
Ok(true) => Ok(SlotsLock { _file: Held(file) }),
Ok(false) => Err(Error::SlotsLocked {
waited_s: SLOTS_WAIT.as_secs(),
}),
Err(e) => Err(Error::io(path, "locked")(e)),
}
}
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]
async fn another_process_holding_the_run_keeps_it_busy() {
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");
assert!(RunLocks::default().acquire(&run(), &missing).await.is_err());
}
#[tokio::test]
async fn a_run_reads_as_held_while_an_operation_holds_it_and_the_reading_takes_nothing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lock");
assert!(!held(&path).unwrap(), "no lock file: never held");
let locks = RunLocks::default();
let op = locks.acquire(&run(), &path).await.unwrap();
assert!(held(&path).unwrap(), "this process's operation holds it");
drop(op);
assert!(!held(&path).unwrap());
let other = File::options().write(true).open(&path).unwrap();
other.lock().unwrap();
assert!(held(&path).unwrap());
drop(other);
assert!(!held(&path).unwrap());
locks.acquire(&run(), &path).await.unwrap();
}
#[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();
}
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 the_slots_released_are_free_at_once_while_a_process_spawned_meanwhile_still_has_their_handle() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("slots.lock");
let held = hold_slots(&path).await.unwrap();
let SlotsLock { _file: file } = &held;
let spawned = spawned_meanwhile(file);
drop(held);
let again = hold_slots(&path).await;
assert!(again.is_ok(), "the slots are free once released: {again:?}");
drop(spawned);
}
#[tokio::test(start_paused = true)]
async fn a_slot_pick_waits_for_another_processes_then_takes_the_slots() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("slots.lock");
let other = File::create(&path).unwrap();
other.lock().unwrap();
let waiting = tokio::spawn({
let path = path.clone();
async move { hold_slots(&path).await.map(drop) }
});
tokio::time::sleep(Duration::from_secs(5)).await;
assert!(!waiting.is_finished(), "waits while another process picks");
drop(other);
waiting.await.unwrap().unwrap();
let held = hold_slots(&path).await.unwrap();
let stuck = hold_slots(&path).await.unwrap_err();
assert_eq!(stuck.code(), crate::ErrorCode::Locked, "busy, not an I/O failure: {stuck}");
assert_eq!(stuck.to_string(), "another start has held this home's slot pick for 30 s; it may hang");
drop(held);
}
}