use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};
use crate::error::{KitError, KitResult};
pub const STALE_AFTER: Duration = Duration::from_secs(30 * 60);
const POLL_INTERVAL: Duration = Duration::from_millis(120);
#[derive(Debug)]
pub struct FileLock {
path: PathBuf,
}
impl FileLock {
pub fn acquire(path: &Path, timeout: Duration) -> KitResult<Self> {
Self::acquire_with_stale_after(path, timeout, STALE_AFTER)
}
pub(crate) fn acquire_with_stale_after(
path: &Path,
timeout: Duration,
stale_after: Duration,
) -> KitResult<Self> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|source| KitError::LockIo {
path: path.to_path_buf(),
source,
})?;
}
let deadline = Instant::now() + timeout;
loop {
match Self::try_create(path) {
Ok(lock) => return Ok(lock),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
if Self::take_over_if_stale(path, stale_after)? {
continue;
}
if Instant::now() >= deadline {
return Err(KitError::LockTimeout {
path: path.to_path_buf(),
secs: timeout.as_secs(),
});
}
std::thread::sleep(POLL_INTERVAL);
}
Err(source) => {
return Err(KitError::LockIo {
path: path.to_path_buf(),
source,
})
}
}
}
}
fn try_create(path: &Path) -> std::io::Result<Self> {
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)?;
let _ = writeln!(f, "pid={} at={:?}", std::process::id(), SystemTime::now());
Ok(Self {
path: path.to_path_buf(),
})
}
fn take_over_if_stale(path: &Path, stale_after: Duration) -> KitResult<bool> {
let Ok(meta) = std::fs::metadata(path) else {
return Ok(true);
};
let Ok(modified) = meta.modified() else {
return Ok(false);
};
let Ok(age) = SystemTime::now().duration_since(modified) else {
return Ok(false);
};
if age < stale_after {
return Ok(false);
}
match std::fs::remove_file(path) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(source) => Err(KitError::LockIo {
path: path.to_path_buf(),
source,
}),
}
}
}
impl Drop for FileLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lock_path(dir: &tempfile::TempDir) -> PathBuf {
dir.path().join(".lock")
}
#[test]
fn acquires_and_creates_parent_directories() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested").join("deeper").join(".lock");
let lock = FileLock::acquire(&path, Duration::from_millis(50)).expect("should acquire");
assert!(path.is_file(), "the lock file should have been created");
drop(lock);
}
#[test]
fn releases_on_drop() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
{
let _lock = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
assert!(path.is_file());
}
assert!(!path.exists(), "the lock file should be deleted on drop");
}
#[test]
fn a_second_holder_times_out() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
let _first = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
let err = FileLock::acquire(&path, Duration::from_millis(120));
assert!(
matches!(err, Err(KitError::LockTimeout { .. })),
"expected LockTimeout, got {err:?}"
);
}
#[test]
fn a_later_holder_succeeds_after_release() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
let first = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
drop(first);
let _second = FileLock::acquire(&path, Duration::from_millis(200)).expect("should acquire");
}
#[test]
fn takes_over_a_stale_lock() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
std::fs::write(&path, "pid=1 at=<stale>").unwrap();
let _lock =
FileLock::acquire_with_stale_after(&path, Duration::from_millis(500), Duration::ZERO)
.expect("a stale lock should be taken over");
}
#[test]
fn does_not_steal_a_fresh_lock() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
std::fs::write(&path, "pid=1 at=<fresh>").unwrap();
let err =
FileLock::acquire_with_stale_after(&path, Duration::from_millis(120), STALE_AFTER);
assert!(
matches!(err, Err(KitError::LockTimeout { .. })),
"a fresh lock must not be stolen"
);
}
#[test]
fn writes_diagnostic_content() {
let dir = tempfile::tempdir().unwrap();
let path = lock_path(&dir);
let _lock = FileLock::acquire(&path, Duration::from_millis(50)).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("pid="), "lock file content: {text:?}");
assert!(text.contains(&std::process::id().to_string()));
}
}