ostrya 0.18.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
//! The update lock: the lock that serializes the writes of refs and of the
//! other repository state outside the object store.
//!
//! These callers hold it:
//!
//! - An [`UpdateGuard`](crate::UpdateGuard), and each writer that the
//!   `UpdateGuard` doc lists.
//! - The receive path, while it reads the state of its target refs, checks
//!   it, and commits.
//! - Summary regeneration, while it refreshes the anchor commit and writes the
//!   summary.
//!
//! The lock is an exclusive `fcntl` record lock (`F_SETLK`) on
//! `<repo>/.update.lock`, beside `.lock`. The lock file opens by the rules of
//! `.lock`. The same process-global registry holds it, so the process keeps one
//! descriptor to it. [`Repo::begin_update`](crate::Repo::begin_update) states
//! the rules that a caller sees.
//!
//! Inside the process the lock is exclusive too. Its waiters queue in the order
//! of their first poll. Only the head of the queue makes lock requests.
//! Against another process the head runs the retry loop of the repository lock:
//! one non-blocking request, then a [`Timer`](ostrya_rt::Timer) wait of at most
//! [`POLL_INTERVAL`]. No request blocks in the kernel, so a dropped wait leaves
//! no lock request behind.
//!
//! The lock ignores `[core] locking` and always takes the record lock.

use std::collections::VecDeque;
#[cfg(test)]
use std::os::fd::BorrowedFd;
use std::os::fd::{AsFd, OwnedFd};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

use futures_lite::FutureExt;

use super::{LockKind, POLL_INTERVAL, Registered, get_or_register, unregister};
use crate::error::{Error, Result};
use crate::repo_fs::{self, FsError, RepoDir, RootFile};

/// The in-process state of an update lock: the hold and the queue of waiters.
#[derive(Debug)]
struct UpdateState {
    /// `true` while a guard holds the lock.
    held: bool,
    /// The ticket the next waiter takes.
    next_ticket: u64,
    /// The waiting tickets in request order, each with the waker of its last
    /// pending poll.
    queue: VecDeque<(u64, Option<Waker>)>,
}

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

impl UpdateLock {
    /// Returns the [`UpdateLock`] of the repository of the root handle
    /// `root`.
    ///
    /// On first use, the call creates `<repo>/.update.lock` if it is absent,
    /// and registers the lock. It makes synchronous file system calls, so run
    /// it on the blocking pool.
    ///
    /// The call opens the file by the rules of `.lock`, through the registry
    /// helper that the repository lock uses. A symlink or an entry that is not
    /// a regular file at `.update.lock` gives [`Error::InvalidFormat`], or
    /// [`Error::Io`] if the process cannot open the entry for write. The
    /// call refuses a file that shares its inode with `.lock` with
    /// [`Error::Io`].
    pub(crate) fn get_or_create(root: &RepoDir) -> Result<Arc<UpdateLock>> {
        get_or_register(root, RootFile::UpdateLock, Registered::update, |fd, key| {
            let lock = Arc::new(UpdateLock {
                key,
                fd: Some(fd),
                state: Mutex::new(UpdateState {
                    held: false,
                    next_ticket: 0,
                    queue: VecDeque::new(),
                }),
            });
            let registered = Registered::Update(Arc::downgrade(&lock));
            (lock, registered)
        })
    }

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

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

/// Takes the waker that the head of the queue left, if any.
///
/// The caller wakes it after it releases the state mutex. Call this only
/// while no guard holds the lock.
fn wake_head(st: &mut UpdateState) -> Option<Waker> {
    st.queue.front_mut().and_then(|(_, waker)| waker.take())
}

/// An acquired update lock. The drop releases it.
#[derive(Debug)]
pub(crate) struct UpdateLockHeld {
    lock: Arc<UpdateLock>,
}

impl UpdateLockHeld {
    /// Returns `true` if this hold is a hold of `lock`.
    pub(crate) fn is_of(&self, lock: &Arc<UpdateLock>) -> bool {
        Arc::ptr_eq(&self.lock, lock)
    }
}

impl Drop for UpdateLockHeld {
    fn drop(&mut self) {
        // The record lock goes first, because no waiter makes a request while
        // `held` is `true`. The release ignores errors, so it never fails.
        let _ = repo_fs::unlock(self.lock.fd().as_fd());
        let waker = match self.lock.state.lock() {
            Ok(mut st) => {
                st.held = false;
                wake_head(&mut st)
            }
            Err(_) => None,
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }
}

/// The outcome of one poll of the turn of a waiter.
enum Turn {
    /// The waiter holds the lock.
    Granted,
    /// The waiter is at the head and another process holds the lock.
    Contended,
    /// The deadline passes before the turn of the waiter comes.
    TimedOut,
}

/// The place of one waiter in the queue.
///
/// If a place drops before its grant, the drop removes it from the queue.
struct Place {
    lock: Arc<UpdateLock>,
    ticket: u64,
    granted: bool,
}

impl Place {
    /// Takes a ticket at the tail of the queue.
    fn enqueue(lock: Arc<UpdateLock>) -> Place {
        let ticket = {
            let mut st = lock.state.lock().unwrap();
            let ticket = st.next_ticket;
            st.next_ticket += 1;
            st.queue.push_back((ticket, None));
            ticket
        };
        Place {
            lock,
            ticket,
            granted: false,
        }
    }

