ostrya 0.15.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
//! The state of a bucket repository that a writer reads: the `config`, the
//! refs, and the presence of a summary signature.

use std::collections::{BTreeMap, BTreeSet};

use ostrya_core::{Checksum, RepoMode, is_ref_name, is_valid_collection_id};

use super::BucketRepo;
use crate::config::RepoConfig;
use crate::error::{Error, Result};
use crate::pull::drive::Slots;
use crate::remote::s3::Object;
use crate::repo::MAX_CONFIG_SIZE;

/// The size of a ref file: 64 hex digits and a newline.
const REF_FILE_SIZE: u64 = 65;

/// The one byte of a partial-commit marker, as the `ostree` command writes
/// it into a `.commitpartial` marker when its fsck finds a commit incomplete
/// (observed).
pub(super) const PARTIAL_STATE_BYTE: u8 = 0x66;

/// The refs of a bucket repository.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct BucketRefs {
    /// The refs `refs/heads/NAME`, by name.
    pub(crate) heads: BTreeMap<String, Checksum>,
    /// The refs `refs/mirrors/ID/NAME`, by collection id, then by name. The
    /// own collection id is not in the map.
    pub(crate) mirrors: BTreeMap<String, BTreeMap<String, Checksum>>,
    /// The refs `refs/mirrors/ID/NAME` of the own collection id, by name.
    /// A read with [`OwnMirrors::Read`] alone fills the map.
    pub(crate) own_mirrors: BTreeMap<String, Checksum>,
}

/// The rule of [`BucketRepo::read_refs`] for a key under `refs/mirrors/ID/`
/// of the own collection id.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum OwnMirrors {
    /// Skip each such key. The read checks no name and reads no ref file.
    Skip,
    /// Check and read each such key as each other key, into
    /// [`BucketRefs::own_mirrors`].
    Read,
}

/// The result of the read of one ref file.
pub(super) enum RefRead {
    /// The file names the commit.
    Commit(Checksum),
    /// The key held no object at the read.
    Gone,
    /// The file breaks the rule of a ref file. The text states the rule,
    /// after the subject "the ref file".
    Malformed(String),
}

/// One ref key of a bucket repository.
pub(super) enum RefKey<'a> {
    /// `refs/heads/NAME`.
    Head(&'a str),
    /// `refs/mirrors/ID/NAME`.
    Mirror(&'a str, &'a str),
}

impl BucketRepo {
    /// Reads the `config` of the repository, or returns `None` if the key
    /// holds no object.
    ///
    /// The config must state the mode `archive-z2` or `archive`, and a
    /// `[core] collection-id` must pass the collection id rule and be at most
    /// 255 bytes. `[core] tombstone-commits` and `[core] indexed-deltas`, which
    /// the summary takes, and `[ex-ostrya] keep-detached-related`, which a
    /// push takes, must be booleans if they are set. `[archive] zlib-level`,
    /// which a push takes, must be an integer if it is set.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the config is larger than 1 MiB, is not
    ///   UTF-8, does not parse, or breaks a rule above.
    /// - [`Error::Remote`] for an error of the bucket client.
    #[cfg_attr(not(feature = "push"), allow(dead_code))]
    pub(crate) async fn read_config(&self) -> Result<Option<RepoConfig>> {
        let read = self.bucket.get("config", MAX_CONFIG_SIZE).await;
        self.check_config(read)
    }

    /// Reads the `config` of the repository as
    /// [`read_config`](BucketRepo::read_config) does, by the strict rule of
    /// an absent key of [`Bucket::get_strict`](crate::remote::s3::Bucket::get_strict).
    ///
    /// # Errors
    ///
    /// The errors of [`read_config`](BucketRepo::read_config). A 404 that is
    /// not an absent key gives [`Error::Remote`].
    pub(super) async fn read_config_strict(&self) -> Result<Option<RepoConfig>> {
        let read = self.bucket.get_strict("config", MAX_CONFIG_SIZE).await;
        self.check_config(read)
    }

