1use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError, TryLockError};
9use std::time::{Duration, Instant};
10
11pub const DIR_LOCK_WAIT: Duration = Duration::from_secs(10);
14
15const RETRY_BACKOFF: Duration = Duration::from_millis(20);
16
17#[derive(Debug, thiserror::Error)]
19#[error("the directory {} is locked by another holder", dir.display())]
20pub struct LockTimeout {
21 pub dir: PathBuf,
22}
23
24impl LockTimeout {
25 pub fn of(error: &std::io::Error) -> Option<&Self> {
26 error.get_ref()?.downcast_ref()
27 }
28}
29
30pub struct DirLock {
31 dir: PathBuf,
32 _process: MutexGuard<'static, ()>,
33 #[cfg(unix)]
34 handle: std::fs::File,
35}
36
37impl DirLock {
38 pub fn acquire(dir: &Path) -> std::io::Result<Self> {
40 std::fs::create_dir_all(dir)?;
41 let dir = dir.canonicalize()?;
42 let process = process_lock(&dir);
43 #[cfg(unix)]
44 let handle = {
45 let handle = std::fs::File::open(&dir)?;
46 flock_exclusive(&handle)?;
47 handle
48 };
49 Ok(Self {
50 dir,
51 _process: process,
52 #[cfg(unix)]
53 handle,
54 })
55 }
56
57 pub fn acquire_within(dir: &Path, wait: Duration) -> std::io::Result<Self> {
61 std::fs::create_dir_all(dir)?;
62 let dir = dir.canonicalize()?;
63 let deadline = Instant::now() + wait;
64 let timed_out =
65 |dir: PathBuf| std::io::Error::new(std::io::ErrorKind::TimedOut, LockTimeout { dir });
66 let process = loop {
67 match try_process_lock(&dir) {
68 Some(guard) => break guard,
69 None if Instant::now() >= deadline => return Err(timed_out(dir)),
70 None => std::thread::sleep(RETRY_BACKOFF),
71 }
72 };
73 #[cfg(unix)]
74 let handle = {
75 let handle = std::fs::File::open(&dir)?;
76 while !try_flock_exclusive(&handle)? {
77 if Instant::now() >= deadline {
78 return Err(timed_out(dir));
79 }
80 std::thread::sleep(RETRY_BACKOFF);
81 }
82 handle
83 };
84 Ok(Self {
85 dir,
86 _process: process,
87 #[cfg(unix)]
88 handle,
89 })
90 }
91
92 pub fn dir(&self) -> &Path {
94 &self.dir
95 }
96
97 pub fn sync(&self) {
99 #[cfg(unix)]
100 let _ = self.handle.sync_all();
101 }
102}
103
104fn process_lock(dir: &Path) -> MutexGuard<'static, ()> {
107 process_mutex(dir)
108 .lock()
109 .unwrap_or_else(PoisonError::into_inner)
110}
111
112fn try_process_lock(dir: &Path) -> Option<MutexGuard<'static, ()>> {
113 match process_mutex(dir).try_lock() {
114 Ok(guard) => Some(guard),
115 Err(TryLockError::Poisoned(e)) => Some(e.into_inner()),
116 Err(TryLockError::WouldBlock) => None,
117 }
118}
119
120fn process_mutex(dir: &Path) -> &'static Mutex<()> {
121 static LOCKS: OnceLock<Mutex<HashMap<PathBuf, &'static Mutex<()>>>> = OnceLock::new();
122 let mut locks = LOCKS
123 .get_or_init(Default::default)
124 .lock()
125 .unwrap_or_else(PoisonError::into_inner);
126 let lock: &'static Mutex<()> = match locks.get(dir) {
127 Some(lock) => lock,
128 None => {
129 let lock = Box::leak(Box::default());
130 locks.insert(dir.to_path_buf(), lock);
131 lock
132 }
133 };
134 lock
135}
136
137#[cfg(unix)]
138fn flock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
139 use std::os::fd::AsRawFd;
140 loop {
141 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 {
143 return Ok(());
144 }
145 let e = std::io::Error::last_os_error();
146 if e.kind() != std::io::ErrorKind::Interrupted {
147 return Err(e);
148 }
149 }
150}
151
152#[cfg(unix)]
153fn try_flock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
154 use std::os::fd::AsRawFd;
155 loop {
156 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
158 return Ok(true);
159 }
160 let e = std::io::Error::last_os_error();
161 match e.kind() {
162 std::io::ErrorKind::Interrupted => {}
163 std::io::ErrorKind::WouldBlock => return Ok(false),
164 _ => return Err(e),
165 }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[cfg(unix)]
174 fn hold_flock(dir: &Path) -> std::fs::File {
175 use std::os::fd::AsRawFd;
176 let file = std::fs::File::open(dir).unwrap();
177 assert_eq!(unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }, 0);
179 file
180 }
181
182 #[cfg(unix)]
183 #[test]
184 fn a_directory_another_flock_holds_times_out_and_then_opens() {
185 let dir = tempfile::tempdir().unwrap();
186 let held = hold_flock(dir.path());
187 let err = DirLock::acquire_within(dir.path(), Duration::from_millis(100))
188 .err()
189 .expect("the directory is held");
190 assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
191 let timeout = LockTimeout::of(&err).expect("a LockTimeout");
192 assert_eq!(timeout.dir, dir.path().canonicalize().unwrap());
193 drop(held);
194 DirLock::acquire_within(dir.path(), Duration::from_secs(5)).unwrap();
195 }
196
197 #[test]
198 fn a_directory_this_process_holds_times_out_and_then_opens() {
199 let dir = tempfile::tempdir().unwrap();
200 let held = DirLock::acquire(dir.path()).unwrap();
201 let err = DirLock::acquire_within(dir.path(), Duration::from_millis(100))
202 .err()
203 .expect("the directory is held");
204 assert!(LockTimeout::of(&err).is_some());
205 drop(held);
206 DirLock::acquire_within(dir.path(), Duration::from_secs(5)).unwrap();
207 }
208
209 #[test]
210 fn other_errors_are_not_a_timeout() {
211 let err = std::io::Error::other("x");
212 assert!(LockTimeout::of(&err).is_none());
213 }
214}