ostrya 0.12.1

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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
//! The export of collection refs onto removable media, and the import from
//! them.
//!
//! [`Repo::export_media`] copies the commits of collection refs onto a
//! mounted volume, into the repository `MOUNT/.ostree/repo`. A client that
//! has no network finds the repository on the volume and pulls from it. The
//! layout is the layout that `ostree create-usb` writes, and
//! `ostree find-remotes --pull` reads it.
//!
//! [`Repo::import_media`] finds the one media repository on the mounted
//! volumes, and pulls collection refs from it into the client repository,
//! under the trust of the remote of each collection.
//!
//! [`MediaExportOptions`] holds the options of the export, and
//! [`MediaExportReport`] gives the repository and the commit of each ref.
//! [`MediaImportOptions`] holds the options of the import, and
//! [`MediaImportReport`] gives the written, the unchanged, and the refused
//! refs.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};

use ostrya_core::{Checksum, ObjectType, Ref, RefSelector, RepoMode, is_valid_collection_id};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;

use crate::config::{RepoConfig, valid_remote_name};
use crate::error::{Error, Result};
use crate::pull::{
    PullVerify, TimestampCheck, check_collection_binding, check_ref_binding, collection_refs,
};
use crate::refs::ref_relpath;
use crate::related::RelatedRule;
use crate::repo::{CreateOptions, Repo};
use crate::repo_fs;
use crate::summary::{OSTREE_METADATA_REF, SummaryOptions};
use crate::verify::PullTrust;

mod find;
mod mountinfo;

use find::{FoundMedia, MediaChoice};

/// The path of the media repository under the mount directory.
const MEDIA_REPO: &str = ".ostree/repo";

/// The directory of the media repository under the mount directory.
const MEDIA_DIR: &str = ".ostree";

/// The options of [`Repo::export_media`].
#[derive(Debug, Clone, Default)]
pub struct MediaExportOptions {
    /// The commit that the one ref of the export gets, in place of the
    /// commit of the ref in the source.
    ///
    /// The source must hold the commit. The ref need not exist in the
    /// source. The commit can be older than the commit of the ref on the
    /// media. The default is `None`: each ref gets the commit of the ref in
    /// the source.
    pub commit: Option<Checksum>,
}

/// The result of [`Repo::export_media`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MediaExportReport {
    /// The path of the media repository: `MOUNT/.ostree/repo`.
    pub repo: PathBuf,
    /// Each exported ref as a collection ref `@ID:NAME`, with its commit, in
    /// the order of the operands. An operand that occurs two times is in the
    /// list one time.
    pub refs: Vec<(Ref, Checksum)>,
}

/// The options of [`Repo::import_media`].
///
/// With no ref in [`refs`](MediaImportOptions::refs) and no collection in
/// [`collections`](MediaImportOptions::collections), the import takes each
/// ref on the media whose collection has a matched remote.
#[derive(Debug, Clone, Default)]
pub struct MediaImportOptions {
    /// The directory that the media finder probes in place of the mount
    /// table.
    ///
    /// The directory need not be a mount point. The default is `None`: the
    /// finder reads the mount table of the process.
    pub mount: Option<PathBuf>,
    /// The refs to import.
    ///
    /// `NAME` ([`Ref::Local`]) is the ref `@OWN:NAME`, where `OWN` is the
    /// `[core] collection-id` of the client repository. `@ID:NAME`
    /// ([`Ref::Collection`]) is the ref `NAME` of the collection `ID`.
    pub refs: Vec<Ref>,
    /// The collections to import each ref of, as the prefix `@ID:` does.
    pub collections: Vec<String>,
}

/// The result of [`Repo::import_media`].
///
/// Each list holds refs as collection refs `@ID:NAME`, also for the
/// `[core] collection-id` of the client repository, in the order of the
/// import.
#[derive(Debug)]
pub struct MediaImportReport {
    /// The path of the media repository.
    pub repo: PathBuf,
    /// Each ref that the import wrote, with its new commit.
    pub written: Vec<(Ref, Checksum)>,
    /// Each ref whose current ref held the commit of the media before the
    /// import, with that commit. The import did not pull it, and did not
    /// write a ref for it. [`Repo::import_media`] states the current ref.
    pub unchanged: Vec<(Ref, Checksum)>,
    /// Each ref that the import refused, with the reason. The import did
    /// not change the ref.
    pub refused: Vec<(Ref, Error)>,
}

/// The reason why the media finder skipped a candidate repository that
/// exists.
///
/// [`Error::MediaNotFound`] holds each skipped candidate with its reason.
#[derive(Debug)]
#[non_exhaustive]
pub enum MediaSkip {
    /// The resolution of the path of the candidate crosses a mount point, a
    /// bind mount included. A btrfs subvolume of the mount is no mount
    /// point.
    OtherFileSystem,
    /// The candidate is the client repository.
    Client,
    /// The finder cannot open the candidate, read its summary, or open its
    /// repository.
    Unreadable(Error),
    /// The summary of the candidate lists no collection ref, or the
    /// candidate has no summary.
    NoCollectionRef,
}

