ostrya 0.12.0

Pure-Rust async reimplementation of the ostree repository library
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! The repository lock and the process-global registry of lock files.
//!
//! [`LockKind`] holds the rules that a caller sees: the lock file, the
//! in-process rules, and the wait. The open of a lock file and the record lock
//! calls go through the lock primitives of `repo_fs`. The retry loop waits on
//! [`ostrya_rt::Timer`].
//!
//! A process-global registry maps the `(device, inode)` of each lock file to
//! its lock. Each handle to one repository gets the same [`RepoLock`]: clones
//! and separate opens. Hold counts let many shared holders share one record
//! lock. The calls change the record lock only when the effective lock
//! changes.
//!
//! A dropped lock closes its descriptor and removes its registry entry under
//! the registry mutex. No call opens a new descriptor to an inode while the
//! registry holds an entry for it. As a result, the descriptor of a dropped
//! lock never closes after the process takes a new lock on the same inode.
//!
//! The update lock on `<repo>/.update.lock` serializes the writes of refs and
//! of the other repository state outside the object store (see [`update`]).
//! The same registry holds both locks, so the process never opens one inode
//! through two live descriptors.

use std::collections::HashMap;
use std::os::fd::{AsFd, OwnedFd};
use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak};
use std::time::{Duration, Instant};

use crate::error::{Error, Result};
use crate::repo_fs::{self, FsError, RepoDir, RootFile};

mod update;
#[cfg(test)]
pub(crate) use update::held_in_process as update_lock_held_in_process;
pub(crate) use update::{UpdateLock, UpdateLockHeld, acquire_update};

/// The delay between two lock attempts while another holder has the lock.
const POLL_INTERVAL: Duration = Duration::from_millis(100);

