ostrya 0.2.8

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
//! Delta-accelerated pull: finding a static delta on a remote, fetching it, and
//! applying it into the pull's transaction.
//!
//! A remote that publishes static deltas can deliver a commit as one delta
//! instead of one request per object. What a pull asks for, in order: the delta
//! index for the target commit, the delta's `superblock`, then the objects the
//! delta hands over loose and its numbered part files. The commit object itself
//! rides in the superblock and is staged from there, so no `.commit` request
//! follows. A part the superblock carries inline, in its metadata dict, is
//! applied from there, and no request is made for it.
//!
//! Which delta. A pull looks for exactly one: `<from>-<to>` where `from` is the
//! commit the ref being pulled names in this repository, and the from-scratch
//! `<to>` where the ref names none. A from-to delta patches against the source
//! commit's objects, so the source commit has to be here complete for the delta
//! to apply; a ref whose commit is absent or partial is treated as naming none. A
//! repository that holds the ref's commit does not take a from-scratch delta,
//! which would re-deliver every object of the target including the ones it
//! already holds -- the objects it is missing are fetched loose instead. This is
//! what the tool was observed to do.
//!
//! Where the delta is advertised. With a summary present, the remote's
//! `delta-indexes/<to_b64[0:2]>/<to_b64[2:]>.index` is fetched first; a remote
//! serving no index falls back to the summary's own `ostree.static-deltas` map.
//! Both hold the same thing: a delta name mapped to the SHA-256 of that delta's
//! superblock. A delta the map does not name is not fetched, so a client holding
//! a commit the remote publishes no delta from fetches loose. With no summary at
//! all nothing is advertised and the delta's `superblock` is requested by name,
//! which is the one case a superblock arrives with no digest to check it against.
//!
//! What is checked. A superblock the remote advertised a digest for is hashed and
//! compared against it before it is parsed, so a delta swapped underneath a
//! signed summary fails the pull with [`Error::ChecksumMismatch`]. The parsed
//! superblock has to name the commit being pulled and the source commit the
//! delta's name claims. The delta's own signatures are then checked over the raw
//! superblock bytes, ahead of any part request, so a delta that fails
//! verification costs no part bytes; the policy is the pull's own, described in
//! [`verify`](super::verify). Each inline part is then checked against the size
//! and the checksum its meta-entry declares, also ahead of any part request.
//! Every object a part produces is written with its expected checksum asserted,
//! which is the read path's own rule. Each part is
//! taken off the connection under the size its meta-entry declares and hashed
//! against the checksum that entry names before it is decompressed, so what a
//! remote can drive onto the staging filesystem for one part is the size the
//! superblock states. A superblock the remote does not hold (a stale
//! advertisement) is a 404, which leaves the pull to fetch the objects loose.
//!
//! Concurrency. Two part fetches are in flight at once ([`PART_CAP`]), whatever
//! the pull's slot count is: a part is decompressed into a random-access blob to
//! be applied, so each one in flight costs an xz decoder, the verified body, and
//! the payload, each blob spilling to a temp file past its heap threshold. Parts
//! are applied as they
//! arrive rather than in part order, which the format allows: a part patches
//! against the source commit's objects, which are present before the delta is
//! applied, and never against another part's output.
//!
//! Completeness. The tool takes the delta plus the objects it hands over loose as
//! the whole of what a target commit needs. This pull queues the commit's tree
//! walk as well, once every part is applied, so an object no part delivered is
//! found and fetched loose. The walk reads what the delta staged and asks the
//! network for nothing when the delta was complete, which keeps a pull's
//! invariant that a published commit is whole.

use std::collections::HashMap;

use ostrya_core::{Checksum, ObjectName, ObjectType, RepoMode, Type, Value, from_bytes};