impl Repo {
    /// Copies the commits of the collection refs `refs` of this repository
    /// onto the volume that is mounted at `mount`.
    ///
    /// The media repository is `mount/.ostree/repo`. The call does not
    /// check that `mount` is a mount point.
    ///
    /// # Refs
    ///
    /// Each operand names one collection ref of this repository, the source:
    ///
    /// - `NAME` ([`Ref::Local`]) is the local ref `refs/heads/NAME`. It goes
    ///   onto the media as the ref `@OWN:NAME`, where `OWN` is the
    ///   `[core] collection-id` of the source.
    /// - `@ID:NAME` ([`Ref::Collection`]) is the collection ref of `ID`. The
    ///   call reads it as [`resolve_ref_tip`](Repo::resolve_ref_tip) does:
    ///   `refs/heads/NAME` when `ID` is the own id, and else
    ///   `refs/mirrors/ID/NAME`.
    ///
    /// The call reads the ref files alone. It does not read the `summary` of
    /// the source, and it does not read `refs/remotes/`. An operand that
    /// occurs two times is exported one time. The operands can name refs of
    /// more than one collection.
    ///
    /// The tip commit of each ref must have an `ostree.collection-binding`
    /// that states `ID`. If the `ostree.ref-binding` key is present, it must
    /// name `NAME`.
    ///
    /// # Media repository
    ///
    /// The call resolves each ref and checks each tip before it creates or
    /// changes a file. It refuses a `mount/.ostree/repo` that is this
    /// repository: the same device and inode, also through a symlink. Then
    /// it creates `mount/.ostree` and the media repository in `archive`
    /// mode, if they do not exist. If `mount/.ostree/repo` holds an entry
    /// `config`, the call opens that repository. It keeps its mode and its
    /// `[core] collection-id`.
    ///
    /// The call makes one pull for each collection, in the order of the
    /// first operand of each collection. Each pull is a local pull at depth
    /// 0 with no signature check. It copies the `.commitmeta` of each
    /// commit, and the dependencies of field 2 of each commit as loose
    /// objects. It copies no static delta. It writes each ref to
    /// `refs/mirrors/ID/NAME`, or to `refs/heads/NAME` when `ID` is the
    /// `[core] collection-id` of the media repository. It moves a ref to an
    /// older commit with no error.
    ///
    /// Then the call sets `[core] indexed-deltas=true` in the `config` of the
    /// media repository, if the key does not hold `true`. Last, it writes
    /// the root summary of the media repository with
    /// [`root_summary_only`](SummaryOptions::root_summary_only): it removes
    /// an existing `summary.sig`, and it writes no `ostree-metadata` anchor
    /// commit.
    ///
    /// A failure after the checks, for example a full volume, can leave the
    /// media repository and objects on the volume. Each pull writes its refs
    /// when it completes, so a failure in the pull of a collection keeps the
    /// refs of the collections that the call pulled before it. The call then
    /// does not set `indexed-deltas` and writes no summary: the media
    /// repository keeps its old summary, or has none.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `refs` is empty, or if
    ///   [`commit`](MediaExportOptions::commit) is set and `refs` holds more
    ///   than one ref.
    /// - [`Error::InvalidRefspec`] if an operand is a remote ref, or fails
    ///   [`Ref::validate`].
    /// - [`Error::InvalidInput`] if an operand is a local ref and the source
    ///   has no `[core] collection-id`, or if two different operands name
    ///   one ref, for example `NAME` and `@OWN:NAME`.
    /// - [`Error::RefNotFound`] if the source does not hold a ref, with the
    ///   text `@ID:NAME`.
    /// - [`Error::NotARef`] if the path of an operand names a directory or a
    ///   special file, or an alias that breaks the alias rule, as
    ///   [`resolve_ref_tip`](Repo::resolve_ref_tip) states.
    /// - [`Error::ObjectNotFound`] if the source does not hold a tip commit,
    ///   for example the commit of [`commit`](MediaExportOptions::commit).
    /// - [`Error::Pull`] if a binding check of a tip fails.
    /// - [`Error::Io`] if the call cannot read the device and the inode of
    ///   this repository.
    /// - [`Error::Io`] if `mount` does not exist or is not a directory.
    /// - [`Error::InvalidInput`] if `mount/.ostree/repo` is this repository.
    ///   The errors above and this error come before the call creates a
    ///   file.
    /// - The errors of [`CreateOptions::create`] other than
    ///   [`Error::RepoExists`], of [`Repo::open`] for an existing media
    ///   repository, of [`pull_local`](Repo::pull_local), of
    ///   [`write_config`](Repo::write_config), and of
    ///   [`regenerate_summary`](Repo::regenerate_summary).
    pub async fn export_media(
        &self,
        mount: &Path,
        refs: &[Ref],
        options: MediaExportOptions,
    ) -> Result<MediaExportReport> {
        if refs.is_empty() {
            return Err(Error::InvalidInput("a media export needs a ref".into()));
        }
        if options.commit.is_some() && refs.len() > 1 {
            return Err(Error::InvalidInput(
                "a media export with a commit takes one ref".into(),
            ));
        }
        let wanted = self.media_refs(refs)?;

        // Each ref resolves, and each tip passes its checks, before the
        // export creates a file.
        let mut tips = Vec::with_capacity(wanted.len());
        for &(id, name) in &wanted {
            let tip = match options.commit {
                Some(commit) => commit,
                None => {
                    let target = Ref::collection(id, name);
                    self.resolve_ref_tip(&target)
                        .await?
                        .ok_or_else(|| Error::RefNotFound(target.to_string()))?
                }
            };
            let (commit, _) = self.load_commit(&tip).await?;
            check_ref_binding(&tip, &commit, name)?;
            check_collection_binding(&tip, &commit, id, false)?;
            tips.push(tip);
        }

        let source = self.clone();
        let dir = mount.to_owned();
        ostrya_rt::unblock(move || make_media_dir_blocking(&source, &dir)).await?;
        let path = mount.join(MEDIA_REPO);
        let mut media = match CreateOptions::new(RepoMode::Archive).create(&path).await {
            Err(Error::RepoExists(_)) => Repo::open(&path).await?,
            created => created?,
        };

        // One pull for each collection, in the order of its first ref.
        let mut collections: Vec<(&str, Vec<(String, Checksum)>)> = Vec::new();
        for (&(id, name), tip) in wanted.iter().zip(&tips) {
            let slot = match collections.iter().position(|(other, _)| *other == id) {
                Some(slot) => slot,
                None => {
                    collections.push((id, Vec::new()));
                    collections.len() - 1
                }
            };
            collections[slot].1.push((name.to_owned(), *tip));
        }
        for (id, targets) in collections {
            media
                .pull_local_pinned(
                    self,
                    id,
                    targets,
                    HashMap::new(),
                    PullTrust::unverified(),
                    TimestampCheck::Off,
                )
                .await?;
        }

        // The summary reads `[core] indexed-deltas` from the config of the
        // handle, and an absent key reads as `true`. Only a key with another
        // value needs a new handle that reads the written config.
        if !matches!(
            media.config().keyfile().get_bool("core", "indexed-deltas"),
            Ok(Some(true))
        ) {
            let stale = !matches!(media.config().indexed_deltas(), Ok(true));
            let mut keyfile = media.config().keyfile().clone();
            keyfile.set_value("core", "indexed-deltas", "true")?;
            media.write_config(&keyfile).await?;
            if stale {
                media = Repo::open(&path).await?;
            }
        }
        media
            .regenerate_summary(&SummaryOptions {
                root_summary_only: true,
                ..SummaryOptions::default()
            })
            .await?;

        Ok(MediaExportReport {
            repo: path,
            refs: wanted
                .into_iter()
                .zip(tips)
                .map(|((id, name), tip)| (Ref::collection(id, name), tip))
                .collect(),
        })
    }