/// The kind of hold on the repository lock: shared or exclusive.
///
/// A writing transaction takes the lock [`Shared`](LockKind::Shared), so many
/// commits run at the same time. The `ostree` command also holds a read lock
/// during a commit. [`Repo::prune`](crate::Repo::prune) takes the lock
/// [`Exclusive`](LockKind::Exclusive).
///
/// If `[core] locking` is `false`, ostrya does not take the repository lock
/// ([`RepoConfig::locking`](crate::config::RepoConfig::locking)). The default
/// is `true`.
///
/// # Lock file
///
/// The repository lock is an `fcntl` record lock (`F_SETLK`) on
/// `<repo>/.lock`. The `ostree` command takes OFD locks on the same file.
/// Record locks and OFD locks share one lock space, so ostrya and the `ostree`
/// command exclude each other on one repository.
///
/// If the file does not exist, the first lock creates it with mode `0660`.
/// The `ostree` command uses the same mode. The process umask reduces this
/// mode.
///
/// In a `bare-user-shared` repository, ostrya sets the mode of a file that it
/// creates to `0660` after the create. Each member of the repository group can
/// then open the file for reading and writing. A file that another member
/// created keeps its mode.
///
/// The open of the file follows no symlink. A symlink, a FIFO, a socket, a
/// device, or a directory at `.lock` fails the lock, and the entry stays. The
/// error is [`Error::InvalidFormat`], or [`Error::Io`] if the process cannot
/// open a FIFO, a socket, or a device for write. The open of an existing file
/// needs write access to it, also for a shared lock. If the file goes away
/// between the create and the open, ostrya creates it again one time. The
/// rules of a new file then apply to it, so a `bare-user-shared` repository
/// gets the forced mode.
///
/// If `.lock` and `.update.lock` are hard links to one inode, the repository
/// lock and the update lock refuse each other. While the process has one of
/// the two files open as its lock file, a lock on the other fails with
/// [`Error::Io`].
///
/// # In-process rules
///
/// An `F_SETLK` lock belongs to the process. Two descriptors in one process
/// do not conflict. Also, the close of any descriptor to the file releases
/// each lock of the process on it.
///
/// To prevent both faults, ostrya keeps one `.lock` descriptor for each
/// repository in each process. All handles to one repository share it, clones
/// and separate opens alike.
///
/// Hold counts in the process apply these rules:
///
/// - Many shared holders can hold the lock at the same time. They share one
///   record lock.
/// - An exclusive acquire waits while a shared holder exists.
/// - A shared acquire waits while an exclusive holder exists.
/// - An exclusive hold is not re-entrant. A second exclusive acquire waits for
///   the release of the first, also when the same caller makes it.
/// - When the last holder releases the lock, ostrya releases the record lock.
///
/// # A holder that waits for its own lock
///
/// No call detects a caller that waits for its own hold. This wait occurs if
/// a caller that holds the lock makes an acquire that its hold excludes:
///
/// - A second exclusive acquire while it holds the lock exclusive.
/// - A shared acquire while it holds the lock exclusive. A
///   [`Transaction`](crate::Transaction) and
///   [`Repo::set_ref_immediate`](crate::Repo::set_ref_immediate) make a
///   shared acquire.
/// - An exclusive acquire, for example [`Repo::prune`](crate::Repo::prune),
///   while it holds the lock shared, for example through a transaction or an
///   [`UpdateGuard`](crate::UpdateGuard).
///
/// The wait lasts until `[core] lock-timeout-secs` passes. The acquire then
/// fails with [`Error::LockTimeout`]. If the value is `-1`, the caller waits
/// forever. If `[core] locking` is `false`, no such wait occurs.
///
/// # Waiting
///
/// An acquire makes one non-blocking lock request. If another process holds a
/// conflicting lock, or an in-process rule makes the acquire wait, the acquire
/// tries again every 100 ms. The `ostree` command also tries again until its
/// timeout.
///
/// `[core] lock-timeout-secs` sets the limit of the wait, in seconds
/// ([`RepoConfig::lock_timeout_secs`](crate::config::RepoConfig::lock_timeout_secs)).
/// The default is `300`. If the wait passes the limit, the acquire fails with
/// [`Error::LockTimeout`]. The value `0` makes one attempt. The value `-1`
/// means no limit, as in the `ostree` command.
///
/// No lock request blocks in the kernel. If a caller drops a future that
/// waits for the lock, no lock request stays behind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockKind {
    /// A shared (read) lock.
    Shared,
    /// An exclusive (write) lock.
    Exclusive,
}

/// The effective lock currently applied to the `.lock` descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OsLock {
    Unlocked,
    Shared,
    Exclusive,
}

/// In-process hold counts and the effective descriptor lock.
#[derive(Debug)]
struct LockState {
    shared: usize,
    exclusive: usize,
    os: OsLock,
}

/// The outcome of one non-blocking acquisition attempt.
enum TryOutcome {
    Acquired,
    WouldBlock,
}

/// The per-repository lock, shared by every handle to one repository in a
/// process.
#[derive(Debug)]
pub(crate) struct RepoLock {
    key: (u64, u64),
    /// The `.lock` descriptor. It is `Some` until the drop closes it under the
    /// registry mutex.
    fd: Option<OwnedFd>,
    state: Mutex<LockState>,
}

/// A lock the registry holds for one lock file.
#[derive(Debug)]
enum Registered {
    Repo(Weak<RepoLock>),
    Update(Weak<UpdateLock>),
}

impl Registered {
    /// Returns the repository lock of this entry, or `None` for another kind
    /// of lock.
    fn repo(&self) -> Option<&Weak<RepoLock>> {
        match self {
            Registered::Repo(weak) => Some(weak),
            Registered::Update(_) => None,
        }
    }

    /// Returns the update lock of this entry, or `None` for another kind of
    /// lock.
    fn update(&self) -> Option<&Weak<UpdateLock>> {
        match self {
            Registered::Update(weak) => Some(weak),
            Registered::Repo(_) => None,
        }
    }
}