    /// Returns the `config` of the read `read`, after the checks of
    /// [`read_config`](BucketRepo::read_config).
    fn check_config(
        &self,
        read: std::result::Result<Option<Object>, crate::remote::Error>,
    ) -> Result<Option<RepoConfig>> {
        let object = match read {
            Ok(Some(object)) => object,
            Ok(None) => return Ok(None),
            Err(crate::remote::Error::LimitExceeded(_)) => {
                return Err(
                    self.malformed(format!("its config is larger than {MAX_CONFIG_SIZE} bytes"))
                );
            }
            Err(e) => return Err(e.into()),
        };
        let text = String::from_utf8(object.bytes)
            .map_err(|_| self.malformed("its config is not UTF-8".to_owned()))?;
        let config = RepoConfig::parse(&text)
            .map_err(|e| self.malformed(format!("its config does not parse: {e}")))?;
        if config.mode() != RepoMode::Archive {
            return Err(self.malformed(format!(
                "its config states the mode '{}', and a bucket repository is in archive form",
                config.mode().as_mode_str()
            )));
        }
        if let Some(id) = config.collection_id()
            && !is_valid_collection_id(id)
        {
            return Err(self.malformed(format!(
                "its config states the collection id '{}', which the collection id rule refuses",
                id.escape_debug()
            )));
        }
        for checked in [
            config.tombstone_commits(),
            config.indexed_deltas(),
            config.keep_detached_related(),
        ] {
            checked.map_err(|e| {
                self.malformed(format!("its config has a key that is no boolean: {e}"))
            })?;
        }
        config.zlib_level().map_err(|e| {
            self.malformed(format!(
                "its config has a zlib-level that is no integer: {e}"
            ))
        })?;
        Ok(Some(config))
    }

    /// Reads the refs of the repository: one list of `refs/`, then a read of
    /// each ref file.
    ///
    /// Each key under `refs/` is `refs/heads/NAME` or `refs/mirrors/ID/NAME`.
    /// `NAME` passes the ref name rule, and `ID` passes the collection id
    /// rule and is at most 255 bytes. A ref file holds 64 lowercase hex
    /// digits and a newline. At most `max_outstanding` reads run at a time.
    ///
    /// The refs of the own collection id `own`, the collection id of the
    /// repository, are under `refs/heads/`. `own_mirrors` gives the rule of
    /// a key under `refs/mirrors/ID/` of `own`: [`OwnMirrors::Skip`] skips
    /// the key with no check, and [`OwnMirrors::Read`] checks and reads it
    /// as each other key.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a key under `refs/` that the call does
    ///   not skip breaks a rule above, if a ref file is malformed, or if a
    ///   listed ref file is gone at its read.
    /// - [`Error::Remote`] for an error of the bucket client.
    pub(crate) async fn read_refs(
        &self,
        own: Option<&str>,
        own_mirrors: OwnMirrors,
    ) -> Result<BucketRefs> {
        let skipped = match own_mirrors {
            OwnMirrors::Skip => own.map(|id| format!("refs/mirrors/{id}/")),
            OwnMirrors::Read => None,
        };
        let listing = self.bucket.list("refs/").await?;
        let mut keys = Vec::with_capacity(listing.objects.len());
        for listed in &listing.objects {
            let key = listed.key.as_str();
            if skipped
                .as_deref()
                .is_some_and(|prefix| key.starts_with(prefix))
            {
                continue;
            }
            match ref_key(key) {
                Some(_) => keys.push(((), key)),
                None => {
                    return Err(self.malformed(format!(
                        "it holds the key '{}' under refs/, which is no ref of refs/heads/ or of \
                         refs/mirrors/ID/",
                        key.escape_debug()
                    )));
                }
            }
        }
        let mut refs = BucketRefs::default();
        for ((), key, commit) in self.read_ref_files(keys).await? {
            match ref_key(key) {
                Some(RefKey::Head(name)) => {
                    refs.heads.insert(name.to_owned(), commit);
                }
                Some(RefKey::Mirror(id, name)) if Some(id) == own => {
                    refs.own_mirrors.insert(name.to_owned(), commit);
                }
                Some(RefKey::Mirror(id, name)) => {
                    refs.mirrors
                        .entry(id.to_owned())
                        .or_default()
                        .insert(name.to_owned(), commit);
                }
                None => unreachable!("each key passed the rule"),
            }
        }
        Ok(refs)
    }