    /// Makes one lock request if this place is the head and no guard holds the
    /// lock.
    ///
    /// Otherwise the call keeps the waker for the release that makes this
    /// place the head, and returns `Poll::Pending`. The request and the grant
    /// happen under the state mutex in one poll, so a dropped wait cannot leave
    /// a hold that no guard releases.
    fn poll_turn(&mut self, cx: &mut Context<'_>) -> Poll<std::result::Result<Turn, FsError>> {
        let mut st = self.lock.state.lock().unwrap();
        let head = st.queue.front().map(|(ticket, _)| *ticket) == Some(self.ticket);
        if head && !st.held {
            return match repo_fs::try_lock(self.lock.fd().as_fd(), LockKind::Exclusive) {
                Ok(true) => {
                    st.held = true;
                    st.queue.pop_front();
                    self.granted = true;
                    Poll::Ready(Ok(Turn::Granted))
                }
                Ok(false) => Poll::Ready(Ok(Turn::Contended)),
                Err(e) => Poll::Ready(Err(e)),
            };
        }
        if let Some((_, waker)) = st.queue.iter_mut().find(|(t, _)| *t == self.ticket) {
            *waker = Some(cx.waker().clone());
        }
        Poll::Pending
    }
}

impl Drop for Place {
    fn drop(&mut self) {
        if self.granted {
            return;
        }
        // A place that leaves the head hands the turn to the next waiter.
        let waker = match self.lock.state.lock() {
            Ok(mut st) => {
                let head = st.queue.front().map(|(ticket, _)| *ticket) == Some(self.ticket);
                st.queue.retain(|(ticket, _)| *ticket != self.ticket);
                if head && !st.held {
                    wake_head(&mut st)
                } else {
                    None
                }
            }
            Err(_) => None,
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }
}

/// Acquires the update lock within `timeout`.
///
/// If `timeout` is `None`, the wait has no deadline. `Some(Duration::ZERO)`
/// makes one attempt. The waiter takes its place in the queue on the first
/// poll of the returned future. The timeout covers the whole wait: the wait in
/// the queue and the retries against other processes.
///
/// If the deadline passes, the call returns [`Error::LockTimeout`] with the
/// whole seconds of `timeout`. If a lock request fails, it returns
/// [`Error::Io`].
pub(crate) async fn acquire_update(
    lock: Arc<UpdateLock>,
    timeout: Option<Duration>,
) -> Result<UpdateLockHeld> {
    // 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)));
    let mut place = Place::enqueue(lock);
    loop {
        let turn = futures_lite::future::poll_fn(|cx| place.poll_turn(cx));
        let turn = match deadline {
            Some((deadline, _)) => {
                let remaining = deadline.saturating_duration_since(Instant::now());
                turn.or(async {
                    ostrya_rt::Timer::after(remaining).await;
                    Ok::<_, FsError>(Turn::TimedOut)
                })
                .await?
            }
            None => turn.await?,
        };
        let wait = match turn {
            Turn::Granted => {
                return Ok(UpdateLockHeld {
                    lock: place.lock.clone(),
                });
            }
            Turn::TimedOut => None,
            Turn::Contended => match deadline {
                Some((deadline, _)) => {
                    let now = Instant::now();
                    (now < deadline).then(|| POLL_INTERVAL.min(deadline - now))
                }
                None => Some(POLL_INTERVAL),
            },
        };
        match (wait, deadline) {
            (Some(wait), _) => ostrya_rt::Timer::after(wait).await,
            (None, Some((_, secs))) => return Err(Error::LockTimeout { secs }),
            (None, None) => unreachable!("a wait with no deadline does not time out"),
        }
    }
}

/// Returns `true` if a guard of this process holds the update lock of the
/// repository at `repo_fd`.
///
/// The unit tests use it. The call reads the registry and does not open the
/// lock file. If the lock of the repository is not registered, it returns
/// `false`.
#[cfg(test)]
pub(crate) fn held_in_process(repo_fd: BorrowedFd<'_>) -> bool {
    let root = RepoDir::from_root_fd(repo_fd.try_clone_to_owned().unwrap());
    let found = {
        let reg = super::registry().map.lock().unwrap();
        super::probe(&reg, &root, RootFile::UpdateLock.name())
            .map(|entry| super::find(entry, Registered::update))
    };
    // The registry mutex is released before the lock can drop, because the
    // drop of the last reference takes the mutex again.
    match found {
        Some(super::Found::Live(lock)) => lock.state.lock().unwrap().held,
        _ => false,
    }
}

/// Compile-time checks that the update lock types are `Send + Sync`, and that
/// the future of `Repo::lock_update` is `Send`.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    fn assert_send<T: Send>(_: &T) {}
    assert_send_sync::<UpdateLock>();
    assert_send_sync::<UpdateLockHeld>();
    let _ = |repo: &crate::Repo| assert_send(&repo.lock_update());
};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CreateOptions, Repo};
    use futures_lite::future::poll_once;
    use ostrya_core::RepoMode;
    use std::os::unix::fs::PermissionsExt;
    use std::path::{Path, PathBuf};
    use std::pin::Pin;