/// The registry entry of one lock file.
#[derive(Debug)]
struct Entry {
    lock: Registered,
    /// The descriptors to the same inode that an open made after the registry
    /// added the entry. The close of one of them drops the record locks of
    /// `lock`, so each one stays open until the registry removes the entry.
    parked: Vec<OwnedFd>,
}

/// The process-global map from the `(device, inode)` of a lock file to its
/// lock.
type LockRegistry = HashMap<(u64, u64), Entry>;

/// The registry, with the condition variable that a dropped lock signals
/// after it removes its entry.
struct Registry {
    map: Mutex<LockRegistry>,
    gone: Condvar,
}

fn registry() -> &'static Registry {
    static REGISTRY: OnceLock<Registry> = OnceLock::new();
    REGISTRY.get_or_init(|| Registry {
        map: Mutex::new(HashMap::new()),
        gone: Condvar::new(),
    })
}

/// Returns the registry entry for the file `name` in the repository root
/// `root`.
///
/// The call does not open the file. The open and the close of a second
/// descriptor to a lock file drop the live lock. The call reads the status of
/// the entry with [`RepoDir::lstat`], which follows no symlink. A symlink at
/// `name` thus gives the inode of the symlink, which the registry never holds.
/// The call ignores each error of the read, and then gives `None`.
fn probe<'r>(reg: &'r LockRegistry, root: &RepoDir, name: &str) -> Option<&'r Entry> {
    let stat = root.lstat(name).ok()?;
    reg.get(&(stat.dev, stat.ino))
}

/// What a registry entry holds for a lock of type `T`.
enum Found<T> {
    /// A live lock of type `T`.
    Live(Arc<T>),
    /// A lock of type `T` whose last reference is gone and whose drop has not
    /// yet closed its descriptor.
    Dying,
    /// A lock of another type.
    Other,
}

fn find<T>(entry: &Entry, view: fn(&Registered) -> Option<&Weak<T>>) -> Found<T> {
    match view(&entry.lock) {
        Some(weak) => weak.upgrade().map_or(Found::Dying, Found::Live),
        None => Found::Other,
    }
}

/// Returns the live lock of type `T` for the root file `file` of the
/// repository root `root`.
///
/// If no live lock exists, the call opens the file with
/// [`RepoDir::open_lock`]. That call creates an absent file with the mode of
/// `file`, and forces the shared mode on a new file in a `bare-user-shared`
/// repository. It follows no symlink, and refuses an entry that is not a
/// regular file. A file that another member of the repository group created
/// keeps its mode. The call then reads the `(device, inode)` of the open file,
/// and registers the lock that `make` builds from the descriptor and the
/// `(device, inode)`.
///
/// Two rules keep one open descriptor for each lock inode in the process:
///
/// - The call opens a new descriptor only while the registry holds no entry
///   for the inode. A dying entry still owns an open descriptor. The call
///   waits until the drop of that lock closes it and removes the entry.
/// - A link or a rename can occur between the probe and the open. The open
///   then returns a descriptor for an inode that the registry already holds.
///   The call never closes this descriptor. It parks the descriptor in the
///   entry, and the descriptor closes when the entry goes.
///
/// The registry mutex stays held across the open, so no other call registers
/// the inode between the probe and the insert. The first opens in the process
/// therefore run one at a time.
fn get_or_register<T>(
    root: &RepoDir,
    file: RootFile,
    view: fn(&Registered) -> Option<&Weak<T>>,
    make: impl FnOnce(OwnedFd, (u64, u64)) -> (Arc<T>, Registered),
) -> Result<Arc<T>> {
    let name = file.name();
    let registry = registry();
    let mut reg = registry.map.lock().unwrap();
    loop {
        match probe(&reg, root, name).map(|entry| find(entry, view)) {
            Some(Found::Live(existing)) => return Ok(existing),
            Some(Found::Other) => return Err(Error::Io(shared_inode(name))),
            Some(Found::Dying) => {
                reg = registry.gone.wait(reg).unwrap();
                continue;
            }
            None => {}
        }

        let fd = root.open_lock(name)?;
        let stat = repo_fs::stat_fd(fd.as_fd())?;
        let key = (stat.dev, stat.ino);
        let Some(entry) = reg.get_mut(&key) else {
            let (lock, registered) = make(fd, key);
            reg.insert(
                key,
                Entry {
                    lock: registered,
                    parked: Vec::new(),
                },
            );
            return Ok(lock);
        };
        // The probe finds a link that stood before the open. This arm catches
        // one made between the probe and the open.
        let found = find(entry, view);
        entry.parked.push(fd);
        match found {
            Found::Live(existing) => return Ok(existing),
            Found::Other => return Err(Error::Io(shared_inode(name))),
            Found::Dying => reg = registry.gone.wait(reg).unwrap(),
        }
    }
}