    /// Finds the one media repository on the mounted volumes, and pulls
    /// collection refs from it into this repository, the client.
    ///
    /// # Media repository
    ///
    /// The media finder reads the mount table of the process, or probes the
    /// directory [`mount`](MediaImportOptions::mount) alone. In the mount
    /// table, it skips a mount whose directory any user can write, such as
    /// `/tmp` or `/dev/shm`. On each mount, it probes each entry of
    /// `.ostree/repos.d/`, then `.ostree/repo`, `ostree/repo`, and
    /// `var/lib/flatpak/repo`. The media repository of a mount is the first
    /// candidate whose summary lists a collection ref. When the summary
    /// states a collection id, the finder does not count the anchor ref
    /// `ostree-metadata` in field 0.
    /// The finder skips a candidate on another file system than the mount,
    /// the client repository, and a candidate that it cannot read. The
    /// import needs exactly one media repository.
    ///
    /// # Refs
    ///
    /// A ref `@ID:NAME` is on the media when the ref files of the media
    /// repository and its `summary` both list it. The summary lists the refs
    /// of `ID` in field 0 when it states the collection id `ID`, and else in
    /// the first entry of `ID` in `ostree.summary.collection-map`. For the
    /// collection id that the summary states, the import does not count the
    /// ref `ostree-metadata` as listed, because it is the anchor ref of the
    /// media repository. The commit of the ref is the commit that the summary
    /// lists, and its timestamp is the `ostree.commit.timestamp` that the
    /// summary lists. The import reads no `summary.sig`.
    ///
    /// The import takes these refs, in this order:
    ///
    /// 1. Each ref of [`refs`](MediaImportOptions::refs), in order.
    /// 2. Each ref on the media of each collection of
    ///    [`collections`](MediaImportOptions::collections), in the order of
    ///    the collections, and in the byte order of the names in one
    ///    collection.
    ///
    /// A ref that the options name two times is imported one time. With no
    /// ref and no collection, the import takes each ref on the media whose
    /// collection has a matched remote, in the byte order of the collection
    /// ids and then of the names. It ignores each other collection.
    ///
    /// # Matched remote
    ///
    /// The matched remote of the collection `ID` is the first remote, in the
    /// byte order of the names, whose `collection-id` is `ID`. If no remote
    /// has that `collection-id`, it is the first remote whose
    /// `mirrored-collection-ids` holds `ID`. The import ignores a remote
    /// whose name or `collection-id` is not valid. It reads no summary of a
    /// remote.
    ///
    /// # Trust
    ///
    /// The import checks the commits of a collection with the trust of its
    /// matched remote, as [`PullTrust::from_remote`] reads it, with no check
    /// of the summary. If that trust checks no commit signature, the import
    /// checks the GPG signature of each commit with the keys of a pull from
    /// the remote with `gpg-verify=true`: the keyring of the remote, or the
    /// global trusted keyrings when the remote has no keyring of its own,
    /// and each keyring that `gpgkeypath` names. A build without the
    /// `verify-gpg` feature refuses each ref of such a remote whose current
    /// ref does not hold the commit of the media.
    ///
    /// # Pull
    ///
    /// The import writes the ref `@ID:NAME` to `refs/mirrors/ID/NAME`, or to
    /// `refs/heads/NAME` when `ID` is the `[core] collection-id` of this
    /// repository. The current ref of `@ID:NAME` is the ref at that place,
    /// read as [`resolve_ref_tip`](Repo::resolve_ref_tip) reads it. A path
    /// to that place through a file holds no ref. A directory or a special
    /// file at that place fails the read of the current ref with
    /// [`Error::NotARef`]. If this repository has no ref at that place, and
    /// the `collection-id` of the matched remote `R` is `ID`, the current ref
    /// is `refs/remotes/R/NAME`, read by the same rules. A remote ref whose
    /// commit this repository does not store gives no current ref. Under the
    /// `[core] collection-id`, the import reads no ref under
    /// `refs/remotes/`.
    ///
    /// The import does not pull a ref whose current ref holds the commit of
    /// the media. It makes one local pull from the media repository for each
    /// other ref, with its own transaction, as the pull of a local candidate
    /// of [`Repo::pull_collection`] does. The pull is at depth 0, and reads
    /// no static delta. It takes the `.commitmeta` and the dependencies of
    /// field 2 of the commit. The `ostree.collection-binding` of the commit
    /// must state `ID`, and the ref-binding check applies. The pull refuses
    /// a commit that is older than the commit of the current ref. If the
    /// current ref is the ref at the place that the import writes, and this
    /// repository does not store its commit, the pull refuses the ref with
    /// [`Error::ObjectNotFound`]. It also refuses a commit whose timestamp
    /// is not the timestamp that the summary lists for the ref.
    ///
    /// A read of the current ref that fails refuses its ref, and so does a
    /// pull that fails. The import then continues with the next ref.
    /// [`MediaImportReport::refused`] holds the error.
    ///
    /// # Errors
    ///
    /// The import gives each error below before its first pull, and then
    /// changes no ref.
    ///
    /// - [`Error::InvalidRefspec`] if a ref of
    ///   [`refs`](MediaImportOptions::refs) is a remote ref or fails
    ///   [`Ref::validate`], or if a collection id of
    ///   [`collections`](MediaImportOptions::collections) is not valid. The
    ///   error of a collection id holds the text `@ID:`.
    /// - [`Error::InvalidInput`] if a ref is a local ref and this repository
    ///   has no `[core] collection-id`, or if two different refs name one
    ///   ref, for example `NAME` and `@OWN:NAME`.
    /// - [`Error::InvalidInput`] if a collection of the options has no
    ///   matched remote. The import gives this error before it reads the
    ///   media.
    /// - [`Error::Core`] if the `collection-id` of a remote holds a malformed
    ///   escape sequence, and the errors of
    ///   [`Remote::mirrored_collection_ids`](crate::config::Remote::mirrored_collection_ids).
    /// - The errors of
    ///   [`generate_composefs`](crate::config::RepoConfig::generate_composefs),
    ///   and [`Error::Core`] if `[ex-ostrya] keep-detached-related` of this
    ///   repository is not a boolean.
    /// - [`Error::Io`] if the finder cannot open
    ///   [`mount`](MediaImportOptions::mount), cannot read the mount table,
    ///   or cannot read the device and the inode of this repository.
    /// - [`Error::MediaNotFound`] if the finder finds no media repository.
    /// - [`Error::AmbiguousMedia`] if the finder finds more than one media
    ///   repository.
    /// - [`Error::Core`] or [`Error::InvalidFormat`] if the summary of the
    ///   media repository does not parse.
    /// - [`Error::InvalidFormat`] if the summary lists a ref with a valid name
    ///   of a collection that the import reads, and the ref has no
    ///   `ostree.commit.timestamp` of type `t`.
    /// - [`Error::RefNotFound`] if a ref of the options is not on the media,
    ///   with the text `@ID:NAME`, or if a collection of the options has no
    ///   ref on the media, with the text `@ID:`.
    /// - The errors of
    ///   [`list_collection_refs_in`](Repo::list_collection_refs_in) on the
    ///   media repository.
    /// - The errors of [`PullTrust::from_remote`] for the matched remote of a
    ///   ref that the import pulls. The import reads no trust for an
    ///   unchanged ref, or for a ref whose current ref it cannot read.
    pub async fn import_media(&self, options: MediaImportOptions) -> Result<MediaImportReport> {
        let named = self.media_refs(&options.refs)?;
        let mut prefixes: Vec<&str> = Vec::new();
        for id in &options.collections {
            if !is_valid_collection_id(id) {
                return Err(Error::InvalidRefspec(format!("@{id}:")));
            }
            if !prefixes.contains(&id.as_str()) {
                prefixes.push(id);
            }
        }
        // The commit of each transaction reads these keys again. These reads
        // fail a bad value before the scan of the media.
        self.config().generate_composefs()?;
        RelatedRule::of(self.config())?;

        // Each collection of the options, with its matched remote, before
        // the scan of the media.
        let remotes = served_collections(self.config())?;
        let mut collections: Vec<(&str, &str)> = Vec::new();
        for id in named
            .iter()
            .map(|&(id, _)| id)
            .chain(prefixes.iter().copied())
        {
            if collections.iter().any(|&(other, _)| other == id) {
                continue;
            }
            let Some(remote) = matched_remote(&remotes, id) else {
                return Err(Error::InvalidInput(format!(
                    "no remote matches the collection {id}: no remote has collection-id={id}, \
                     and no remote holds {id} in mirrored-collection-ids"
                )));
            };
            collections.push((id, remote));
        }
        let no_operand = named.is_empty() && prefixes.is_empty();
        if no_operand {
            // Each collection that a remote serves, in byte order.
            let mut ids: Vec<&str> = remotes
                .iter()
                .flat_map(|remote| {
                    remote
                        .collection_id
                        .as_deref()
                        .into_iter()
                        .chain(remote.mirrored.iter().map(String::as_str))
                })
                .collect();
            ids.sort_unstable();
            ids.dedup();
            collections = ids
                .into_iter()
                .filter_map(|id| Some((id, matched_remote(&remotes, id)?)))
                .collect();
        }

        let choice = match &options.mount {
            Some(dir) => find::find_media_in(self, dir).await?,
            None => find::find_media(self, mountinfo::read_table().await?).await?,
        };
        let FoundMedia {
            path,
            repo: media,
            summary,
        } = take_media(choice)?;
        let ids: Vec<String> = collections.iter().map(|&(id, _)| id.to_owned()).collect();
        let mut listed = ostrya_rt::unblock(move || summary_collections(&summary, &ids)).await?;
        if no_operand {
            collections.retain(|&(id, _)| listed.get(id).is_some_and(|refs| !refs.is_empty()));
        }

        // The refs of each collection on the media: the summary lists them,
        // and the media repository holds their ref files. For a collection
        // that only named refs select, the listing reads the files of these
        // names alone. A valid ref name holds no wildcard, so each name is a
        // literal pattern.
        let all = RefSelector::parse([])?;
        let mut on_media: HashMap<&str, ListedTips> = HashMap::new();
        for &(id, _) in &collections {
            let only_named = !no_operand && !prefixes.contains(&id);
            let selector = if only_named {
                RefSelector::parse(
                    named
                        .iter()
                        .filter(|&&(other, _)| other == id)
                        .map(|&(_, name)| name),
                )?
            } else {
                all.clone()
            };
            let files: HashSet<String> = media
                .list_collection_refs_in(id, &selector)
                .await?
                .into_iter()
                .map(|(name, _)| name)
                .collect();
            let mut refs = listed.remove(id).unwrap_or_default();
            refs.retain(|name, _| files.contains(name));
            on_media.insert(id, refs);
        }
        drop(listed);

        let mut selected: Vec<(&str, String, (Checksum, u64))> = Vec::new();
        let seen: HashSet<(&str, &str)> = named.iter().copied().collect();
        for &(id, name) in &named {
            let Some(&tip) = on_media[id].get(name) else {
                return Err(Error::RefNotFound(Ref::collection(id, name).to_string()));
            };
            selected.push((id, name.to_owned(), tip));
        }
        for &id in &prefixes {
            let refs = on_media.remove(id).unwrap_or_default();
            if refs.is_empty() {
                return Err(Error::RefNotFound(format!("@{id}:")));
            }
            for (name, tip) in refs {
                if !seen.contains(&(id, name.as_str())) {
                    selected.push((id, name, tip));
                }
            }
        }
        if no_operand {
            for &(id, _) in &collections {
                for (name, tip) in on_media.remove(id).unwrap_or_default() {
                    selected.push((id, name, tip));
                }
            }
        }
        // Only the selected refs stay in memory during the pulls.
        drop(on_media);

        // The matched remote whose remote refs count for each collection: a
        // remote whose `collection-id` is the collection, when the collection
        // is not the `[core] collection-id` of this repository.
        let own = self.config().collection_id();
        let tracked: HashMap<&str, &str> = collections
            .iter()
            .copied()
            .filter(|&(id, remote)| {
                Some(id) != own
                    && remotes
                        .iter()
                        .any(|r| r.name == remote && r.collection_id.as_deref() == Some(id))
            })
            .collect();

        // The current ref is the ref that the pull writes. If that ref is
        // absent, it is the remote ref of the remote in `tracked`. A remote
        // ref whose commit this repository does not store is no current ref.
        // The ref that the pull writes is read with the reader of the pull,
        // so a directory at that place fails the read with `NotARef`.
        let mut tips = Vec::with_capacity(selected.len());
        for &(id, ref name, _) in &selected {
            let mut check = TimestampCheck::CurrentRef;
            let mut tip = match ref_relpath(own, &Ref::collection(id, name)) {
                Ok(relpath) => self.resolve_relpath_tip(relpath).await,
                Err(e) => Err(e),
            };
            if let (Ok(None), Some(&remote)) = (&tip, tracked.get(id)) {
                tip = self.resolve_ref_tip(&Ref::remote(remote, name)).await;
                if let Ok(Some(remote_tip)) = tip {
                    match self.has_object(ObjectType::Commit, &remote_tip).await {
                        Ok(true) => check = TimestampCheck::Rev(remote_tip),
                        Ok(false) => tip = Ok(None),
                        Err(e) => tip = Err(e),
                    }
                }
            }
            tips.push((tip, check));
        }

        // The trust of each matched remote of a ref to pull, one time, before
        // the first pull.
        let remote_of: HashMap<&str, &str> = collections.iter().copied().collect();
        let mut trusts: HashMap<&str, Option<PullTrust>> = HashMap::new();
        for ((id, _, (commit, _)), (tip, _)) in selected.iter().zip(&tips) {
            let remote = remote_of[id];
            if matches!(tip, Ok(tip) if *tip != Some(*commit)) && !trusts.contains_key(remote) {
                trusts.insert(remote, self.media_trust(remote).await?);
            }
        }

        let mut report = MediaImportReport {
            repo: path,
            written: Vec::new(),
            unchanged: Vec::new(),
            refused: Vec::new(),
        };
        for ((id, name, (commit, timestamp)), (tip, check)) in selected.into_iter().zip(tips) {
            let target = Ref::collection(id, name.as_str());
            match tip {
                Ok(Some(tip)) if tip == commit => {
                    report.unchanged.push((target, commit));
                    continue;
                }
                Ok(_) => {}
                Err(e) => {
                    report.refused.push((target, e));
                    continue;
                }
            }
            let remote = remote_of[id];
            let Some(trust) = &trusts[remote] else {
                report.refused.push((target, no_gpg_engine(remote)));
                continue;
            };
            let listed = HashMap::from([(name.clone(), timestamp)]);
            let targets = vec![(name, commit)];
            match self
                .pull_local_pinned(&media, id, targets, listed, trust.clone(), check)
                .await
            {
                Ok(_) => report.written.push((target, commit)),
                Err(e) => report.refused.push((target, e)),
            }
        }
        Ok(report)
    }