    /// Reads the refs of each ref directory of `dirs`, `refs/heads/` or
    /// `refs/mirrors/ID/`, and returns one map for each directory, in the
    /// order of `dirs`. The call reads no key outside `dirs`.
    ///
    /// The call sends one list of each directory, at most `max_outstanding`
    /// lists at a time. Then it reads the ref files of all the directories,
    /// at most `max_outstanding` reads at a time in total.
    ///
    /// The part of each key after its directory passes the ref name rule. A
    /// ref file holds 64 lowercase hex digits and a newline.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a key under a directory is no ref name,
    ///   if a ref file is malformed, or if a listed ref file is gone at its
    ///   read.
    /// - [`Error::Remote`] for an error of the bucket client.
    #[cfg_attr(not(feature = "push"), allow(dead_code))]
    pub(crate) async fn read_ref_dirs(
        &self,
        dirs: &[String],
    ) -> Result<Vec<BTreeMap<String, Checksum>>> {
        let mut listings = Vec::with_capacity(dirs.len());
        let mut lists = Slots::new(self.max_outstanding);
        let mut pending = dirs.iter().enumerate();
        loop {
            while lists.has_room()
                && let Some((index, dir)) = pending.next()
            {
                let bucket = &self.bucket;
                lists.push(async move { (index, bucket.list(dir).await) });
            }
            let Some((index, list)) = lists.next_ready().await else {
                break;
            };
            listings.push((index, list?));
        }
        listings.sort_by_key(|(index, _)| *index);
        let mut keys = Vec::new();
        for (index, listing) in &listings {
            let dir = dirs[*index].as_str();
            for listed in &listing.objects {
                let key = listed.key.as_str();
                match key.strip_prefix(dir) {
                    Some(name) if is_ref_name(name) => keys.push((*index, key)),
                    _ => {
                        return Err(self.malformed(format!(
                            "it holds the key '{}' under {dir}, which is no ref of {dir}",
                            key.escape_debug()
                        )));
                    }
                }
            }
        }
        let mut refs = vec![BTreeMap::new(); dirs.len()];
        for (index, key, commit) in self.read_ref_files(keys).await? {
            refs[index].insert(key[dirs[index].len()..].to_owned(), commit);
        }
        Ok(refs)
    }

    /// Reads the ref file of each key of `keys`, at most `max_outstanding`
    /// reads at a time. Each item of `keys` is a tag and a key. The call
    /// returns the tag and the key of each item with its commit.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a ref file is malformed, or if a ref
    ///   file is gone at its read.
    /// - [`Error::Remote`] for an error of the bucket client.
    async fn read_ref_files<'k, T: Send + 'k>(
        &self,
        keys: Vec<(T, &'k str)>,
    ) -> Result<Vec<(T, &'k str, Checksum)>> {
        let mut out = Vec::with_capacity(keys.len());
        let mut reads = Slots::new(self.max_outstanding);
        let mut pending = keys.into_iter();
        loop {
            while reads.has_room()
                && let Some((tag, key)) = pending.next()
            {
                reads.push(async move { (tag, key, self.read_ref_file(key).await) });
            }
            let Some((tag, key, read)) = reads.next_ready().await else {
                break;
            };
            match read? {
                RefRead::Commit(commit) => out.push((tag, key, commit)),
                RefRead::Gone => {
                    return Err(self.malformed(format!(
                        "the ref file '{}' was in the listing and is gone",
                        key.escape_debug()
                    )));
                }
                RefRead::Malformed(why) => {
                    return Err(
                        self.malformed(format!("the ref file '{}' {why}", key.escape_debug()))
                    );
                }
            }
        }
        Ok(out)
    }

    /// Reads the ref file at `key`.
    ///
    /// # Errors
    ///
    /// [`Error::Remote`] for an error of the bucket client.
    async fn read_ref_file(&self, key: &str) -> Result<RefRead> {
        ref_read(self.bucket.get(key, REF_FILE_SIZE).await)
    }

    /// Reads the ref file at `key`, by the strict rule of an absent key of
    /// [`Bucket::get_strict`](crate::remote::s3::Bucket::get_strict).
    ///
    /// # Errors
    ///
    /// [`Error::Remote`] for an error of the bucket client, also for a 404
    /// that is not an absent key.
    pub(super) async fn read_ref_file_strict(&self, key: &str) -> Result<RefRead> {
        ref_read(self.bucket.get_strict(key, REF_FILE_SIZE).await)
    }

    /// Returns each commit that has a partial-commit marker: one list of
    /// `state/`.
    ///
    /// A marker is the key `state/<checksum>.commitpartial`, in lowercase
    /// hex. It marks a commit whose tree misses objects. Each other key under
    /// `state/` is ignored.
    ///
    /// # Errors
    ///
    /// [`Error::Remote`] for an error of the bucket client.
    pub(crate) async fn partial_commits(&self) -> Result<BTreeSet<Checksum>> {
        Ok(self
            .bucket
            .list("state/")
            .await?
            .objects
            .iter()
            .filter_map(|listed| marker_commit(&listed.key))
            .collect())
    }

    /// Returns `true` if the key `summary.sig` holds an object.
    ///
    /// The call is a check of
    /// [`Bucket::exists_strict`](crate::remote::s3::Bucket::exists_strict),
    /// by the strict rule of an absent key. It asks for the first byte of the
    /// key alone.
    ///
    /// # Errors
    ///
    /// [`Error::Remote`] for an error of the bucket client, also for a 404
    /// that is not an absent key.
    pub(super) async fn is_signed(&self) -> Result<bool> {
        Ok(self.bucket.exists_strict("summary.sig").await?)
    }

    /// Returns the error of a bucket repository whose content breaks a rule.
    /// `what` starts with the subject of the rule, for example "its config".
    pub(crate) fn malformed(&self, what: String) -> Error {
        Error::InvalidFormat(format!("the bucket repository {}: {what}", self.address()))
    }
}

/// Returns the ref that the key `key` names, or `None` for a key that is no
/// ref key.
pub(super) fn ref_key(key: &str) -> Option<RefKey<'_>> {
    if let Some(name) = key.strip_prefix("refs/heads/") {
        return is_ref_name(name).then_some(RefKey::Head(name));
    }
    let (id, name) = key.strip_prefix("refs/mirrors/")?.split_once('/')?;
    (is_valid_collection_id(id) && is_ref_name(name)).then_some(RefKey::Mirror(id, name))
}