/// Closes the descriptor `fd` of a dropped lock and removes its entry at
/// `key`, with the parked descriptors, under the registry mutex.
///
/// The call then wakes the calls that wait for the entry to go. No call
/// replaces an entry, so the entry at `key` belongs to the dropped lock.
fn unregister(key: (u64, u64), fd: Option<OwnedFd>) {
    let registry = registry();
    // A poisoned mutex still guards a whole map. If a drop skips the removal,
    // the waiters for this inode wait with no end.
    let mut reg = registry.map.lock().unwrap_or_else(PoisonError::into_inner);
    drop(fd);
    drop(reg.remove(&key));
    drop(reg);
    registry.gone.notify_all();
}

/// Returns the error for a lock file whose inode the registry holds for
/// another kind of lock.
///
/// A hard link between the two lock files causes this state. The close of a
/// second descriptor to that inode drops the other lock. Also, the two locks
/// do not exclude each other inside the process.
fn shared_inode(name: &str) -> std::io::Error {
    std::io::Error::other(format!(
        "lock file {name} shares its inode with another lock file of the repository"
    ))
}

impl RepoLock {
    /// Returns the [`RepoLock`] for the repository of the root handle `root`.
    ///
    /// The first use creates `<repo>/.lock` if it is absent, and registers the
    /// lock. The call opens the file through [`get_or_register`], which states
    /// the rules of the open. A symlink or an entry that is not a regular file
    /// at `.lock` gives [`Error::InvalidFormat`], or [`Error::Io`] if the
    /// process cannot open the entry for write. The call runs synchronous
    /// file system calls, so the caller runs it on the blocking pool.
    pub(crate) fn get_or_create(root: &RepoDir) -> Result<Arc<RepoLock>> {
        get_or_register(root, RootFile::Lock, Registered::repo, |fd, key| {
            let lock = Arc::new(RepoLock {
                key,
                fd: Some(fd),
                state: Mutex::new(LockState {
                    shared: 0,
                    exclusive: 0,
                    os: OsLock::Unlocked,
                }),
            });
            let registered = Registered::Repo(Arc::downgrade(&lock));
            (lock, registered)
        })
    }

    fn fd(&self) -> &OwnedFd {
        self.fd
            .as_ref()
            .expect("the descriptor stays open until the drop")
    }