    /// Returns the trust of the import of the refs whose matched remote is
    /// `remote`, as [`import_media`](Repo::import_media) states, or `None`
    /// if the import needs a GPG check that this build cannot make.
    async fn media_trust(&self, remote: &str) -> Result<Option<PullTrust>> {
        // The summary of the media is unsigned, so the import checks no
        // summary.
        let verify = PullVerify {
            gpg_summary: Some(false),
            sign_summary: Some(false),
            ..PullVerify::default()
        };
        let trust = PullTrust::for_pull(self, remote, &verify, None).await?;
        if trust.checks_signatures() {
            return Ok(Some(trust));
        }
        #[cfg(feature = "verify-gpg")]
        {
            let verify = PullVerify {
                gpg: Some(true),
                ..verify
            };
            PullTrust::for_pull(self, remote, &verify, None)
                .await
                .map(Some)
        }
        #[cfg(not(feature = "verify-gpg"))]
        Ok(None)
    }

    /// Returns the collection id and the name of each ref of the operands
    /// `refs`, in order, as [`export_media`](Repo::export_media) states. An
    /// operand that occurs two times gives one entry.
    fn media_refs<'a>(&'a self, refs: &'a [Ref]) -> Result<Vec<(&'a str, &'a str)>> {
        let own = self.config().collection_id();
        let mut seen: HashMap<(&str, &str), &Ref> = HashMap::new();
        let mut wanted = Vec::with_capacity(refs.len());
        for r in refs {
            r.validate()?;
            let pair = match r {
                Ref::Local { name } => match own {
                    Some(id) => (id, name.as_str()),
                    None => {
                        return Err(Error::InvalidInput(format!(
                            "the ref {r} needs the collection id of the repository, and the \
                             repository has none"
                        )));
                    }
                },
                Ref::Collection { id, name } => (id.as_str(), name.as_str()),
                Ref::Remote { .. } => return Err(Error::InvalidRefspec(r.to_string())),
            };
            match seen.get(&pair) {
                Some(first) if *first == r => continue,
                Some(first) => {
                    return Err(Error::InvalidInput(format!(
                        "the refs {first} and {r} name one ref @{}:{}",
                        pair.0, pair.1
                    )));
                }
                None => {
                    seen.insert(pair, r);
                    wanted.push(pair);
                }
            }
        }
        Ok(wanted)
    }
}