/// Returns the key of the partial-commit marker of `commit`.
pub(crate) fn marker_key(commit: &Checksum) -> String {
    format!("state/{}.commitpartial", commit.to_hex())
}

/// Returns the commit of the partial-commit marker `key`, or `None` for a key
/// of another form.
fn marker_commit(key: &str) -> Option<Checksum> {
    let hex = key.strip_prefix("state/")?.strip_suffix(".commitpartial")?;
    if hex.len() != 64 || !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return None;
    }
    Checksum::from_hex(hex).ok()
}

/// Returns the result of the read `read` of a ref file.
fn ref_read(read: std::result::Result<Option<Object>, crate::remote::Error>) -> Result<RefRead> {
    let bytes = match read {
        Ok(Some(object)) => object.bytes,
        Ok(None) => return Ok(RefRead::Gone),
        Err(crate::remote::Error::LimitExceeded(_)) => {
            return Ok(RefRead::Malformed(format!(
                "is larger than {REF_FILE_SIZE} bytes"
            )));
        }
        Err(e) => return Err(e.into()),
    };
    Ok(match parse_ref_file(&bytes) {
        Some(commit) => RefRead::Commit(commit),
        None => {
            RefRead::Malformed("does not hold 64 lowercase hex digits and a newline".to_owned())
        }
    })
}

/// Returns the commit of the ref file `bytes`: 64 lowercase hex digits and a
/// newline.
fn parse_ref_file(bytes: &[u8]) -> Option<Checksum> {
    let hex = bytes.strip_suffix(b"\n")?;
    if hex.len() != 64 || !hex.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return None;
    }
    Checksum::from_hex(std::str::from_utf8(hex).ok()?).ok()
}

/// Returns the two ref inputs of the summary of `refs`: the refs of field 0,
/// and the refs of `ostree.summary.collection-map` by collection id.
///
/// Field 0 holds the refs of `refs/heads/`. The map holds each collection of
/// `refs/mirrors/` with a ref. Each list is sorted byte-wise by name. A
/// writer refuses a bucket repository with `refs/mirrors/` of its own
/// collection id, so the two inputs are the inputs of the root summary of a
/// local repository with the same refs and the same `[core] collection-id`.
#[allow(clippy::type_complexity)]
pub(crate) fn summary_refs(
    refs: &BucketRefs,
) -> (
    Vec<(String, Checksum)>,
    BTreeMap<String, Vec<(String, Checksum)>>,
) {
    let list = |dir: &BTreeMap<String, Checksum>| -> Vec<(String, Checksum)> {
        dir.iter()
            .map(|(name, commit)| (name.clone(), *commit))
            .collect()
    };
    let collections = refs
        .mirrors
        .iter()
        .filter(|(_, dir)| !dir.is_empty())
        .map(|(id, dir)| (id.clone(), list(dir)))
        .collect();
    (list(&refs.heads), collections)
}