    /// Adds one holder of `kind` without blocking.
    ///
    /// A record lock belongs to the process, so the descriptor alone cannot
    /// keep one in-process holder from another. The hold counts do that. If a
    /// rule excludes the acquire, the call reports [`TryOutcome::WouldBlock`]
    /// and raises no count. The caller then goes into the retry loop.
    fn try_acquire(&self, kind: LockKind) -> std::result::Result<TryOutcome, FsError> {
        let mut st = self.state.lock().unwrap();
        match kind {
            LockKind::Shared => {
                // An exclusive holder excludes every other holder in this
                // process.
                if st.exclusive > 0 {
                    return Ok(TryOutcome::WouldBlock);
                }
                if st.os == OsLock::Shared {
                    st.shared += 1;
                    return Ok(TryOutcome::Acquired);
                }
                if !repo_fs::try_lock(self.fd().as_fd(), LockKind::Shared)? {
                    return Ok(TryOutcome::WouldBlock);
                }
                st.os = OsLock::Shared;
                st.shared += 1;
                Ok(TryOutcome::Acquired)
            }
            LockKind::Exclusive => {
                // An exclusive acquire waits for every other holder, an
                // exclusive one included: the hold is not re-entrant, so two
                // callers never share it.
                if st.shared > 0 || st.exclusive > 0 {
                    return Ok(TryOutcome::WouldBlock);
                }
                if !repo_fs::try_lock(self.fd().as_fd(), LockKind::Exclusive)? {
                    return Ok(TryOutcome::WouldBlock);
                }
                st.os = OsLock::Exclusive;
                st.exclusive += 1;
                Ok(TryOutcome::Acquired)
            }
        }
    }

    /// Drops one holder of `kind`. When the last holder goes, the call releases
    /// the record lock.
    fn release(&self, kind: LockKind) {
        let mut st = self.state.lock().unwrap();
        match kind {
            LockKind::Shared => st.shared = st.shared.saturating_sub(1),
            LockKind::Exclusive => st.exclusive = st.exclusive.saturating_sub(1),
        }
        let target = if st.exclusive > 0 {
            OsLock::Exclusive
        } else if st.shared > 0 {
            OsLock::Shared
        } else {
            OsLock::Unlocked
        };
        if target == st.os {
            return;
        }
        // A shared holder and an exclusive holder exclude each other, so one of
        // the two counts is zero, and the target here is `Unlocked`. The call
        // ignores errors, so a release never fails, also in a drop.
        let _ = repo_fs::unlock(self.fd().as_fd());
        st.os = target;
    }
}

impl Drop for RepoLock {
    fn drop(&mut self) {
        // Closing the descriptor releases any residual record lock.
        unregister(self.key, self.fd.take());
    }
}

/// A hold on the repository lock. The drop of the guard releases the hold.
#[derive(Debug)]
pub(crate) struct LockGuard {
    hold: Option<(Arc<RepoLock>, LockKind)>,
}

impl LockGuard {
    /// Creates a guard that holds no lock, for a repository with `[core]
    /// locking` set to `false`.
    pub(crate) fn disabled() -> LockGuard {
        LockGuard { hold: None }
    }
}

impl Drop for LockGuard {
    fn drop(&mut self) {
        if let Some((lock, kind)) = &self.hold {
            lock.release(*kind);
        }
    }
}

/// The two locks that a writer of the update-lock state holds: the update
/// lock, and the repository lock held shared. The fields drop in declaration
/// order, so the drop releases the update lock first.
#[derive(Debug)]
pub(crate) struct UpdateLocks {
    // The code never reads the two fields. Each field exists for its drop.
    #[allow(dead_code)]
    pub(crate) update: UpdateLockHeld,
    #[allow(dead_code)]
    pub(crate) repo: LockGuard,
}

