Skip to main content

lean_ctx_fs/
file_lock.rs

1// SPDX-License-Identifier: Apache-2.0
2use 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
19/// Takes an exclusive advisory lock, giving up after `timeout` rather than
20/// waiting for as long as the other holder cares to keep it.
21///
22/// `fs2::FileExt::lock_exclusive` has no deadline at all. On a thread whose only
23/// job is that one write, an unbounded wait is merely slow. Anywhere else it is
24/// a wedge: the waiter keeps everything it already owns — a `tokio` guard, an
25/// executor worker — for the entire wait, and nothing in the process can end it
26/// (#1783). A caller that cannot afford to wait forever could not express that
27/// before this; now the bound is the default and the failure is an ordinary
28/// `Err` the caller can retry on its own schedule.
29pub 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/// An advisory lock on `file`, released explicitly when the guard drops.
51///
52/// An `fs2` lock is a `flock(2)` lock: it belongs to the open file description,
53/// not to the descriptor, and it ends only when the last descriptor of that
54/// description closes. A child process any other thread spawns holds a copy of
55/// every descriptor from `fork` until its program starts (close-on-exec does
56/// not shorten that), so releasing a lock by dropping the file leaves it held
57/// for that moment. A concurrent `try_lock_exclusive` then sees `EWOULDBLOCK`,
58/// and a caller that skips its work on a busy lock skips it although nobody is
59/// working. `Drop` therefore calls `unlock` first, which ends the lock for every
60/// copy at once, and closes the file after. Unwinding drops the guard too.
61#[derive(Debug)]
62pub struct FlockGuard {
63    file: File,
64}
65
66impl FlockGuard {
67    /// Takes the exclusive lock if it is free. `Ok(None)`: someone holds it.
68    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    /// Takes the shared lock if no exclusive holder has it. `Ok(None)`: one has.
77    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    /// Waits for the exclusive lock without a deadline.
86    pub fn exclusive(file: File) -> std::io::Result<Self> {
87        fs2::FileExt::lock_exclusive(&file)?;
88        Ok(Self { file })
89    }
90
91    /// Waits for the shared lock without a deadline.
92    pub fn shared(file: File) -> std::io::Result<Self> {
93        fs2::FileExt::lock_shared(&file)?;
94        Ok(Self { file })
95    }
96
97    /// Waits for the exclusive lock at most `timeout`, as
98    /// [`acquire_exclusive_timeout`] does.
99    pub fn exclusive_timeout(file: File, timeout: Duration) -> Result<Self, String> {
100        acquire_exclusive_timeout(&file, timeout)?;
101        Ok(Self { file })
102    }
103
104    /// Takes over the release of a lock the caller already took on `file`
105    /// (for a retry loop that polls `try_lock_*` with its own schedule).
106    pub fn from_locked(file: File) -> Self {
107        Self { file }
108    }
109
110    /// The locked file.
111    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
130/// One thread's turn at a lock path within this process; the next waiter in
131/// line gets it when this drops.
132///
133/// An advisory file lock polled with a deadline is no queue: threads of one
134/// process that take the same lock back to back make a waiter's deadline count
135/// every critical section ahead of it, so eight writers whose writes each take
136/// a second (an `fsync` plus a Windows replace that waits out a scanner) fail
137/// the last one after five seconds although every holder made progress. The
138/// turn queues the threads of a process in arrival order, and a waiter's
139/// `timeout` counts only time in which no turn was handed over: a holder that
140/// never returns still fails every waiter after `timeout`, a queue that moves
141/// fails nobody. Other processes are still bounded by the file lock itself.
142pub 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    /// The next ticket handed out, and the ticket whose turn it is.
156    next: u64,
157    serving: u64,
158    /// Tickets whose waiters gave up before their turn came.
159    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/// Wait for this thread's turn at `path` among the threads of this process.
185/// `None` once `timeout` passed without any turn being handed over.
186///
187/// The queue is keyed on `path` exactly as spelled, not canonicalized: two
188/// spellings of one lock file (relative and absolute, through a symlink) get
189/// two queues, and their callers fall back to contending on the file lock
190/// alone, as before the turn existed. Callers pass one derived path per lock.
191#[must_use]
192pub fn take_turn(path: &Path, timeout: Duration) -> Option<Turn> {
193    // Lock order everywhere: the map, then a queue's line. The ticket is drawn
194    // under the map lock so a releasing holder never drops a queue in use.
195    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    /// The next ticket `take_turn` would hand out at `path`, 0 without a queue.
254    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    /// A waiter that gives up in the middle of the line leaves an abandoned
269    /// ticket. The holder's release must skip it and hand the turn to the
270    /// waiter behind it at once; without the skip that waiter would wait out
271    /// its own timeout. The idle queue is then removed from the map.
272    #[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    /// A duplicate of the locked descriptor (what a child process spawned by
352    /// another thread holds until it execs) must not keep the lock alive once
353    /// the guard drops.
354    #[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}