use crate::delta::{
    Blob, DeltaFallback, DeltaPart, DeltaSuperblock, MAX_SUPERBLOCK, apply_part, concat_to_blob,
    decode_inline_part, decode_part_stream, inline_part_at, verify_inline_part,
};
use crate::deltagen::{
    STATIC_DELTAS_KEY, SUPERBLOCK_FILE, delta_index_relative_path, delta_name, delta_relative_dir,
};
use crate::error::{Error, Result};
use crate::fetch::{FetchRequest, Fetched, Fetcher, Priority};
use crate::object::MAX_METADATA_SIZE;
use crate::pull::verify::Verification;
use crate::pull::{ModeChecks, PullCounters, PullFlags, PullOptions, refspec};
use crate::read::CommitState;
use crate::repo::Repo;
use crate::summary::{INDEXED_DELTAS_KEY, Summary};
use crate::transaction::Transaction;

use super::http::fetch_optional;

/// How many delta parts one pull fetches at once.
pub(crate) const PART_CAP: usize = 2;

/// A delta one pull applies for one target commit.
///
/// A job is built during discovery and lives until the pull returns, so a pull
/// retains one of these per target commit. It holds what application reads and
/// nothing else: the superblock's raw bytes, its signature array, and its
/// metadata dict are read at acquisition and dropped there, so what a job
/// retains on the heap is bounded by the target commit -- one meta-entry per
/// part, listing every object the delta produces -- plus 128 KiB at most of
/// inline part bodies, rather than by the superblock size a remote chooses.
/// The inline part bodies are kept in one [`Blob`]: on the heap where they
/// total 128 KiB or less, and otherwise one read-only map of an anonymous temp
/// file in the repository's `tmp/`. That file costs disk space and address
/// space up to the size of the superblock, and it is released when the pull
/// returns.
pub(crate) struct DeltaJob {
    /// The delta's request path prefix, `deltas/<fanout>/<rest>`.
    dir: String,
    /// The delta's name in hex, `<to>` or `<from>-<to>`, as the advertisement
    /// keys it and as a message names it.
    name: String,
    /// The normal-form bytes of the target commit, which the superblock carries
    /// and the pull stages from here.
    pub(crate) commit_bytes: Vec<u8>,
    /// The per-part meta-entries, in part order: what each part hashes to, the
    /// size it is fetched under, and the objects it produces.
    meta_entries: Vec<DeltaPart>,
    /// The objects the delta references and hands over loose.
    fallbacks: Vec<DeltaFallback>,
    /// One slot per part, in part order: the part where the superblock carries
    /// it inline, already checked against its meta-entry, and `None` where the
    /// part is fetched as a file.
    inline: Vec<Option<InlinePart>>,
    /// The bodies of the inline parts, one after the other in part order.
    inline_bodies: Blob,
}

/// A part the superblock carries inline, copied out of the metadata dict.
struct InlinePart {
    /// The compression byte.
    compression: u8,
    /// Where the body that follows the compression byte starts in
    /// [`DeltaJob::inline_bodies`].
    start: usize,
    /// The length of that body.
    len: usize,
}

impl DeltaJob {
    /// The objects the delta names but does not carry, which the pull fetches
    /// loose.
    pub(crate) fn fallbacks(&self) -> Vec<ObjectName> {
        self.fallbacks
            .iter()
            .map(|fallback| ObjectName::new(fallback.checksum, fallback.objtype))
            .collect()
    }

    /// How many parts the delta carries, inline or as files.
    pub(crate) fn parts(&self) -> usize {
        self.meta_entries.len()
    }

    /// How many parts the pull fetches as files, and the sizes the superblock
    /// declares for them.
    pub(crate) fn fetched_parts(&self) -> (u32, u64) {
        self.meta_entries
            .iter()
            .zip(&self.inline)
            .filter(|(_, inline)| inline.is_none())
            .fold((0, 0), |(parts, bytes), (entry, _)| {
                (parts + 1, bytes + entry.size)
            })
    }
}

