lean-ctx-fs 0.2.2

Filesystem and environment foundation for LeanCTX | OSS: atomic writes, file locks, hashing, JSONC, home resolution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// SPDX-License-Identifier: Apache-2.0
use std::collections::{BTreeSet, HashMap};
use std::fs::File;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::{Duration, Instant};

const RETRY_INTERVAL: Duration = Duration::from_millis(10);

pub fn is_contended(error: &Error) -> bool {
    error.kind() == ErrorKind::WouldBlock
        || error
            .raw_os_error()
            .zip(fs2::lock_contended_error().raw_os_error())
            .is_some_and(|(error_code, contended_code)| error_code == contended_code)
}

/// Takes an exclusive advisory lock, giving up after `timeout` rather than
/// waiting for as long as the other holder cares to keep it.
///
/// `fs2::FileExt::lock_exclusive` has no deadline at all. On a thread whose only
/// job is that one write, an unbounded wait is merely slow. Anywhere else it is
/// a wedge: the waiter keeps everything it already owns — a `tokio` guard, an
/// executor worker — for the entire wait, and nothing in the process can end it
/// (#1783). A caller that cannot afford to wait forever could not express that
/// before this; now the bound is the default and the failure is an ordinary
/// `Err` the caller can retry on its own schedule.
pub fn acquire_exclusive_timeout(file: &File, timeout: Duration) -> Result<(), String> {
    use fs2::FileExt;

    let deadline = Instant::now() + timeout;
    loop {
        match file.try_lock_exclusive() {
            Ok(()) => return Ok(()),
            Err(error) if is_contended(&error) => {
                if Instant::now() >= deadline {
                    return Err(format!(
                        "still held after {}ms — giving up rather than blocking",
                        timeout.as_millis()
                    ));
                }
                std::thread::sleep(RETRY_INTERVAL);
            }
            Err(error) => return Err(error.to_string()),
        }
    }
}

/// An advisory lock on `file`, released explicitly when the guard drops.
///
/// An `fs2` lock is a `flock(2)` lock: it belongs to the open file description,
/// not to the descriptor, and it ends only when the last descriptor of that
/// description closes. A child process any other thread spawns holds a copy of
/// every descriptor from `fork` until its program starts (close-on-exec does
/// not shorten that), so releasing a lock by dropping the file leaves it held
/// for that moment. A concurrent `try_lock_exclusive` then sees `EWOULDBLOCK`,
/// and a caller that skips its work on a busy lock skips it although nobody is
/// working. `Drop` therefore calls `unlock` first, which ends the lock for every
/// copy at once, and closes the file after. Unwinding drops the guard too.
#[derive(Debug)]
pub struct FlockGuard {
    file: File,
}