/// Opens the directory `mount`, refuses a `mount/.ostree/repo` that is the
/// repository `source`, and creates the directory `.ostree` in `mount` if
/// it does not exist, with the mode `0777` less the file-creation mask.
fn make_media_dir_blocking(source: &Repo, mount: &Path) -> Result<()> {
    let stat = repo_fs::stat_fd(source.repo_fd())?;
    let own = (stat.dev, stat.ino);
    let fd = rustix::fs::open(
        mount,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    // A media repository that does not open is no source repository. The
    // create reports its error.
    if let Ok(media) = rustix::fs::openat(
        &fd,
        MEDIA_REPO,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    ) && find::identity(&media)? == own
    {
        return Err(Error::InvalidInput(format!(
            "the media repository {} is the source repository",
            mount.join(MEDIA_REPO).display()
        )));
    }
    match rustix::fs::mkdirat(&fd, MEDIA_DIR, Mode::from_raw_mode(0o777)) {
        Ok(()) | Err(Errno::EXIST) => Ok(()),
        Err(e) => Err(e.into()),
    }
}

/// The collections that one remote serves.
struct ServedCollections<'a> {
    /// The name of the remote.
    name: &'a str,
    /// The `collection-id` of the remote.
    collection_id: Option<String>,
    /// The `mirrored-collection-ids` of the remote.
    mirrored: Vec<String>,
}

