use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
use rustix::fs::{FlockOperation, flock};
use rustix::io::Errno;
use crate::error::Result;
#[derive(Debug)]
pub(crate) struct FileLock {
file: File,
}
#[derive(Debug)]
pub(crate) enum Probe {
Missing,
Held,
Acquired(FileLock),
}
impl FileLock {
pub(crate) fn try_exclusive(path: &Path) -> Result<Option<Self>> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)?;
Self::try_lock(file)
}
pub(crate) fn probe(path: &Path) -> Result<Probe> {
let file = match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Probe::Missing),
Err(e) => return Err(e.into()),
};
Ok(match Self::try_lock(file)? {
Some(lock) => Probe::Acquired(lock),
None => Probe::Held,
})
}
fn try_lock(file: File) -> Result<Option<Self>> {
match flock(&file, FlockOperation::NonBlockingLockExclusive) {
Ok(()) => Ok(Some(Self { file })),
Err(Errno::WOULDBLOCK) => Ok(None),
Err(errno) => Err(io::Error::from(errno).into()),
}
}
}
#[derive(Debug)]
pub(crate) struct WriteLock {
file: File,
}
#[derive(Debug)]
pub(crate) struct WriteGuard<'a> {
file: &'a File,
}
impl WriteLock {
pub(crate) fn open(path: &Path) -> Result<Self> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)?;
Ok(Self { file })
}
pub(crate) fn acquire(&self) -> Result<WriteGuard<'_>> {
loop {
match flock(&self.file, FlockOperation::LockExclusive) {
Ok(()) => return Ok(WriteGuard { file: &self.file }),
Err(Errno::INTR) => {}
Err(errno) => return Err(io::Error::from(errno).into()),
}
}
}
}
impl Drop for WriteGuard<'_> {
fn drop(&mut self) {
let _ = flock(self.file, FlockOperation::Unlock);
}
}
impl Drop for FileLock {
fn drop(&mut self) {
let _ = flock(&self.file, FlockOperation::Unlock);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_is_exclusive_until_dropped() {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("writer.lock");
let first = FileLock::try_exclusive(&path).unwrap();
assert!(first.is_some());
assert!(FileLock::try_exclusive(&path).unwrap().is_none());
drop(first);
assert!(FileLock::try_exclusive(&path).unwrap().is_some());
}
#[test]
fn write_lock_excludes_other_holders_until_the_guard_is_dropped() {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("write.lock");
let first = WriteLock::open(&path).unwrap();
let second = WriteLock::open(&path).unwrap();
let guard = first.acquire().unwrap();
assert!(FileLock::try_exclusive(&path).unwrap().is_none());
drop(guard);
let guard = second.acquire().unwrap();
assert!(FileLock::try_exclusive(&path).unwrap().is_none());
drop(guard);
drop(first.acquire().unwrap());
assert!(FileLock::try_exclusive(&path).unwrap().is_some());
}
#[test]
fn probe_tells_missing_held_and_free_apart() {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().join("member.lock");
assert!(matches!(FileLock::probe(&path).unwrap(), Probe::Missing));
assert!(!path.exists(), "the probe never creates the file");
let held = FileLock::try_exclusive(&path).unwrap().unwrap();
assert!(matches!(FileLock::probe(&path).unwrap(), Probe::Held));
drop(held);
assert!(matches!(
FileLock::probe(&path).unwrap(),
Probe::Acquired(_)
));
}
}