impl FlockGuard {
    /// Takes the exclusive lock if it is free. `Ok(None)`: someone holds it.
    pub fn try_exclusive(file: File) -> std::io::Result<Option<Self>> {
        match fs2::FileExt::try_lock_exclusive(&file) {
            Ok(()) => Ok(Some(Self { file })),
            Err(error) if is_contended(&error) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Takes the shared lock if no exclusive holder has it. `Ok(None)`: one has.
    pub fn try_shared(file: File) -> std::io::Result<Option<Self>> {
        match fs2::FileExt::try_lock_shared(&file) {
            Ok(()) => Ok(Some(Self { file })),
            Err(error) if is_contended(&error) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Waits for the exclusive lock without a deadline.
    pub fn exclusive(file: File) -> std::io::Result<Self> {
        fs2::FileExt::lock_exclusive(&file)?;
        Ok(Self { file })
    }

    /// Waits for the shared lock without a deadline.
    pub fn shared(file: File) -> std::io::Result<Self> {
        fs2::FileExt::lock_shared(&file)?;
        Ok(Self { file })
    }

    /// Waits for the exclusive lock at most `timeout`, as
    /// [`acquire_exclusive_timeout`] does.
    pub fn exclusive_timeout(file: File, timeout: Duration) -> Result<Self, String> {
        acquire_exclusive_timeout(&file, timeout)?;
        Ok(Self { file })
    }

    /// Takes over the release of a lock the caller already took on `file`
    /// (for a retry loop that polls `try_lock_*` with its own schedule).
    pub fn from_locked(file: File) -> Self {
        Self { file }
    }

    /// The locked file.
    pub fn file(&self) -> &File {
        &self.file
    }
}

impl std::ops::Deref for FlockGuard {
    type Target = File;

    fn deref(&self) -> &File {
        &self.file
    }
}

impl Drop for FlockGuard {
    fn drop(&mut self) {
        let _ = fs2::FileExt::unlock(&self.file);
    }
}

/// One thread's turn at a lock path within this process; the next waiter in
/// line gets it when this drops.
///
/// An advisory file lock polled with a deadline is no queue: threads of one
/// process that take the same lock back to back make a waiter's deadline count
/// every critical section ahead of it, so eight writers whose writes each take
/// a second (an `fsync` plus a Windows replace that waits out a scanner) fail
/// the last one after five seconds although every holder made progress. The
/// turn queues the threads of a process in arrival order, and a waiter's
/// `timeout` counts only time in which no turn was handed over: a holder that
/// never returns still fails every waiter after `timeout`, a queue that moves
/// fails nobody. Other processes are still bounded by the file lock itself.
pub struct Turn {
    path: PathBuf,
    queue: Arc<Queue>,
}

#[derive(Default)]
struct Queue {
    line: Mutex<Line>,
    moved: Condvar,
}

#[derive(Default)]
struct Line {
    /// The next ticket handed out, and the ticket whose turn it is.
    next: u64,
    serving: u64,
    /// Tickets whose waiters gave up before their turn came.
    abandoned: BTreeSet<u64>,
}

impl Line {
    fn advance(&mut self) {
        self.serving += 1;
        while self.abandoned.remove(&self.serving) {
            self.serving += 1;
        }
    }

    fn idle(&self) -> bool {
        self.serving == self.next
    }
}

fn queues() -> &'static Mutex<HashMap<PathBuf, Arc<Queue>>> {
    static QUEUES: OnceLock<Mutex<HashMap<PathBuf, Arc<Queue>>>> = OnceLock::new();
    QUEUES.get_or_init(Mutex::default)
}

fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Wait for this thread's turn at `path` among the threads of this process.
/// `None` once `timeout` passed without any turn being handed over.
///
/// The queue is keyed on `path` exactly as spelled, not canonicalized: two
/// spellings of one lock file (relative and absolute, through a symlink) get
/// two queues, and their callers fall back to contending on the file lock
/// alone, as before the turn existed. Callers pass one derived path per lock.
#[must_use]
pub fn take_turn(path: &Path, timeout: Duration) -> Option<Turn> {
    // Lock order everywhere: the map, then a queue's line. The ticket is drawn
    // under the map lock so a releasing holder never drops a queue in use.
    let (queue, ticket) = {
        let mut map = locked(queues());
        let queue = Arc::clone(map.entry(path.to_path_buf()).or_default());
        let mut line = locked(&queue.line);
        let ticket = line.next;
        line.next += 1;
        drop(line);
        drop(map);
        (queue, ticket)
    };
    let mut line = locked(&queue.line);
    let mut seen = line.serving;
    let mut deadline = Instant::now() + timeout;
    while line.serving != ticket {
        let now = Instant::now();
        if line.serving != seen {
            seen = line.serving;
            deadline = now + timeout;
        }
        let left = deadline.saturating_duration_since(now);
        if left.is_zero() {
            line.abandoned.insert(ticket);
            return None;
        }
        line = queue
            .moved
            .wait_timeout(line, left)
            .unwrap_or_else(PoisonError::into_inner)
            .0;
    }
    drop(line);
    Some(Turn {
        path: path.to_path_buf(),
        queue,
    })
}

impl Drop for Turn {
    fn drop(&mut self) {
        let mut map = locked(queues());
        let mut line = locked(&self.queue.line);
        line.advance();
        if line.idle() {
            map.remove(&self.path);
        }
        drop(line);
        drop(map);
        self.queue.moved.notify_all();
    }
}

#[cfg(test)]
mod tests {
    use super::{FlockGuard, acquire_exclusive_timeout, is_contended, locked, queues, take_turn};
    use std::io::{Error, ErrorKind};
    use std::path::Path;
    use std::time::{Duration, Instant};

    /// The next ticket `take_turn` would hand out at `path`, 0 without a queue.
    fn tickets_drawn(path: &Path) -> u64 {
        locked(queues())
            .get(path)
            .map_or(0, |queue| locked(&queue.line).next)
    }

    fn wait_for_tickets(path: &Path, drawn: u64) {
        let deadline = Instant::now() + Duration::from_secs(10);
        while tickets_drawn(path) < drawn {
            assert!(Instant::now() < deadline, "ticket {drawn} never drawn");
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    /// A waiter that gives up in the middle of the line leaves an abandoned
    /// ticket. The holder's release must skip it and hand the turn to the
    /// waiter behind it at once; without the skip that waiter would wait out
    /// its own timeout. The idle queue is then removed from the map.
    #[test]
    fn an_abandoned_ticket_is_skipped_and_the_idle_queue_removed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("abandoned.lock");

        let holder = take_turn(&path, Duration::from_secs(1)).expect("free turn");
        let quitter = {
            let path = path.clone();
            std::thread::spawn(move || take_turn(&path, Duration::from_millis(100)).is_none())
        };
        wait_for_tickets(&path, 2);
        let patient = {
            let path = path.clone();
            std::thread::spawn(move || {
                let turn = take_turn(&path, Duration::from_secs(30));
                (turn.is_some(), Instant::now())
            })
        };
        wait_for_tickets(&path, 3);

        assert!(
            quitter.join().expect("quitter"),
            "the middle waiter must give up while the holder keeps its turn"
        );
        let released = Instant::now();
        drop(holder);
        let (got_turn, served) = patient.join().expect("patient");

        assert!(
            got_turn,
            "the waiter behind an abandoned ticket gets its turn"
        );
        let handover = served.saturating_duration_since(released);
        assert!(
            handover < Duration::from_secs(5),
            "the abandoned ticket must be skipped, handover took {handover:?}"
        );
        assert!(
            !locked(queues()).contains_key(&path),
            "an idle queue must leave the map"
        );
    }

    fn lock_file(dir: &Path) -> std::fs::File {
        std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(dir.join("guard.lock"))
            .expect("open lock file")
    }

    #[test]
    fn try_exclusive_reports_a_held_lock_as_none() {
        let dir = tempfile::tempdir().expect("tempdir");
        let held = FlockGuard::try_exclusive(lock_file(dir.path()))
            .expect("lock")
            .expect("free lock");
        assert!(
            FlockGuard::try_exclusive(lock_file(dir.path()))
                .expect("try")
                .is_none(),
            "a held lock must read as busy"
        );
        assert!(
            FlockGuard::try_shared(lock_file(dir.path()))
                .expect("try shared")
                .is_none(),
            "an exclusive holder excludes shared lockers"
        );
        drop(held);
        assert!(
            FlockGuard::try_exclusive(lock_file(dir.path()))
                .expect("try")
                .is_some(),
            "a dropped guard frees the lock"
        );
    }

    /// A duplicate of the locked descriptor (what a child process spawned by
    /// another thread holds until it execs) must not keep the lock alive once
    /// the guard drops.
    #[test]
    fn a_duplicated_handle_does_not_outlive_the_guard() {
        let dir = tempfile::tempdir().expect("tempdir");
        let guard = FlockGuard::exclusive(lock_file(dir.path())).expect("lock");
        let inherited = guard.file().try_clone().expect("duplicate handle");
        drop(guard);
        assert!(
            FlockGuard::try_exclusive(lock_file(dir.path()))
                .expect("try")
                .is_some(),
            "the lock must end with the guard, not with the last copy"
        );
        drop(inherited);
    }

    #[test]
    fn a_duplicated_handle_does_not_outlive_a_guard_dropped_by_unwinding() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut inherited = None;
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let guard =
                FlockGuard::exclusive_timeout(lock_file(dir.path()), Duration::from_secs(1))
                    .expect("lock");
            inherited = Some(guard.try_clone().expect("duplicate handle"));
            panic!("the critical section fails");
        }));
        assert!(unwound.is_err());
        assert!(inherited.is_some());
        assert!(
            FlockGuard::try_exclusive(lock_file(dir.path()))
                .expect("try")
                .is_some(),
            "unwinding must release the lock although a copy is still open"
        );
    }