/// Returns the collections of each remote of `config`, in the byte order of
/// the names. The list leaves out a remote whose name or `collection-id` is
/// not valid.
///
/// # Errors
///
/// - [`Error::Core`] if a `collection-id` holds a malformed escape sequence.
/// - The errors of
///   [`Remote::mirrored_collection_ids`](crate::config::Remote::mirrored_collection_ids).
fn served_collections(config: &RepoConfig) -> Result<Vec<ServedCollections<'_>>> {
    let mut names: Vec<&str> = config
        .remotes()
        .filter(|name| valid_remote_name(name))
        .collect();
    names.sort_unstable();
    names.dedup();
    let mut served = Vec::with_capacity(names.len());
    for name in names {
        let Some(remote) = config.remote(name) else {
            continue;
        };
        let collection_id = remote.collection_id()?;
        if collection_id
            .as_deref()
            .is_some_and(|id| !is_valid_collection_id(id))
        {
            continue;
        }
        served.push(ServedCollections {
            name,
            collection_id,
            mirrored: remote.mirrored_collection_ids()?,
        });
    }
    Ok(served)
}

/// Returns the matched remote of the collection `id` among `remotes`, as
/// [`Repo::import_media`] states, or `None` if no remote matches.
fn matched_remote<'a>(remotes: &[ServedCollections<'a>], id: &str) -> Option<&'a str> {
    remotes
        .iter()
        .find(|remote| remote.collection_id.as_deref() == Some(id))
        .or_else(|| {
            remotes
                .iter()
                .find(|remote| remote.mirrored.iter().any(|other| other == id))
        })
        .map(|remote| remote.name)
}