    /// The environment variable that names the repository of the lock-holder
    /// helper process.
    const HOLDER_ENV: &str = "OSTRYA_UPDATE_HOLDER";

    /// The environment variable that names the marker file of the umask child.
    const UMASK_ENV: &str = "OSTRYA_UPDATE_UMASK_CHILD";

    /// The update lock file, relative to the repository root.
    const UPDATE_LOCK_FILE: &str = ".update.lock";

    /// A scratch directory that holds a repository at `repo`. The drop removes
    /// the directory.
    struct Scratch {
        dir: PathBuf,
    }

    impl Scratch {
        fn new(label: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "ostrya-update-lock-{label}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Scratch { dir }
        }

        fn path(&self) -> PathBuf {
            self.dir.join("repo")
        }

        /// Creates the repository in `mode`.
        fn create(&self, mode: RepoMode) -> Repo {
            ostrya_rt::block_on(Repo::create(&self.path(), CreateOptions::new(mode))).unwrap()
        }

        /// Creates the repository with `lock-timeout-secs` set to `secs`.
        fn create_with_timeout(&self, secs: i64) -> Repo {
            drop(self.create(RepoMode::BareUser));
            let config = self.path().join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(&format!("lock-timeout-secs={secs}\n"));
            std::fs::write(&config, text).unwrap();
            self.open()
        }

        fn open(&self) -> Repo {
            ostrya_rt::block_on(Repo::open(&self.path())).unwrap()
        }
    }

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

    /// Returns the lock of `repo` from the registry that holds the cached lock
    /// of the handle.
    fn lock_of(repo: &Repo) -> Arc<UpdateLock> {
        UpdateLock::get_or_create(repo.root_dir()).unwrap()
    }

    /// Returns the number of waiters in the queue of `lock`.
    fn waiters(lock: &UpdateLock) -> usize {
        lock.state.lock().unwrap().queue.len()
    }