    #[test]
    fn shared_guards_coexist() {
        let dir = tempfile::tempdir().expect("tempdir");
        let first = FlockGuard::shared(lock_file(dir.path())).expect("shared");
        let second = FlockGuard::try_shared(lock_file(dir.path()))
            .expect("try shared")
            .expect("shared lockers coexist");
        drop((first, second));
    }

    #[test]
    fn recognizes_fs2_contention_sentinel() {
        assert!(is_contended(&fs2::lock_contended_error()));
    }

    #[test]
    fn rejects_unrelated_errors() {
        assert!(!is_contended(&Error::new(
            ErrorKind::PermissionDenied,
            "unrelated",
        )));
    }

    #[test]
    fn gives_up_instead_of_waiting_for_a_held_lock() {
        use fs2::FileExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("contended.lock");
        let holder = std::fs::File::create(&path).expect("create holder");
        holder.lock_exclusive().expect("hold the lock");

        let waiter = std::fs::OpenOptions::new()
            .write(true)
            .open(&path)
            .expect("open waiter");
        let started = Instant::now();
        let result = acquire_exclusive_timeout(&waiter, Duration::from_millis(120));
        let waited = started.elapsed();

        assert!(
            result.is_err(),
            "must not acquire a lock someone else holds"
        );
        assert!(
            waited < Duration::from_secs(5),
            "must return on its own deadline, waited {waited:?}"
        );
        FileExt::unlock(&holder).expect("release");
    }

    #[test]
    fn takes_a_free_lock_immediately() {
        use fs2::FileExt;

        let dir = tempfile::tempdir().expect("tempdir");
        let file = std::fs::File::create(dir.path().join("free.lock")).expect("create");

        acquire_exclusive_timeout(&file, Duration::from_millis(100)).expect("uncontended");
        FileExt::unlock(&file).expect("release");
    }
}