/// Applies the rule of one media repository to the result `choice` of the
/// media finder.
fn take_media(choice: MediaChoice) -> Result<FoundMedia> {
    match choice {
        MediaChoice::One(found) => Ok(found),
        MediaChoice::None(skipped) => Err(Error::MediaNotFound { skipped }),
        MediaChoice::Many(paths) => Err(Error::AmbiguousMedia { paths }),
    }
}

/// The refs of one collection that the media summary lists: each name, in
/// byte order, with its commit and its timestamp.
type ListedTips = BTreeMap<String, (Checksum, u64)>;

/// Returns the refs that the media summary `bytes` lists for each
/// collection of `ids`, with their commits and their timestamps, as
/// [`collection_refs`] reads them. The call leaves out a name that fails the
/// ref-name rule, and the anchor ref `ostree-metadata` of the media
/// repository in field 0. It parses the refs of the collections of `ids`
/// alone.
///
/// # Errors
///
/// - [`Error::Core`] or [`Error::InvalidFormat`] if the bytes do not parse,
///   or if the collection map is malformed.
/// - [`Error::InvalidFormat`] if a ref with a valid name of a collection of
///   `ids` has no `ostree.commit.timestamp` of type `t`.
fn summary_collections(bytes: &[u8], ids: &[String]) -> Result<BTreeMap<String, ListedTips>> {
    let mut listed = BTreeMap::new();
    for id in ids {
        let (own, refs) = collection_refs(bytes, id, None)?;
        // Field 0 also lists the anchor ref of the media repository.
        let names = refs
            .listed
            .into_iter()
            .filter(|entry| !own || entry.name != OSTREE_METADATA_REF)
            .map(|entry| (entry.name, (entry.commit, entry.timestamp)))
            .collect();
        listed.insert(id.clone(), names);
    }
    Ok(listed)
}

