use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
thread_local! {
static HELD: RefCell<HashMap<PathBuf, (File, usize)>> = RefCell::new(HashMap::new());
}
fn nest(path: &Path) -> bool {
HELD.with(|held| {
if let Some((_, count)) = held.borrow_mut().get_mut(path) {
*count += 1;
true
} else {
false
}
})
}
fn open(path: &Path) -> io::Result<File> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
let gitignore = dir.join(".gitignore");
if !gitignore.exists() {
let _ = std::fs::write(&gitignore, "*\n");
}
}
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
}
pub(crate) fn acquire(path: &Path) -> io::Result<()> {
if nest(path) {
return Ok(());
}
let file = open(path)?;
file.lock()?;
HELD.with(|held| held.borrow_mut().insert(path.to_path_buf(), (file, 1)));
Ok(())
}
pub(crate) fn acquire_within(path: &Path, limit: Option<std::time::Duration>) -> io::Result<bool> {
let Some(limit) = limit else {
return acquire(path).map(|()| true);
};
if nest(path) {
return Ok(true);
}
let file = open(path)?;
let started = std::time::Instant::now();
let mut pause = std::time::Duration::from_millis(1);
loop {
match file.try_lock() {
Ok(()) => {
HELD.with(|held| held.borrow_mut().insert(path.to_path_buf(), (file, 1)));
return Ok(true);
}
Err(std::fs::TryLockError::WouldBlock) => {}
Err(std::fs::TryLockError::Error(e)) => return Err(e),
}
let waited = started.elapsed();
if waited >= limit {
return Ok(false);
}
std::thread::sleep(pause.min(limit - waited));
pause = (pause * 2).min(std::time::Duration::from_millis(50));
}
}
pub(crate) fn try_acquire(path: &Path) -> io::Result<bool> {
if nest(path) {
return Ok(true);
}
let file = open(path)?;
match file.try_lock() {
Ok(()) => {
HELD.with(|held| held.borrow_mut().insert(path.to_path_buf(), (file, 1)));
Ok(true)
}
Err(std::fs::TryLockError::WouldBlock) => Ok(false),
Err(std::fs::TryLockError::Error(e)) => Err(e),
}
}
pub(crate) fn holds_another(path: &Path) -> bool {
HELD.with(|held| {
let held = held.borrow();
!held.is_empty() && !held.contains_key(path)
})
}
pub(crate) fn release(path: &Path) {
HELD.with(|held| {
let mut held = held.borrow_mut();
let last = match held.get_mut(path) {
Some((_, count)) => {
*count -= 1;
*count == 0
}
None => false,
};
if last && let Some((file, _)) = held.remove(path) {
let _ = file.unlock();
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
use std::time::{Duration, Instant};
fn hold(path: &Path) -> (mpsc::Sender<()>, std::thread::JoinHandle<()>) {
let (held_tx, held_rx) = mpsc::channel();
let (go_tx, go_rx) = mpsc::channel::<()>();
let path = path.to_path_buf();
let handle = std::thread::spawn(move || {
acquire(&path).unwrap();
held_tx.send(()).unwrap();
let _ = go_rx.recv();
release(&path);
});
held_rx.recv().unwrap();
(go_tx, handle)
}
#[test]
fn a_held_lock_ends_the_wait_at_the_limit_and_holds_nothing() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("write.lock");
let (go, holder) = hold(&path);
let started = Instant::now();
let limit = Duration::from_millis(300);
assert!(!acquire_within(&path, Some(limit)).unwrap());
let waited = started.elapsed();
assert!(waited >= limit, "waited only {waited:?}");
assert!(waited < Duration::from_secs(5), "waited {waited:?}");
assert!(
!try_acquire(&path).unwrap(),
"the timed-out wait left no hold behind on this thread"
);
go.send(()).unwrap();
holder.join().unwrap();
assert!(acquire_within(&path, Some(limit)).unwrap());
release(&path);
}
#[test]
fn a_lock_released_inside_the_limit_is_taken() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("write.lock");
let (go, holder) = hold(&path);
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
go.send(()).unwrap();
});
let started = Instant::now();
assert!(acquire_within(&path, Some(Duration::from_secs(10))).unwrap());
assert!(started.elapsed() >= Duration::from_millis(100));
release(&path);
releaser.join().unwrap();
holder.join().unwrap();
}
#[test]
fn no_limit_waits_until_the_holder_lets_go() {
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("write.lock");
let (go, holder) = hold(&path);
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(300));
go.send(()).unwrap();
});
let started = Instant::now();
assert!(acquire_within(&path, None).unwrap());
assert!(started.elapsed() >= Duration::from_millis(250));
release(&path);
releaser.join().unwrap();
holder.join().unwrap();
}
}