/// Find the delta to pull each target commit with, keyed by that commit.
///
/// A commit with no entry is pulled object by object. Discovery is skipped for a
/// commit whose object this repository already holds, complete or partial, since
/// the walk then fetches only what is missing, for a
/// [`COMMIT_ONLY`](PullFlags::COMMIT_ONLY) pull, whose plan is the commit objects
/// alone, for a pull held to [`subpaths`](PullOptions::subpaths) into an
/// `archive` repository that does not
/// [`require_static_deltas`](PullOptions::require_static_deltas), which fetches
/// the subpaths loose, and when
/// [`disable_static_deltas`](PullOptions::disable_static_deltas) is set.
///
/// Two refs naming one commit share one delta, since the plan fetches that commit
/// once. The source commit is read from the ref this repository holds, so the
/// refs are tried in the order they were requested and the first that yields a
/// delta decides.
///
/// Each delta index request and each superblock request adds one to the
/// metadata fetched in `progress`, whatever the remote answers, which is what
/// the tool counts.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn discover(
    repo: &Repo,
    fetcher: &Fetcher,
    summary: Option<&Summary>,
    targets: &[(String, Checksum)],
    opts: &PullOptions,
    ref_prefix: Option<&str>,
    verification: &Verification,
    progress: &PullCounters,
) -> Result<HashMap<Checksum, DeltaJob>> {
    let mut jobs = HashMap::new();
    if opts.disable_static_deltas
        || opts.flags.contains(PullFlags::COMMIT_ONLY)
        || (!opts.subpaths.is_empty()
            && repo.mode() == RepoMode::Archive
            && !opts.require_static_deltas)
    {
        return Ok(jobs);
    }
    for (ref_name, to) in targets {
        if jobs.contains_key(to) || repo.has_object(ObjectType::Commit, to).await? {
            continue;
        }
        let from = source_commit(repo, ref_name, to, ref_prefix).await?;
        if let Some(job) = discover_one(
            repo,
            fetcher,
            summary,
            from,
            *to,
            opts,
            verification,
            progress,
        )
        .await?
        {
            jobs.insert(*to, job);
        }
    }
    Ok(jobs)
}

/// Whether this repository already holds a commit and everything it references.
async fn complete_here(repo: &Repo, commit: &Checksum) -> Result<bool> {
    Ok(repo.has_object(ObjectType::Commit, commit).await?
        && repo.commit_state(commit).await? == CommitState::Normal)
}

/// The commit a from-to delta would patch against: the one the ref being pulled
/// names in this repository, when this repository holds it complete.
///
/// A ref that names nothing, or names a commit whose objects are not all here,
/// yields `None`, and the pull looks for a from-scratch delta instead: a delta
/// patches against the source commit's objects, and the ones a partial commit is
/// missing are what a part would fail to read. A ref that already names the
/// target yields `None` as well, since a delta from a commit to itself carries
/// nothing.
async fn source_commit(
    repo: &Repo,
    ref_name: &str,
    to: &Checksum,
    ref_prefix: Option<&str>,
) -> Result<Option<Checksum>> {
    let Some(current) = repo.resolve_ref_tip(&refspec(ref_prefix, ref_name)).await? else {
        return Ok(None);
    };
    if current == *to || !complete_here(repo, &current).await? {
        return Ok(None);
    }
    Ok(Some(current))
}

/// What a remote states about the deltas it holds.
enum Advertisement {
    /// A map of delta name to superblock digest: the index file for the target
    /// commit, or the summary's own map.
    Map(Value),
    /// The remote serves no summary, so it advertises nothing and a delta is
    /// asked for by name.
    Unlisted,
    /// The remote serves a summary and names no delta in it.
    Nothing,
}