/// Acquires `kind` on `lock` and tries again until `timeout` passes. `None`
/// tries again with no limit.
///
/// Each attempt runs on the calling task. It takes the state mutex and makes
/// one non-blocking lock request, so it returns at once. If an attempt ran on
/// the blocking pool, it can complete after the caller drops this future. It
/// then leaves a hold that no guard releases.
pub(crate) async fn acquire(
    lock: Arc<RepoLock>,
    kind: LockKind,
    timeout: Option<Duration>,
) -> Result<LockGuard> {
    // A timeout past the range of `Instant` has no deadline.
    let deadline = timeout.and_then(|t| Some((Instant::now().checked_add(t)?, t.as_secs() as i64)));
    loop {
        match lock.try_acquire(kind)? {
            TryOutcome::Acquired => {
                return Ok(LockGuard {
                    hold: Some((lock, kind)),
                });
            }
            TryOutcome::WouldBlock => {
                let wait = match deadline {
                    Some((deadline, secs)) => {
                        let now = Instant::now();
                        if now >= deadline {
                            return Err(Error::LockTimeout { secs });
                        }
                        POLL_INTERVAL.min(deadline - now)
                    }
                    None => POLL_INTERVAL,
                };
                ostrya_rt::Timer::after(wait).await;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ostrya_core::RepoMode;
    use std::os::fd::AsRawFd;

    /// A repository root handle over a throwaway directory, for lock unit
    /// tests.
    struct Scratch {
        _dir: std::path::PathBuf,
        root: RepoDir,
    }

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            use std::sync::atomic::{AtomicU64, Ordering};
            static COUNTER: AtomicU64 = AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir =
                std::env::temp_dir().join(format!("ostrya-lock-{}-{tag}-{n}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            let root = RepoDir::open_root(rustix::fs::CWD, &dir)
                .unwrap()
                .with_repo_mode(RepoMode::Bare);
            Scratch { _dir: dir, root }
        }

        fn root(&self) -> &RepoDir {
            &self.root
        }

        fn path(&self) -> &std::path::Path {
            &self._dir
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self._dir);
        }
    }

    fn os_lock(lock: &RepoLock) -> OsLock {
        lock.state.lock().unwrap().os
    }

    /// The in-process hold counts, as `(shared, exclusive)`.
    fn counts(lock: &RepoLock) -> (usize, usize) {
        let st = lock.state.lock().unwrap();
        (st.shared, st.exclusive)
    }

    #[test]
    fn shared_holders_share_one_descriptor_lock() {
        let scratch = Scratch::new("shared");
        let lock = RepoLock::get_or_create(scratch.root()).unwrap();

        assert!(matches!(
            lock.try_acquire(LockKind::Shared).unwrap(),
            TryOutcome::Acquired
        ));
        assert!(matches!(
            lock.try_acquire(LockKind::Shared).unwrap(),
            TryOutcome::Acquired
        ));
        assert_eq!(os_lock(&lock), OsLock::Shared);

        lock.release(LockKind::Shared);
        assert_eq!(os_lock(&lock), OsLock::Shared); // one holder remains
        lock.release(LockKind::Shared);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
    }

    #[test]
    fn exclusive_waits_for_a_shared_holder() {
        let scratch = Scratch::new("wait");
        let lock = RepoLock::get_or_create(scratch.root()).unwrap();

        lock.try_acquire(LockKind::Shared).unwrap();
        assert_eq!(os_lock(&lock), OsLock::Shared);

        // The exclusive attempt reports `WouldBlock` while the shared holder
        // stands, and the effective lock stays shared.
        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::WouldBlock
        ));
        assert_eq!(os_lock(&lock), OsLock::Shared);
        assert_eq!(counts(&lock), (1, 0));

        // Once the shared holder releases, the attempt succeeds.
        lock.release(LockKind::Shared);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::Acquired
        ));
        assert_eq!(os_lock(&lock), OsLock::Exclusive);

        lock.release(LockKind::Exclusive);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
    }

    #[test]
    fn shared_waits_for_an_exclusive_holder() {
        let scratch = Scratch::new("shared-waits");
        let lock = RepoLock::get_or_create(scratch.root()).unwrap();

        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::Acquired
        ));
        assert_eq!(os_lock(&lock), OsLock::Exclusive);

        // The shared attempt reports `WouldBlock` while the exclusive holder
        // stands, the effective lock stays exclusive, and no count rises.
        assert!(matches!(
            lock.try_acquire(LockKind::Shared).unwrap(),
            TryOutcome::WouldBlock
        ));
        assert_eq!(os_lock(&lock), OsLock::Exclusive);
        assert_eq!(counts(&lock), (0, 1));

        // Once the exclusive holder releases, the attempt succeeds.
        lock.release(LockKind::Exclusive);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
        assert_eq!(counts(&lock), (0, 0));
        assert!(matches!(
            lock.try_acquire(LockKind::Shared).unwrap(),
            TryOutcome::Acquired
        ));
        assert_eq!(os_lock(&lock), OsLock::Shared);
        assert_eq!(counts(&lock), (1, 0));

        lock.release(LockKind::Shared);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
    }

    #[test]
    fn a_second_exclusive_waits_for_the_first() {
        let scratch = Scratch::new("exclusive-waits");
        let lock = RepoLock::get_or_create(scratch.root()).unwrap();

        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::Acquired
        ));

        // The hold is not re-entrant: a second exclusive attempt waits, and the
        // count stays at the one holder.
        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::WouldBlock
        ));
        assert_eq!(os_lock(&lock), OsLock::Exclusive);
        assert_eq!(counts(&lock), (0, 1));

        // Once the first holder releases, the second attempt succeeds.
        lock.release(LockKind::Exclusive);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
        assert_eq!(counts(&lock), (0, 0));
        assert!(matches!(
            lock.try_acquire(LockKind::Exclusive).unwrap(),
            TryOutcome::Acquired
        ));
        assert_eq!(os_lock(&lock), OsLock::Exclusive);
        assert_eq!(counts(&lock), (0, 1));

        lock.release(LockKind::Exclusive);
        assert_eq!(os_lock(&lock), OsLock::Unlocked);
    }

    #[test]
    fn one_repo_lock_is_shared_across_handles_and_reclaimed() {
        let scratch = Scratch::new("registry");
        let a = RepoLock::get_or_create(scratch.root()).unwrap();
        let b = RepoLock::get_or_create(scratch.root()).unwrap();
        assert!(Arc::ptr_eq(&a, &b), "same repo yields one shared lock");
        let key = a.key;

        drop(a);
        drop(b);
        assert!(
            !registry().map.lock().unwrap().contains_key(&key),
            "registry entry is reclaimed once the last handle drops"
        );
    }

    /// Returns `true` if the kernel records an exclusive record lock that
    /// this process set through the descriptor of `lock`.
    ///
    /// The fdinfo of a descriptor lists only the locks that this process set
    /// through that descriptor. The kernel builds it in one pass, so it is a
    /// consistent snapshot. A read of `/proc/locks` takes several calls. If
    /// other locks change between two of them, a line goes missing.
    fn holds_write_lock(lock: &RepoLock) -> bool {
        let path = format!("/proc/self/fdinfo/{}", lock.fd().as_raw_fd());
        let info = std::fs::read_to_string(path).unwrap();
        info.lines().any(|line| {
            let fields: Vec<&str> = line.split_whitespace().collect();
            fields.len() > 4 && fields[0] == "lock:" && fields[2] == "POSIX" && fields[4] == "WRITE"
        })
    }

    /// A lock dropped on another thread closes its descriptor before the
    /// process creates a new lock on the same inode. As a result, the close
    /// does not drop the record lock of the new lock.
    #[test]
    fn a_new_lock_survives_the_close_of_a_dropped_one() {
        for _ in 0..20 {
            let scratch = Scratch::new("redrop");
            let old = RepoLock::get_or_create(scratch.root()).unwrap();
            let weak = Arc::downgrade(&old);

            // The held registry mutex stops the drop of `old` before it
            // closes the descriptor. The test then asks for the new lock at
            // once.
            let reg = registry().map.lock().unwrap();
            let dropper = std::thread::spawn(move || drop(old));
            while weak.strong_count() > 0 {
                std::thread::yield_now();
            }
            drop(reg);
            let new = RepoLock::get_or_create(scratch.root()).unwrap();
            assert!(matches!(
                new.try_acquire(LockKind::Exclusive).unwrap(),
                TryOutcome::Acquired
            ));
            dropper.join().unwrap();

            assert!(holds_write_lock(&new), "the close dropped the new lock");
            new.release(LockKind::Exclusive);
        }
    }

    /// Returns the error of the open of the lock file `name` in `root`.
    /// `name` is `.lock` or `.update.lock`.
    fn lock_error(root: &RepoDir, name: &str) -> Error {
        if name == RootFile::Lock.name() {
            RepoLock::get_or_create(root).map(drop).unwrap_err()
        } else {
            UpdateLock::get_or_create(root).map(drop).unwrap_err()
        }
    }

    /// Runs [`lock_error`] in a new thread, and panics if it does not return
    /// in 10 seconds. Before the panic, an open of the FIFO `fifo` for write
    /// releases an open that waits for a writer.
    fn lock_error_without_block(root: &RepoDir, name: &str, fifo: &std::path::Path) -> Error {
        use std::sync::mpsc;

        let (tx, rx) = mpsc::channel();
        let (root, name) = (root.clone(), name.to_owned());
        let worker = std::thread::spawn(move || {
            let _ = tx.send(lock_error(&root, &name));
        });
        match rx.recv_timeout(Duration::from_secs(10)) {
            Ok(err) => {
                worker.join().unwrap();
                err
            }
            Err(_) => {
                let _ = rustix::fs::open(
                    fifo,
                    rustix::fs::OFlags::WRONLY
                        | rustix::fs::OFlags::NONBLOCK
                        | rustix::fs::OFlags::CLOEXEC,
                    rustix::fs::Mode::empty(),
                );
                panic!("the open of the FIFO {} blocked", fifo.display());
            }
        }
    }

    #[test]
    fn a_lock_file_that_is_a_symlink_or_not_a_regular_file_is_refused() {
        let outside = Scratch::new("refused-outside");
        let target = outside.path().join("target");
        std::fs::write(&target, b"outside bytes").unwrap();
        let dangling = outside.path().join("absent");
        let symlink_text = "passes through a symlink; ostrya refuses a symlink in the repository";
        let not_regular_text = "is not a regular file";

        for name in [RootFile::Lock.name(), RootFile::UpdateLock.name()] {
            let cases = [
                ("symlink", symlink_text),
                ("dangling", symlink_text),
                ("fifo", not_regular_text),
                ("socket", not_regular_text),
                ("directory", not_regular_text),
            ];
            for (label, text) in cases {
                let scratch = Scratch::new("refused");
                let at = scratch.path().join(name);
                match label {
                    "symlink" => std::os::unix::fs::symlink(&target, &at).unwrap(),
                    "dangling" => std::os::unix::fs::symlink(&dangling, &at).unwrap(),
                    "fifo" => rustix::fs::mknodat(
                        rustix::fs::CWD,
                        &at,
                        rustix::fs::FileType::Fifo,
                        rustix::fs::Mode::from_raw_mode(0o600),
                        0,
                    )
                    .unwrap(),
                    "socket" => drop(std::os::unix::net::UnixListener::bind(&at).unwrap()),
                    _ => std::fs::create_dir(&at).unwrap(),
                }
                let err = lock_error_without_block(scratch.root(), name, &at);
                let expected = format!("{name} {text}");
                assert!(
                    matches!(&err, Error::InvalidFormat(m) if *m == expected),
                    "{name} as a {label}: {err:?}"
                );
                assert!(
                    std::fs::symlink_metadata(&at).is_ok(),
                    "{name} as a {label} stays"
                );
            }
        }
        assert_eq!(std::fs::read(&target).unwrap(), b"outside bytes");
        assert!(
            std::fs::symlink_metadata(&dangling).is_err(),
            "the target of a dangling symlink is not created"
        );
    }
}