    /// Waits until the queue of `lock` holds `n` waiters. The wait yields to
    /// the executor, so a task spawned on a single-threaded runtime can run.
    async fn wait_for_waiters(lock: &UpdateLock, n: usize) {
        for _ in 0..500 {
            if waiters(lock) == n {
                return;
            }
            ostrya_rt::Timer::after(Duration::from_millis(10)).await;
        }
        panic!("the queue never held {n} waiters");
    }

    type Pending = Pin<Box<dyn Future<Output = Result<UpdateLockHeld>> + Send>>;

    fn waiter(lock: &Arc<UpdateLock>, timeout: Option<Duration>) -> Pending {
        Box::pin(acquire_update(lock.clone(), timeout))
    }

    fn mode_of(path: &Path) -> u32 {
        std::fs::metadata(path).unwrap().permissions().mode() & 0o7777
    }

    /// Returns the mode that a file created with mode `0660` gets under the
    /// umask of this process.
    fn masked_lock_mode(dir: &Path) -> u32 {
        use std::os::unix::fs::OpenOptionsExt;
        let probe = dir.join("probe-file");
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o660)
            .open(&probe)
            .unwrap();
        mode_of(&probe)
    }

    #[test]
    fn the_lock_file_sits_at_the_repository_root_and_stays() {
        let scratch = Scratch::new("file");
        let repo = scratch.create(RepoMode::BareUser);
        let file = scratch.path().join(UPDATE_LOCK_FILE);
        assert!(!file.exists(), "the file is created on the first acquire");

        let guard = ostrya_rt::block_on(repo.lock_update()).unwrap();
        let meta = std::fs::symlink_metadata(&file).unwrap();
        assert!(
            meta.file_type().is_file(),
            "the lock file is a regular file"
        );
        assert_eq!(mode_of(&file), masked_lock_mode(&scratch.dir));

        drop(guard);
        drop(repo);
        assert!(file.exists(), "the lock file stays after the handle drops");
    }

    /// A lock file created in a `bare-user-shared` repository is `0660` under a
    /// umask of `0077`.
    ///
    /// The tests of this binary run in parallel threads, and the umask is a
    /// property of the process. For this reason, the acquire runs in a child
    /// process. The child is this test binary, run again for this test alone.
    #[test]
    fn a_shared_repository_forces_the_lock_mode() {
        if let Some(marker) = std::env::var_os(UMASK_ENV) {
            let marker = PathBuf::from(marker);
            rustix::process::umask(rustix::fs::Mode::from_raw_mode(0o077));
            let dir = marker.with_file_name("child");
            std::fs::create_dir_all(&dir).unwrap();
            assert_eq!(masked_lock_mode(&dir), 0o600, "umask 0077 applies");
            let path = dir.join("repo");
            ostrya_rt::block_on(async {
                let repo = Repo::create(&path, CreateOptions::new(RepoMode::BareUserShared))
                    .await
                    .unwrap();
                drop(repo.lock_update().await.unwrap());
            });
            assert_eq!(mode_of(&path.join(UPDATE_LOCK_FILE)), 0o660);
            std::fs::write(marker, b"ran").unwrap();
            return;
        }
        let scratch = Scratch::new("shared");
        let marker = scratch.dir.join("ran");
        let status = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "lock::update::tests::a_shared_repository_forces_the_lock_mode",
                "--exact",
                "--nocapture",
            ])
            .env(UMASK_ENV, &marker)
            .status()
            .expect("re-execute this test binary");
        assert!(status.success(), "the child failed: {status}");
        // If the filter of the child matches no test name, the child runs
        // nothing and exits 0. The marker shows that the check ran.
        assert!(marker.exists(), "the child ran no check");
    }

    #[test]
    fn an_existing_lock_file_keeps_its_mode() {
        let scratch = Scratch::new("existing");
        let repo = scratch.create(RepoMode::BareUserShared);
        let file = scratch.path().join(UPDATE_LOCK_FILE);
        std::fs::write(&file, b"").unwrap();
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();

        drop(ostrya_rt::block_on(repo.lock_update()).unwrap());
        assert_eq!(mode_of(&file), 0o600);
    }

    #[test]
    fn two_holders_in_one_process_serialize() {
        let scratch = Scratch::new("serialize");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        ostrya_rt::block_on(async {
            let first = repo.lock_update().await.unwrap();
            let mut second = waiter(&lock, None);
            assert!(poll_once(&mut second).await.is_none(), "the second waits");
            let err = acquire_update(lock.clone(), Some(Duration::ZERO))
                .await
                .unwrap_err();
            assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");

            drop(first);
            second.await.unwrap();
        });
    }

    #[test]
    fn two_handles_share_one_lock() {
        let scratch = Scratch::new("handles");
        drop(scratch.create(RepoMode::BareUser));
        let (a, b) = (scratch.open(), scratch.open());
        ostrya_rt::block_on(async {
            let first = a.lock_update().await.unwrap();
            let lock = lock_of(&b);
            // The first call on `b` opens the lock file on the blocking pool,
            // so it joins the queue only when the open completes.
            let mut second = Box::pin(b.lock_update());
            for _ in 0..500 {
                assert!(poll_once(&mut second).await.is_none(), "the second waits");
                if waiters(&lock) == 1 {
                    break;
                }
                ostrya_rt::Timer::after(Duration::from_millis(10)).await;
            }
            assert_eq!(waiters(&lock), 1, "the second joined the queue");
            assert!(poll_once(&mut second).await.is_none(), "the second waits");
            let first_lock = Arc::as_ptr(&first.lock);

            drop(first);
            let second = second.await.unwrap();
            assert_eq!(Arc::as_ptr(&second.lock), first_lock, "one cached lock");
        });
    }

    #[test]
    fn waiters_acquire_in_request_order() {
        let scratch = Scratch::new("order");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        ostrya_rt::block_on(async {
            let holder = repo.lock_update().await.unwrap();
            let mut pending = Vec::new();
            for label in ["B", "C", "D"] {
                let mut w = waiter(&lock, None);
                assert!(poll_once(&mut w).await.is_none());
                pending.push((label, w));
            }
            drop(holder);

            // Poll the waiters from the last to the first, so the poll order
            // does not match the request order.
            let mut order = Vec::new();
            while !pending.is_empty() {
                for i in (0..pending.len()).rev() {
                    if let Some(guard) = poll_once(&mut pending[i].1).await {
                        guard.unwrap();
                        order.push(pending.remove(i).0);
                    }
                }
            }
            assert_eq!(order, ["B", "C", "D"]);
        });
    }

    /// Calls through the handle join the queue on their first poll, so the
    /// call polled first takes the lock first.
    #[test]
    fn handle_calls_acquire_in_first_poll_order() {
        let scratch = Scratch::new("order-handle");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        ostrya_rt::block_on(async {
            let holder = repo.lock_update().await.unwrap();
            let mut x = Box::pin(repo.lock_update());
            let mut y = Box::pin(repo.lock_update());
            assert!(poll_once(&mut x).await.is_none());
            assert!(poll_once(&mut y).await.is_none());
            assert_eq!(waiters(&lock), 2, "both calls joined the queue");
            drop(holder);

            // Poll the second call first. It stays pending until the first
            // call releases.
            assert!(poll_once(&mut y).await.is_none(), "the second waits");
            let first = x.await.unwrap();
            assert!(poll_once(&mut y).await.is_none(), "the second waits");
            drop(first);
            drop(y.await.unwrap());
        });
    }

    #[test]
    fn spawned_waiters_acquire_in_request_order() {
        let scratch = Scratch::new("order-spawned");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        let order = Arc::new(Mutex::new(Vec::new()));
        ostrya_rt::block_on(async {
            let holder = repo.lock_update().await.unwrap();
            let mut tasks = Vec::new();
            for (n, label) in ["B", "C", "D"].into_iter().enumerate() {
                let (task_lock, order) = (lock.clone(), order.clone());
                tasks.push(ostrya_rt::spawn(async move {
                    let guard = acquire_update(task_lock, Some(Duration::from_secs(10))).await?;
                    order.lock().unwrap().push(label);
                    ostrya_rt::Timer::after(Duration::from_millis(10)).await;
                    drop(guard);
                    Ok::<_, Error>(())
                }));
                wait_for_waiters(&lock, n + 1).await;
            }
            drop(holder);
            for task in tasks {
                task.await.unwrap();
            }
        });
        assert_eq!(*order.lock().unwrap(), ["B", "C", "D"]);
    }

    #[test]
    fn a_dropped_or_timed_out_waiter_leaves_the_queue() {
        let scratch = Scratch::new("leave");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        let long = Some(Duration::from_secs(10));
        ostrya_rt::block_on(async {
            // If the head drops after the release wakes it, the next waiter
            // gets the turn.
            let holder = repo.lock_update().await.unwrap();
            let mut head = waiter(&lock, None);
            assert!(poll_once(&mut head).await.is_none());
            let next = ostrya_rt::spawn(acquire_update(lock.clone(), long));
            wait_for_waiters(&lock, 2).await;
            drop(holder);
            drop(head);
            let holder = next.await.unwrap();
            assert_eq!(waiters(&lock), 0);

            // A head that times out leaves the queue, and the next waiter takes
            // the lock on the release.
            let head = acquire_update(lock.clone(), Some(Duration::from_millis(50)));
            let mut head = Box::pin(head);
            assert!(poll_once(&mut head).await.is_none());
            let next = ostrya_rt::spawn(acquire_update(lock.clone(), long));
            wait_for_waiters(&lock, 2).await;
            let err = head.await.unwrap_err();
            assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
            assert_eq!(waiters(&lock), 1);
            drop(holder);
            drop(next.await.unwrap());
            assert_eq!(waiters(&lock), 0);
        });
    }

    #[test]
    fn the_shared_repository_lock_stays_available() {
        let scratch = Scratch::new("repo-lock");
        let repo = scratch.create_with_timeout(0);
        ostrya_rt::block_on(async {
            let _update = repo.lock_update().await.unwrap();
            let first = repo.lock_repo(LockKind::Shared).await.unwrap();
            let second = repo.lock_repo(LockKind::Shared).await.unwrap();
            drop((first, second));
        });
    }

    /// With `lock-timeout-secs=-1` a waiter in the queue takes the lock when
    /// the holder releases it.
    #[test]
    fn a_waiter_with_no_limit_takes_the_lock_on_release() {
        let scratch = Scratch::new("no-limit");
        let repo = scratch.create_with_timeout(-1);
        let lock = lock_of(&repo);
        let holder = ostrya_rt::block_on(repo.lock_update()).unwrap();
        let release = std::thread::spawn(move || {
            for _ in 0..5000 {
                if waiters(&lock) == 1 {
                    drop(holder);
                    return;
                }
                std::thread::sleep(Duration::from_millis(1));
            }
            panic!("the waiter never joined the queue");
        });
        drop(ostrya_rt::block_on(repo.lock_update()).unwrap());
        release.join().unwrap();
    }

    #[test]
    fn two_processes_serialize() {
        use std::process::{Command, Stdio};

        let scratch = Scratch::new("processes");
        let repo = scratch.create(RepoMode::BareUser);
        let lock = lock_of(&repo);
        let held = scratch.path().join(".held");
        let releasing = scratch.path().join(".releasing");
        let mut child = Command::new(std::env::current_exe().unwrap())
            .args([
                "lock::update::tests::update_lock_holder_subprocess",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env(HOLDER_ENV, scratch.path())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .expect("re-execute this test binary");
        for _ in 0..500 {
            if held.exists() {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(held.exists(), "the child never took the lock");

        ostrya_rt::block_on(async {
            let err = acquire_update(lock.clone(), Some(Duration::ZERO))
                .await
                .unwrap_err();
            assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
            // A wait of three poll intervals makes several requests, all of
            // which fail. The error states the whole seconds of the wait.
            let start = Instant::now();
            let err = acquire_update(lock.clone(), Some(Duration::from_millis(300)))
                .await
                .unwrap_err();
            assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
            assert!(start.elapsed() >= Duration::from_millis(300));

            let waiting = ostrya_rt::spawn(acquire_update(lock.clone(), None));
            wait_for_waiters(&lock, 1).await;
            drop(child.stdin.take());
            let guard = waiting.await.unwrap();
            assert!(releasing.exists(), "the lock came only after the release");
            drop(guard);
        });
        let output = child.wait_with_output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "the child reported {}:\n{stdout}",
            output.status
        );
    }

    /// The lock-holder half of [`two_processes_serialize`].
    ///
    /// It runs only if this test binary runs again with [`HOLDER_ENV`] set. It
    /// takes the update lock and writes `.held`. When its standard input
    /// closes, it writes `.releasing` and releases the lock.
    #[test]
    #[ignore = "helper process for two_processes_serialize"]
    fn update_lock_holder_subprocess() {
        use std::io::Read;

        let Some(path) = std::env::var_os(HOLDER_ENV).map(PathBuf::from) else {
            return;
        };
        let repo = ostrya_rt::block_on(Repo::open(&path)).unwrap();
        let guard = ostrya_rt::block_on(repo.lock_update()).unwrap();
        std::fs::write(path.join(".held"), b"1").unwrap();
        let mut sink = Vec::new();
        let _ = std::io::stdin().read_to_end(&mut sink);
        std::fs::write(path.join(".releasing"), b"1").unwrap();
        drop(guard);
    }

    #[test]
    fn a_lock_file_linked_to_the_repository_lock_is_refused() {
        use std::os::fd::AsRawFd;

        let scratch = Scratch::new("linked");
        let repo = scratch.create(RepoMode::BareUser);
        ostrya_rt::block_on(async {
            let guard = repo.lock_repo(LockKind::Shared).await.unwrap();
            let lock_file = scratch.path().join(".lock");
            std::fs::hard_link(&lock_file, scratch.path().join(UPDATE_LOCK_FILE)).unwrap();

            let err = repo.lock_update().await.unwrap_err();
            assert!(matches!(err, Error::Io(_)), "{err:?}");

            // The kernel still records the shared lock of this process on the
            // inode of `.lock`. The check reads the fdinfo of the descriptor
            // that set the lock. It lists only the locks that this process set
            // through that descriptor. It is a consistent snapshot, and
            // `/proc/locks` gives no consistent snapshot.
            let (lock, _) = guard.hold.as_ref().unwrap();
            let path = format!("/proc/self/fdinfo/{}", lock.fd().as_raw_fd());
            let info = std::fs::read_to_string(path).unwrap();
            let held = info.lines().any(|line| {
                let fields: Vec<&str> = line.split_whitespace().collect();
                fields.len() > 4
                    && fields[0] == "lock:"
                    && fields[2] == "POSIX"
                    && fields[4] == "READ"
            });
            assert!(held, "the repository lock was dropped:\n{info}");
        });
    }

    #[test]
    fn a_lock_file_that_is_a_symlink_to_the_repository_lock_is_refused() {
        use std::os::fd::AsRawFd;

        let scratch = Scratch::new("symlinked");
        let repo = scratch.create(RepoMode::BareUser);
        ostrya_rt::block_on(async {
            let guard = repo.lock_repo(LockKind::Shared).await.unwrap();
            std::os::unix::fs::symlink(".lock", scratch.path().join(UPDATE_LOCK_FILE)).unwrap();

            let err = repo.lock_update().await.unwrap_err();
            let expected = format!(
                "{UPDATE_LOCK_FILE} passes through a symlink; \
                 ostrya refuses a symlink in the repository"
            );
            assert!(
                matches!(&err, Error::InvalidFormat(m) if *m == expected),
                "{err:?}"
            );

            // The kernel still records the shared lock of this process on the
            // inode of `.lock`. The fdinfo of the descriptor that set the lock
            // is a consistent snapshot of the locks set through it.
            let (lock, _) = guard.hold.as_ref().unwrap();
            let path = format!("/proc/self/fdinfo/{}", lock.fd().as_raw_fd());
            let info = std::fs::read_to_string(path).unwrap();
            let held = info.lines().any(|line| {
                let fields: Vec<&str> = line.split_whitespace().collect();
                fields.len() > 4
                    && fields[0] == "lock:"
                    && fields[2] == "POSIX"
                    && fields[4] == "READ"
            });
            assert!(held, "the repository lock was dropped:\n{info}");
        });
    }
}