/// Find and read the delta from `from` to `to`, or `None` when the remote
/// publishes none.
#[allow(clippy::too_many_arguments)]
async fn discover_one(
    repo: &Repo,
    fetcher: &Fetcher,
    summary: Option<&Summary>,
    from: Option<Checksum>,
    to: Checksum,
    opts: &PullOptions,
    verification: &Verification,
    progress: &PullCounters,
) -> Result<Option<DeltaJob>> {
    let name = delta_name(from.as_ref(), &to);
    let advertised = match summary {
        None => Advertisement::Unlisted,
        Some(summary) => match advertised_map(fetcher, summary, &to, progress).await? {
            Some(map) => Advertisement::Map(map),
            None => Advertisement::Nothing,
        },
    };
    if opts.require_static_deltas && !matches!(advertised, Advertisement::Map(_)) {
        return Err(Error::Pull(format!(
            "a static delta was required to pull {to}, but the remote advertises \
             neither a delta index nor summary deltas"
        )));
    }

    let digest = match &advertised {
        // A map that does not name this delta ends the search: the remote
        // publishes deltas and none of them produces this commit from what is
        // here, so the objects are fetched loose.
        Advertisement::Map(map) => match map_digest(map, &name)? {
            Some(digest) => Some(digest),
            None => return Ok(None),
        },
        // Nothing states a digest, so the delta is asked for by name and its
        // superblock arrives unchecked against an advertisement. What it produces
        // is still checked object by object as the parts are applied.
        Advertisement::Unlisted => None,
        Advertisement::Nothing => return Ok(None),
    };

    let path = format!(
        "{}/{SUPERBLOCK_FILE}",
        delta_relative_dir(from.as_ref(), &to)
    );
    // A superblock the remote no longer holds is a stale advertisement, which
    // leaves the objects to be fetched loose.
    let fetched = fetch_optional(fetcher, &path, Priority::High, MAX_SUPERBLOCK).await?;
    progress.metadata_fetched();
    let Some(bytes) = fetched else {
        return Ok(None);
    };
    if let Some(expected) = digest {
        let actual = Checksum::sha256(&bytes);
        if actual != expected {
            return Err(Error::ChecksumMismatch { expected, actual });
        }
    }

    let superblock = DeltaSuperblock::parse(bytes)?;
    if superblock.to != to || superblock.from != from {
        return Err(Error::Pull(format!(
            "static delta {name}: its superblock produces {} from {}",
            superblock.to,
            match superblock.from {
                Some(from) => from.to_hex(),
                None => "scratch".to_owned(),
            }
        )));
    }
    // Destructured, so the compiler establishes that the raw bytes, the
    // signature array, and the metadata dict reach verification and the inline
    // parts and go no further: what the job carries is what application reads.
    let DeltaSuperblock {
        commit_bytes,
        meta_entries,
        fallbacks,
        signatures,
        superblock_bytes,
        metadata,
        inline_index,
        ..
    } = superblock;
    verify_fetched_delta(verification, &name, &superblock_bytes, signatures.as_ref()).await?;
    drop(superblock_bytes);
    let dir = delta_relative_dir(from.as_ref(), &to);
    let (inline, inline_bodies) =
        take_inline_parts(repo, &metadata, &inline_index, &dir, &meta_entries).await?;
    drop(metadata);
    Ok(Some(DeltaJob {
        dir,
        name,
        commit_bytes,
        meta_entries,
        fallbacks,
        inline,
        inline_bodies,
    }))
}

