1use std::collections::{BTreeSet, HashMap};
3use std::fs::File;
4use std::io::{Error, ErrorKind};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
7use std::time::{Duration, Instant};
8
9const RETRY_INTERVAL: Duration = Duration::from_millis(10);
10
11pub fn is_contended(error: &Error) -> bool {
12 error.kind() == ErrorKind::WouldBlock
13 || error
14 .raw_os_error()
15 .zip(fs2::lock_contended_error().raw_os_error())
16 .is_some_and(|(error_code, contended_code)| error_code == contended_code)
17}
18
19pub fn acquire_exclusive_timeout(file: &File, timeout: Duration) -> Result<(), String> {
30 use fs2::FileExt;
31
32 let deadline = Instant::now() + timeout;
33 loop {
34 match file.try_lock_exclusive() {
35 Ok(()) => return Ok(()),
36 Err(error) if is_contended(&error) => {
37 if Instant::now() >= deadline {
38 return Err(format!(
39 "still held after {}ms — giving up rather than blocking",
40 timeout.as_millis()
41 ));
42 }
43 std::thread::sleep(RETRY_INTERVAL);
44 }
45 Err(error) => return Err(error.to_string()),
46 }
47 }
48}
49
50#[derive(Debug)]
62pub struct FlockGuard {
63 file: File,
64}
65
66impl FlockGuard {
67 pub fn try_exclusive(file: File) -> std::io::Result<Option<Self>> {
69 match fs2::FileExt::try_lock_exclusive(&file) {
70 Ok(()) => Ok(Some(Self { file })),
71 Err(error) if is_contended(&error) => Ok(None),
72 Err(error) => Err(error),
73 }
74 }
75
76 pub fn try_shared(file: File) -> std::io::Result<Option<Self>> {
78 match fs2::FileExt::try_lock_shared(&file) {
79 Ok(()) => Ok(Some(Self { file })),
80 Err(error) if is_contended(&error) => Ok(None),
81 Err(error) => Err(error),
82 }
83 }
84
85 pub fn exclusive(file: File) -> std::io::Result<Self> {
87 fs2::FileExt::lock_exclusive(&file)?;
88 Ok(Self { file })
89 }
90
91 pub fn shared(file: File) -> std::io::Result<Self> {
93 fs2::FileExt::lock_shared(&file)?;
94 Ok(Self { file })
95 }
96
97 pub fn exclusive_timeout(file: File, timeout: Duration) -> Result<Self, String> {
100 acquire_exclusive_timeout(&file, timeout)?;
101 Ok(Self { file })
102 }
103
104 pub fn from_locked(file: File) -> Self {
107 Self { file }
108 }
109
110 pub fn file(&self) -> &File {
112 &self.file
113 }
114}
115
116impl std::ops::Deref for FlockGuard {
117 type Target = File;
118
119 fn deref(&self) -> &File {
120 &self.file
121 }
122}
123
124impl Drop for FlockGuard {
125 fn drop(&mut self) {
126 let _ = fs2::FileExt::unlock(&self.file);
127 }
128}
129
130pub struct Turn {
143 path: PathBuf,
144 queue: Arc<Queue>,
145}
146
147#[derive(Default)]
148struct Queue {
149 line: Mutex<Line>,
150 moved: Condvar,
151}
152
153#[derive(Default)]
154struct Line {
155 next: u64,
157 serving: u64,
158 abandoned: BTreeSet<u64>,
160}
161
162impl Line {
163 fn advance(&mut self) {
164 self.serving += 1;
165 while self.abandoned.remove(&self.serving) {
166 self.serving += 1;
167 }
168 }
169
170 fn idle(&self) -> bool {
171 self.serving == self.next
172 }
173}
174
175fn queues() -> &'static Mutex<HashMap<PathBuf, Arc<Queue>>> {
176 static QUEUES: OnceLock<Mutex<HashMap<PathBuf, Arc<Queue>>>> = OnceLock::new();
177 QUEUES.get_or_init(Mutex::default)
178}
179
180fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
181 mutex.lock().unwrap_or_else(PoisonError::into_inner)
182}
183
184#[must_use]
192pub fn take_turn(path: &Path, timeout: Duration) -> Option<Turn> {
193 let (queue, ticket) = {
196 let mut map = locked(queues());
197 let queue = Arc::clone(map.entry(path.to_path_buf()).or_default());
198 let mut line = locked(&queue.line);
199 let ticket = line.next;
200 line.next += 1;
201 drop(line);
202 drop(map);
203 (queue, ticket)
204 };
205 let mut line = locked(&queue.line);
206 let mut seen = line.serving;
207 let mut deadline = Instant::now() + timeout;
208 while line.serving != ticket {
209 let now = Instant::now();
210 if line.serving != seen {
211 seen = line.serving;
212 deadline = now + timeout;
213 }
214 let left = deadline.saturating_duration_since(now);
215 if left.is_zero() {
216 line.abandoned.insert(ticket);
217 return None;
218 }
219 line = queue
220 .moved
221 .wait_timeout(line, left)
222 .unwrap_or_else(PoisonError::into_inner)
223 .0;
224 }
225 drop(line);
226 Some(Turn {
227 path: path.to_path_buf(),
228 queue,
229 })
230}
231
232impl Drop for Turn {
233 fn drop(&mut self) {
234 let mut map = locked(queues());
235 let mut line = locked(&self.queue.line);
236 line.advance();
237 if line.idle() {
238 map.remove(&self.path);
239 }
240 drop(line);
241 drop(map);
242 self.queue.moved.notify_all();
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::{FlockGuard, acquire_exclusive_timeout, is_contended, locked, queues, take_turn};
249 use std::io::{Error, ErrorKind};
250 use std::path::Path;
251 use std::time::{Duration, Instant};
252
253 fn tickets_drawn(path: &Path) -> u64 {
255 locked(queues())
256 .get(path)
257 .map_or(0, |queue| locked(&queue.line).next)
258 }
259
260 fn wait_for_tickets(path: &Path, drawn: u64) {
261 let deadline = Instant::now() + Duration::from_secs(10);
262 while tickets_drawn(path) < drawn {
263 assert!(Instant::now() < deadline, "ticket {drawn} never drawn");
264 std::thread::sleep(Duration::from_millis(1));
265 }
266 }
267
268 #[test]
273 fn an_abandoned_ticket_is_skipped_and_the_idle_queue_removed() {
274 let dir = tempfile::tempdir().expect("tempdir");
275 let path = dir.path().join("abandoned.lock");
276
277 let holder = take_turn(&path, Duration::from_secs(1)).expect("free turn");
278 let quitter = {
279 let path = path.clone();
280 std::thread::spawn(move || take_turn(&path, Duration::from_millis(100)).is_none())
281 };
282 wait_for_tickets(&path, 2);
283 let patient = {
284 let path = path.clone();
285 std::thread::spawn(move || {
286 let turn = take_turn(&path, Duration::from_secs(30));
287 (turn.is_some(), Instant::now())
288 })
289 };
290 wait_for_tickets(&path, 3);
291
292 assert!(
293 quitter.join().expect("quitter"),
294 "the middle waiter must give up while the holder keeps its turn"
295 );
296 let released = Instant::now();
297 drop(holder);
298 let (got_turn, served) = patient.join().expect("patient");
299
300 assert!(
301 got_turn,
302 "the waiter behind an abandoned ticket gets its turn"
303 );
304 let handover = served.saturating_duration_since(released);
305 assert!(
306 handover < Duration::from_secs(5),
307 "the abandoned ticket must be skipped, handover took {handover:?}"
308 );
309 assert!(
310 !locked(queues()).contains_key(&path),
311 "an idle queue must leave the map"
312 );
313 }
314
315 fn lock_file(dir: &Path) -> std::fs::File {
316 std::fs::OpenOptions::new()
317 .create(true)
318 .truncate(false)
319 .write(true)
320 .open(dir.join("guard.lock"))
321 .expect("open lock file")
322 }
323
324 #[test]
325 fn try_exclusive_reports_a_held_lock_as_none() {
326 let dir = tempfile::tempdir().expect("tempdir");
327 let held = FlockGuard::try_exclusive(lock_file(dir.path()))
328 .expect("lock")
329 .expect("free lock");
330 assert!(
331 FlockGuard::try_exclusive(lock_file(dir.path()))
332 .expect("try")
333 .is_none(),
334 "a held lock must read as busy"
335 );
336 assert!(
337 FlockGuard::try_shared(lock_file(dir.path()))
338 .expect("try shared")
339 .is_none(),
340 "an exclusive holder excludes shared lockers"
341 );
342 drop(held);
343 assert!(
344 FlockGuard::try_exclusive(lock_file(dir.path()))
345 .expect("try")
346 .is_some(),
347 "a dropped guard frees the lock"
348 );
349 }
350
351 #[test]
355 fn a_duplicated_handle_does_not_outlive_the_guard() {
356 let dir = tempfile::tempdir().expect("tempdir");
357 let guard = FlockGuard::exclusive(lock_file(dir.path())).expect("lock");
358 let inherited = guard.file().try_clone().expect("duplicate handle");
359 drop(guard);
360 assert!(
361 FlockGuard::try_exclusive(lock_file(dir.path()))
362 .expect("try")
363 .is_some(),
364 "the lock must end with the guard, not with the last copy"
365 );
366 drop(inherited);
367 }
368
369 #[test]
370 fn a_duplicated_handle_does_not_outlive_a_guard_dropped_by_unwinding() {
371 let dir = tempfile::tempdir().expect("tempdir");
372 let mut inherited = None;
373 let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
374 let guard =
375 FlockGuard::exclusive_timeout(lock_file(dir.path()), Duration::from_secs(1))
376 .expect("lock");
377 inherited = Some(guard.try_clone().expect("duplicate handle"));
378 panic!("the critical section fails");
379 }));
380 assert!(unwound.is_err());
381 assert!(inherited.is_some());
382 assert!(
383 FlockGuard::try_exclusive(lock_file(dir.path()))
384 .expect("try")
385 .is_some(),
386 "unwinding must release the lock although a copy is still open"
387 );
388 }
389
390 #[test]
391 fn shared_guards_coexist() {
392 let dir = tempfile::tempdir().expect("tempdir");
393 let first = FlockGuard::shared(lock_file(dir.path())).expect("shared");
394 let second = FlockGuard::try_shared(lock_file(dir.path()))
395 .expect("try shared")
396 .expect("shared lockers coexist");
397 drop((first, second));
398 }
399
400 #[test]
401 fn recognizes_fs2_contention_sentinel() {
402 assert!(is_contended(&fs2::lock_contended_error()));
403 }
404
405 #[test]
406 fn rejects_unrelated_errors() {
407 assert!(!is_contended(&Error::new(
408 ErrorKind::PermissionDenied,
409 "unrelated",
410 )));
411 }
412
413 #[test]
414 fn gives_up_instead_of_waiting_for_a_held_lock() {
415 use fs2::FileExt;
416
417 let dir = tempfile::tempdir().expect("tempdir");
418 let path = dir.path().join("contended.lock");
419 let holder = std::fs::File::create(&path).expect("create holder");
420 holder.lock_exclusive().expect("hold the lock");
421
422 let waiter = std::fs::OpenOptions::new()
423 .write(true)
424 .open(&path)
425 .expect("open waiter");
426 let started = Instant::now();
427 let result = acquire_exclusive_timeout(&waiter, Duration::from_millis(120));
428 let waited = started.elapsed();
429
430 assert!(
431 result.is_err(),
432 "must not acquire a lock someone else holds"
433 );
434 assert!(
435 waited < Duration::from_secs(5),
436 "must return on its own deadline, waited {waited:?}"
437 );
438 FileExt::unlock(&holder).expect("release");
439 }
440
441 #[test]
442 fn takes_a_free_lock_immediately() {
443 use fs2::FileExt;
444
445 let dir = tempfile::tempdir().expect("tempdir");
446 let file = std::fs::File::create(dir.path().join("free.lock")).expect("create");
447
448 acquire_exclusive_timeout(&file, Duration::from_millis(100)).expect("uncontended");
449 FileExt::unlock(&file).expect("release");
450 }
451}