/// Refuses a ref directory in which one name is a directory prefix of
/// another name, as `a` and `a/b` are.
///
/// One pass looks up, for each name, each part of the name before a `/` as
/// a name of the directory.
pub(crate) fn check_prefixes(dir: &BTreeMap<String, Checksum>) -> Result<()> {
    for name in dir.keys() {
        for (at, _) in name.match_indices('/') {
            let directory = &name[..at];
            if dir.contains_key(directory) {
                return Err(super::invalid(format!(
                    "the ref '{directory}' is a directory of the ref '{name}', and one directory \
                     of refs cannot hold both"
                )));
            }
        }
    }
    Ok(())
}

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

    fn csum(byte: u8) -> Checksum {
        Checksum::from_bytes([byte; 32])
    }

    fn dir(names: &[&str]) -> BTreeMap<String, Checksum> {
        names
            .iter()
            .map(|name| ((*name).to_owned(), csum(1)))
            .collect()
    }

    #[test]
    fn a_ref_file_is_64_lowercase_hex_digits_and_a_newline() {
        let hex = "ab".repeat(32);
        assert_eq!(
            parse_ref_file(format!("{hex}\n").as_bytes()),
            Some(Checksum::from_hex(&hex).unwrap())
        );
        for body in [
            hex.clone(),
            format!("{}\n", hex.to_uppercase()),
            format!("{}\n", &hex[..63]),
            format!("{hex}\n\n"),
            format!("{hex} \n"),
            String::new(),
        ] {
            assert_eq!(parse_ref_file(body.as_bytes()), None, "{body:?}");
        }
    }

    #[test]
    fn a_marker_key_names_one_commit_in_lowercase_hex() {
        let commit = Checksum::from_bytes([0xab; 32]);
        let key = marker_key(&commit);
        assert_eq!(key, format!("state/{}.commitpartial", "ab".repeat(32)));
        assert_eq!(marker_commit(&key), Some(commit));
        for key in [
            format!("state/{}.commitpartial", "AB".repeat(32)),
            format!("state/{}.commitpartial", "a".repeat(63)),
            format!("state/{}.commit", "ab".repeat(32)),
            format!("state/x/{}.commitpartial", "ab".repeat(32)),
            "state/other".to_owned(),
        ] {
            assert_eq!(marker_commit(&key), None, "{key}");
        }
    }

    #[test]
    fn a_ref_key_is_a_head_or_a_mirror_ref() {
        assert!(matches!(
            ref_key("refs/heads/a/b"),
            Some(RefKey::Head("a/b"))
        ));
        assert!(matches!(
            ref_key("refs/mirrors/org.example.Os/main"),
            Some(RefKey::Mirror("org.example.Os", "main"))
        ));
        for key in [
            "refs/remotes/origin/main",
            "refs/heads/-x",
            "refs/heads/",
            "refs/mirrors/nodot/main",
            "refs/mirrors/org.example.Os/",
            "refs/mirrors/org.example.Os",
            "refs/other",
        ] {
            assert!(ref_key(key).is_none(), "{key}");
        }
        let long = format!("refs/mirrors/org.{}/x", "a".repeat(252));
        assert!(ref_key(&long).is_none());
    }

    #[test]
    fn a_name_that_is_a_directory_of_another_is_refused() {
        check_prefixes(&dir(&["a", "a-b", "a.b", "ab", "b/c"])).unwrap();
        for names in [
            &["a", "a/b"][..],
            &["a", "a-b", "a.b", "a/b"],
            &["x", "x/y/z"],
            &["a/b", "a/b/c"],
        ] {
            match check_prefixes(&dir(names)) {
                Err(Error::Remote(crate::remote::Error::InvalidInput(message))) => {
                    assert!(message.contains("is a directory of the ref"), "{message}");
                }
                other => panic!("{names:?}: {other:?}"),
            }
        }
    }

    #[test]
    fn the_summary_refs_are_the_heads_and_a_map_of_the_mirrors() {
        let mut refs = BucketRefs::default();
        refs.heads.insert("main".into(), csum(1));
        refs.heads.insert("a".into(), csum(2));
        refs.mirrors.insert("org.example.B".into(), dir(&["main"]));
        refs.mirrors
            .insert("org.example.Empty".into(), BTreeMap::new());
        let (local, collections) = summary_refs(&refs);
        assert_eq!(
            local,
            [("a".to_owned(), csum(2)), ("main".to_owned(), csum(1))]
        );
        assert_eq!(collections.len(), 1);
        assert_eq!(collections["org.example.B"], [("main".to_owned(), csum(1))]);
    }
}