/// Check each part the superblock carries inline against its meta-entry, in
/// part order, and copy the bodies out of the metadata dict into one [`Blob`],
/// so the dict can be dropped. Where the bodies total more than the heap
/// threshold of 128 KiB, the blob is one anonymous temp file in the
/// repository's `tmp/`, mapped read-only, and the job keeps no copy of them on
/// the heap.
async fn take_inline_parts(
    repo: &Repo,
    metadata: &Value,
    index: &[Option<usize>],
    dir: &str,
    meta_entries: &[DeltaPart],
) -> Result<(Vec<Option<InlinePart>>, Blob)> {
    let mut inline = Vec::with_capacity(meta_entries.len());
    let mut bodies: Vec<&[u8]> = Vec::new();
    let mut start = 0usize;
    for (part, entry) in meta_entries.iter().enumerate() {
        let Some((compression, body)) = inline_part_at(metadata, index, part, || dir.to_owned())?
        else {
            inline.push(None);
            continue;
        };
        verify_inline_part(compression, body, entry)?;
        inline.push(Some(InlinePart {
            compression,
            start,
            len: body.len(),
        }));
        start += body.len();
        bodies.push(body);
    }
    if bodies.is_empty() {
        return Ok((inline, Blob::Ram(Vec::new())));
    }
    let tmp = repo.open_tmp_dir().await?;
    Ok((inline, concat_to_blob(&bodies, &tmp).await?))
}

/// Verify a fetched delta's detached signatures over the raw superblock bytes.
///
/// The pull's own policy decides: the sign-api engines it checks a commit with
/// check the delta too, since a delta carries sign-api signatures alone. A delta
/// carrying none of those signatures is accepted, and the commit it delivers is
/// held to the commit policy like any other. The call sits here so the
/// superblock's raw bytes and its signature array are read where they are
/// available and dropped afterwards, rather than held for the length of the
/// pull.
async fn verify_fetched_delta(
    verification: &Verification,
    name: &str,
    superblock_bytes: &[u8],
    signatures: Option<&Value>,
) -> Result<()> {
    verification
        .check_delta(name, superblock_bytes, signatures)
        .await
}

/// The delta map the remote advertises for `to`: the index file when it serves
/// one, the summary's own `ostree.static-deltas` map otherwise, and `None` when
/// it advertises neither.
///
/// The index is asked for first whenever the summary states `indexed-deltas`,
/// which is the default a repository that says nothing carries. A remote that
/// holds deltas but has never been reindexed answers 404 there and is read
/// through the summary map instead.
async fn advertised_map(
    fetcher: &Fetcher,
    summary: &Summary,
    to: &Checksum,
    progress: &PullCounters,
) -> Result<Option<Value>> {
    if indexed_deltas(summary) {
        let path = delta_index_relative_path(to);
        let fetched = fetch_optional(fetcher, &path, Priority::High, MAX_METADATA_SIZE).await?;
        progress.metadata_fetched();
        if let Some(bytes) = fetched {
            let ty = Type::parse("a{sv}").map_err(ostrya_core::Error::from)?;
            let dict = from_bytes(&ty, &bytes).map_err(ostrya_core::Error::from)?;
            let map = dict
                .dict_get(STATIC_DELTAS_KEY)
                .and_then(Value::as_variant)
                .map(|(_, map)| map.clone())
                .ok_or_else(|| {
                    Error::InvalidFormat(format!(
                        "the remote's delta index for {to} holds no {STATIC_DELTAS_KEY} map"
                    ))
                })?;
            return Ok(Some(map));
        }
    }
    Ok(summary.metadata_value(STATIC_DELTAS_KEY).cloned())
}

/// Whether the summary states that the remote indexes its deltas. A summary that
/// does not carry the key is read as indexing them, which is the repository
/// default.
fn indexed_deltas(summary: &Summary) -> bool {
    summary
        .metadata_value(INDEXED_DELTAS_KEY)
        .and_then(Value::as_bool)
        .unwrap_or(true)
}

/// The superblock digest a delta map holds for `name`.
fn map_digest(map: &Value, name: &str) -> Result<Option<Checksum>> {
    let Some(entry) = map.dict_get(name) else {
        return Ok(None);
    };
    let bytes = entry
        .as_variant()
        .map(|(_, value)| value)
        .and_then(Value::as_bytes)
        .ok_or_else(|| {
            Error::InvalidFormat(format!(
                "the remote advertises static delta {name} with no superblock digest"
            ))
        })?;
    Ok(Some(Checksum::from_ay(bytes)?))
}