/// Returns the refusal of a ref whose matched remote `remote` checks no
/// commit signature, in a build with no GPG engine.
fn no_gpg_engine(remote: &str) -> Error {
    Error::Unsupported(format!(
        "remote '{remote}' checks no commit signature, so the media import checks the GPG \
         signature of the commit with the keyrings of the remote, and this build has no GPG \
         engine; build with the verify-gpg feature, or turn on sign-verify or a trust group \
         for the remote"
    ))
}

/// The options, the reports, and the futures of an export and an import
/// move across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<MediaExportOptions>();
    assert_send_sync::<MediaExportReport>();
    assert_send_sync::<MediaImportOptions>();
    assert_send_sync::<MediaImportReport>();
    assert_send_sync::<MediaSkip>();
    fn assert_send<T: Send>(_: &T) {}
    let _ = |repo: &Repo, mount: &Path, refs: &[Ref]| {
        assert_send(&repo.export_media(mount, refs, MediaExportOptions::default()))
    };
    let _ = |repo: &Repo| assert_send(&repo.import_media(MediaImportOptions::default()));
};

#[cfg(test)]
mod tests {
    use super::*;

    /// No media repository gives each skipped candidate, and more than one
    /// gives the path of each.
    #[test]
    fn the_finder_result_maps_to_the_media_errors() {
        let skipped = vec![(PathBuf::from("/mnt/a/.ostree/repo"), MediaSkip::Client)];
        let err = take_media(MediaChoice::None(skipped)).err().unwrap();
        assert!(
            matches!(&err, Error::MediaNotFound { skipped }
                if matches!(skipped.as_slice(), [(path, MediaSkip::Client)]
                    if path == Path::new("/mnt/a/.ostree/repo"))),
            "{err:?}"
        );
        let paths = vec![
            PathBuf::from("/mnt/b/ostree/repo"),
            PathBuf::from("/mnt/a/.ostree/repo"),
        ];
        let err = take_media(MediaChoice::Many(paths.clone())).err().unwrap();
        assert!(
            matches!(&err, Error::AmbiguousMedia { paths: got } if *got == paths),
            "{err:?}"
        );
        assert!(err.to_string().contains("/mnt/b/ostree/repo"), "{err}");
    }

    /// The summary parse reads the first collection-map entry of an id, with
    /// the commit and the timestamp of each ref, and parses no collection
    /// that the caller does not ask for. A ref with no timestamp in a
    /// collection that the caller asks for fails the parse.
    #[test]
    fn the_summary_parse_reads_the_first_map_entry_of_an_id() {
        use ostrya_core::{Type, Value, to_bytes};

        use crate::summary::COMMIT_TIMESTAMP_KEY;

        let entry = |name: &str, byte: u8, timestamp: Option<u64>| {
            let metadata = timestamp.map(|ts| {
                Value::Tuple(vec![
                    Value::Str(COMMIT_TIMESTAMP_KEY.to_owned()),
                    Value::variant(Type::parse("t").unwrap(), Value::U64(ts.swap_bytes())),
                ])
            });
            Value::Tuple(vec![
                Value::Str(name.to_owned()),
                Value::Tuple(vec![
                    Value::U64(0),
                    Value::Bytes(vec![byte; 32]),
                    Value::Array(metadata.into_iter().collect()),
                ]),
            ])
        };
        let collection = |id: &str, refs: Vec<Value>| {
            Value::Tuple(vec![Value::Str(id.to_owned()), Value::Array(refs)])
        };
        let summary = |map: Vec<Value>| {
            let metadata = Value::Array(vec![Value::Tuple(vec![
                Value::Str("ostree.summary.collection-map".to_owned()),
                Value::variant(
                    Type::parse("a{sa(s(taya{sv}))}").unwrap(),
                    Value::Array(map),
                ),
            ])]);
            let summary = Value::Tuple(vec![Value::Array(Vec::new()), metadata]);
            to_bytes(&Type::parse("(a(s(taya{sv}))a{sv})").unwrap(), &summary).unwrap()
        };

        let bytes = summary(vec![
            collection("org.x", vec![entry("a", 1, Some(1000))]),
            collection("org.x", vec![entry("b", 2, Some(2000))]),
            collection("org.y", vec![entry("c", 3, None)]),
        ]);
        let listed = summary_collections(&bytes, &["org.x".to_owned()]).unwrap();
        let x: Vec<(&str, &(Checksum, u64))> = listed["org.x"]
            .iter()
            .map(|(name, tip)| (name.as_str(), tip))
            .collect();
        assert_eq!(x, [("a", &(Checksum::from_bytes([1; 32]), 1000))]);
        assert!(!listed.contains_key("org.y"), "{listed:?}");

        let bytes = summary(vec![collection(
            "org.x",
            vec![entry("a", 1, Some(1000)), entry("b", 2, None)],
        )]);
        let err = summary_collections(&bytes, &["org.x".to_owned()]).unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
    }
}