/// Fetch one part of a delta and apply it into the pull's transaction.
///
/// A part the superblock carries inline was checked at discovery, so it is
/// decompressed and applied with no request.
///
/// The part streams off the connection under the size the superblock declares for
/// it and is hashed against the superblock's checksum for it; the verified body
/// then decompresses into the random-access blob the operations read, which is on
/// the heap while it is small and a mapped temp file when it is not. A remote that
/// answers a part request with more than the part is, or with other bytes
/// altogether, therefore writes at most the declared size before the refusal.
/// Applying the blob produces the part's objects, each written under the checksum
/// the superblock names, so a part that produces something else fails there.
///
/// `checks` are the pull's mode checks, which every content object a part
/// produces is held to exactly as a loose fetch of that object would be. A
/// part fetched as a file adds one part and its declared size to `progress`
/// once its body has passed the checksum.
pub(crate) async fn fetch_part(
    txn: &Transaction,
    fetcher: &Fetcher,
    job: &DeltaJob,
    index: usize,
    checks: ModeChecks,
    progress: &PullCounters,
) -> Result<()> {
    let entry = job.meta_entries.get(index).ok_or_else(|| {
        Error::InvalidFormat(format!(
            "static delta {}: no part {index} in its superblock",
            job.name
        ))
    })?;
    if let Some(Some(part)) = job.inline.get(index) {
        let staging = txn.staging_fd().try_clone_to_owned()?;
        let body = &job.inline_bodies.as_slice()[part.start..part.start + part.len];
        let payload = decode_inline_part(part.compression, body, &staging).await?;
        return apply_part(txn, payload.as_slice(), &entry.objects, &staging, checks).await;
    }
    let path = format!("{}/{index}", job.dir);
    // The superblock states the part file's size, so the fetcher refuses a
    // `Content-Length` above it before the body arrives and stops a body that
    // passes it as the bytes land.
    // A body that fails in transit is fetched again from the start, into a new
    // blob, while the fetcher's retry count has a repeat left.
    let mut refetch = fetcher.refetching(FetchRequest {
        priority: Priority::High,
        max_size: Some(entry.size),
        ..FetchRequest::path(&path)
    });
    let staging = txn.staging_fd().try_clone_to_owned()?;
    let blob = loop {
        let body = match refetch.fetch().await? {
            Fetched::Body(body) => body,
            Fetched::NotModified => {
                return Err(Error::Fetch(format!(
                    "{path}: the remote answered 304 to an unconditional request"
                )));
            }
        };
        match decode_part_stream(body, entry, &staging).await {
            Ok(blob) => break blob,
            Err(e) => refetch.retry(e).await?,
        }
    };
    progress.part_fetched(entry.size);
    apply_part(txn, blob.as_slice(), &entry.objects, &staging, checks).await
}

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

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

    /// The digest lookup reads the `ay` behind the variant, reports an absent
    /// delta as absent, and refuses an entry holding something else.
    #[test]
    fn map_digest_reads_the_advertised_ay() {
        let digest = checksum(0x33);
        let ay = Type::parse("ay").unwrap();
        let mut map = Value::Array(Vec::new());
        crate::commit::append_dict_entry(
            &mut map,
            "delta-name",
            Value::variant(ay, Value::Bytes(digest.as_bytes().to_vec())),
        )
        .unwrap();
        crate::commit::append_dict_entry(
            &mut map,
            "not-a-digest",
            Value::variant(Type::parse("s").unwrap(), Value::Str("nope".to_owned())),
        )
        .unwrap();

        assert_eq!(map_digest(&map, "delta-name").unwrap(), Some(digest));
        assert_eq!(map_digest(&map, "absent").unwrap(), None);
        assert!(matches!(
            map_digest(&map, "not-a-digest"),
            Err(Error::InvalidFormat(_))
        ));
    }
}