bunsen 0.40.0

bunsen is a batteries included common library for burn
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
//! Fetch: a URL streamed into the cache, hashed as it lands.

use std::{
    fmt,
    path::Path,
    sync::Arc,
    time::Duration,
};

use super::{
    TransferObserver,
    files::io_at,
};
use crate::errors::{
    BunsenError,
    BunsenErrorKind,
    BunsenResult,
    DigestMismatch,
    DigestOrigin,
    LookupError,
    LookupProblem,
};

/// Why a fetch from a URL failed: the cause of the errors [`fetch_file`]
/// returns for the network side of a transfer.
///
/// A generic consumer reads only the error's kind. A handler with its own
/// recovery, such as the mirror loop of
/// [`BunsenDiskCache::fetch_from_urls`](super::BunsenDiskCache::fetch_from_urls),
/// reads this cause with [`BunsenError::find`] to tell a mirror that is down
/// from one that served the wrong bytes.
///
/// The kind comes from the variant, through `From`:
///
/// - [`Status`](Self::Status) 401, 403, 404 and 410 are a
///   [`Lookup`](BunsenErrorKind::Lookup) whose [`LookupError`] (`Unauthorized`,
///   `Denied`, `Missing`) wraps this failure; `find::<FetchFailure>()` still
///   reaches it.
/// - [`Status`](Self::Status) 408, 429 and 5xx, [`Transport`](Self::Transport)
///   and [`ShortTransfer`](Self::ShortTransfer) are
///   [`Unavailable`](BunsenErrorKind::Unavailable): a retry may succeed.
/// - Any other status, and [`Digest`](Self::Digest), are
///   [`InvalidResource`](BunsenErrorKind::InvalidResource).
///
/// A failure of the local disk under a transfer (the `.partial`, its
/// directory, the rename) is not a fetch failure: it is sorted by its
/// `io::Error`, with the local path, through [`sys_at`](crate::errors::sys_at).
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum FetchFailure {
    /// The server answered with an error status.
    Status {
        /// The URL requested.
        url: String,
        /// The HTTP status.
        status: u16,
        /// How long the server asked the client to wait before retrying
        /// (`Retry-After`, in seconds), when it said.
        retry_after: Option<Duration>,
    },

    /// No usable response, or the body stream broke: a refused or dropped
    /// connection, a DNS or TLS failure, a timeout.
    Transport {
        /// The URL requested.
        url: String,
        /// The transport's error.
        source: Arc<ureq::Error>,
    },

    /// The body ended short of its `Content-Length`.
    ShortTransfer {
        /// The URL requested.
        url: String,
        /// Bytes received.
        received: u64,
        /// Bytes the server declared.
        expected: u64,
    },

    /// The bytes do not match the pinned digest; its origin is a
    /// [`DigestOrigin::Download`] naming the URL.
    Digest(DigestMismatch),
}

impl FetchFailure {
    /// The URL the failed fetch requested.
    pub fn url(&self) -> &str {
        match self {
            Self::Status { url, .. }
            | Self::Transport { url, .. }
            | Self::ShortTransfer { url, .. } => url,
            Self::Digest(mismatch) => match &mismatch.origin {
                DigestOrigin::Download { url } => url,
                DigestOrigin::AtRest | DigestOrigin::Bundled => &mismatch.subject,
            },
        }
    }
}

impl fmt::Display for FetchFailure {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        match self {
            Self::Status {
                url,
                status,
                retry_after,
            } => {
                write!(f, "{url}: HTTP status {status}")?;
                if let Some(after) = retry_after {
                    write!(f, " (retry after {}s)", after.as_secs())?;
                }
                Ok(())
            }
            Self::Transport { url, source } => write!(f, "{url}: {source}"),
            Self::ShortTransfer {
                url,
                received,
                expected,
            } => write!(f, "{url}: short transfer, {received} of {expected} bytes"),
            Self::Digest(mismatch) => write!(f, "{mismatch}"),
        }
    }
}

impl core::error::Error for FetchFailure {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Transport { source, .. } => Some(source.as_ref()),
            Self::Digest(mismatch) => Some(mismatch),
            Self::Status { .. } | Self::ShortTransfer { .. } => None,
        }
    }
}

impl From<FetchFailure> for BunsenError {
    #[track_caller]
    fn from(failure: FetchFailure) -> Self {
        let (kind, lookup) = match &failure {
            FetchFailure::Status { status, .. } => match status {
                401 => (BunsenErrorKind::Lookup, Some(LookupProblem::Unauthorized)),
                403 => (BunsenErrorKind::Lookup, Some(LookupProblem::Denied)),
                404 | 410 => (BunsenErrorKind::Lookup, Some(LookupProblem::Missing)),
                408 | 429 | 500..=599 => (BunsenErrorKind::Unavailable, None),
                _ => (BunsenErrorKind::InvalidResource, None),
            },
            FetchFailure::Transport { .. } | FetchFailure::ShortTransfer { .. } => {
                (BunsenErrorKind::Unavailable, None)
            }
            FetchFailure::Digest(_) => (BunsenErrorKind::InvalidResource, None),
        };
        match lookup {
            Some(problem) => {
                let url = failure.url().to_string();
                BunsenError::lookup(LookupError::url(url, problem).with_source(failure))
            }
            None => BunsenError::from_cause(kind, failure),
        }
    }
}

/// Streams `url` to `dest`, checked against `sha256` when one is given,
/// reporting to `observers`.
///
/// The bytes are hashed as they land, in `<dest>.partial`
/// ([`partial_path`](super::partial_path)), and renamed into place only once
/// they check out. A pinned file (`Some`) must match its digest; every file
/// must match the `Content-Length` when the server sent one. Nothing is left at
/// `dest` or beside it when either check fails, so an interrupted or corrupt
/// transfer never leaves a trusted-looking file at `dest`.
///
/// The transfer is reported to every observer: `begin` once the response
/// headers are in (which is when the length is known), `position` as bytes
/// land, and `finish` with the outcome. A request that fails before a
/// response body, unanswered or with an error status, is an error with no
/// transfer reported.
///
/// This is the one place bunsen reaches the network at run time; it is
/// behind the `fetch` feature. Most callers reach it through
/// [`BunsenDiskCache`](super::BunsenDiskCache), which brings its own
/// observers.
///
/// # Errors
/// - A failure of the network side has a [`FetchFailure`] cause, which picks
///   the kind: [`Lookup`](BunsenErrorKind::Lookup) for an HTTP 401, 403, 404 or
///   410; [`Unavailable`](BunsenErrorKind::Unavailable) for a transport
///   failure, a short transfer, or an HTTP 408, 429 or 5xx;
///   [`InvalidResource`](BunsenErrorKind::InvalidResource) for a digest
///   mismatch ([`FetchFailure::Digest`]; nothing is left at `dest`) or any
///   other status.
/// - A failure of the local disk is sorted by its `io::Error` and names the
///   local path (see [`sys_at`](crate::errors::sys_at)): usually
///   [`Sys`](BunsenErrorKind::Sys).
/// - [`Illegal`](BunsenErrorKind::Illegal) if `dest` is not a file path, or
///   `url` is not a URL.
pub fn fetch_file(
    url: &str,
    dest: &Path,
    sha256: Option<&str>,
    observers: &[Arc<dyn TransferObserver>],
) -> BunsenResult<()> {
    bunsen_fetch::fetch_file(url, dest, sha256, observers).map_err(fetch_error)
}

/// [`fetch_file`] with a required digest.
///
/// # Errors
/// As [`fetch_file`].
pub fn fetch_verified(
    url: &str,
    dest: &Path,
    sha256: &str,
    observers: &[Arc<dyn TransferObserver>],
) -> BunsenResult<()> {
    fetch_file(url, dest, Some(sha256), observers)
}

/// The first `len` bytes of `url`, or all of it when it is shorter, by a
/// range request: a file's header, read before the file is fetched. Nothing
/// is written, and no observer is told.
///
/// # Errors
/// As [`fetch_file`], for the network side and a bad URL.
pub fn fetch_prefix(
    url: &str,
    len: u64,
) -> BunsenResult<Vec<u8>> {
    bunsen_fetch::fetch_prefix(url, len).map_err(fetch_error)
}

/// A `bunsen_fetch` failure, sorted into bunsen's kinds: the network side
/// through [`FetchFailure`], the local disk through
/// [`sys_at`](crate::errors::sys_at).
fn fetch_error(e: bunsen_fetch::FetchError) -> BunsenError {
    use bunsen_fetch::{
        FetchError,
        FetchFailure as Leaf,
    };
    match e {
        FetchError::Failure(Leaf::Status {
            url,
            status,
            retry_after,
        }) => FetchFailure::Status {
            url,
            status,
            retry_after,
        }
        .into(),
        FetchError::Failure(Leaf::Transport { url, source }) => {
            FetchFailure::Transport { url, source }.into()
        }
        FetchError::Failure(Leaf::ShortTransfer {
            url,
            received,
            expected,
        }) => FetchFailure::ShortTransfer {
            url,
            received,
            expected,
        }
        .into(),
        FetchError::Failure(Leaf::Digest {
            url,
            dest,
            expected,
            found,
        }) => FetchFailure::Digest(DigestMismatch::new(
            dest.display().to_string(),
            DigestOrigin::Download { url },
            expected,
            found,
        ))
        .into(),
        FetchError::Io(io) => io_at(io),
        FetchError::NotAFilePath(dest) => {
            BunsenError::illegal(format!("{}: not a file path", dest.display()))
        }
        FetchError::BadUrl { url, source } => {
            BunsenError::illegal(format!("{url}: not a URL")).with_cause(source)
        }
        other => BunsenError::invalid_resource(other.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::Path,
    };

    use super::*;
    use crate::{
        data::cache::{
            partial_path,
            testing::{
                ABC_SHA256,
                CacheProgressEvent,
                RecordingObserver,
                refused_url,
                serve_once,
                serve_once_declaring,
                serve_ranges,
                serve_status,
            },
        },
        errors::testing::{
            ErrorMatcher,
            predicate,
        },
    };

    fn observers(observer: &Arc<RecordingObserver>) -> Vec<Arc<dyn TransferObserver>> {
        vec![observer.clone()]
    }

    /// Each status picks its kind; a lookup status keeps the failure under
    /// its `LookupError`, where `find` still reaches it.
    #[test]
    fn test_fetch_failure_kinds() {
        use BunsenErrorKind::*;
        let status = |status: u16| {
            BunsenError::from(FetchFailure::Status {
                url: "https://h.example/f".to_string(),
                status,
                retry_after: None,
            })
        };
        for (code, kind) in [
            (401, Lookup),
            (403, Lookup),
            (404, Lookup),
            (410, Lookup),
            (408, Unavailable),
            (429, Unavailable),
            (500, Unavailable),
            (503, Unavailable),
            (400, InvalidResource),
            (418, InvalidResource),
        ] {
            assert_eq!(status(code).kind(), kind, "{code}");
        }
        for (code, problem) in [
            (401, LookupProblem::Unauthorized),
            (403, LookupProblem::Denied),
            (410, LookupProblem::Missing),
        ] {
            ErrorMatcher::kind(Lookup)
                .cause(predicate("the problem", move |l: &LookupError| {
                    l.problem == problem
                }))
                .has_cause::<FetchFailure>()
                .assert(&status(code));
        }

        let short = BunsenError::from(FetchFailure::ShortTransfer {
            url: "u".to_string(),
            received: 3,
            expected: 10,
        });
        assert_eq!(short.kind(), Unavailable);
        assert_eq!(short.to_string(), "u: short transfer, 3 of 10 bytes");

        let digest = BunsenError::from(FetchFailure::Digest(DigestMismatch::new(
            "f",
            DigestOrigin::Download {
                url: "u".to_string(),
            },
            "aa",
            "bb",
        )));
        assert_eq!(digest.kind(), InvalidResource);
        assert_eq!(digest.find::<FetchFailure>().unwrap().url(), "u");
    }

    /// The bytes land at `dest`, the `.partial` is gone, and the observer saw
    /// the whole transfer: the URL, the destination and the length in
    /// `begin`, the count as it landed, `Complete` at the end.
    #[test]
    fn test_fetch_verified_streams_hashes_and_reports() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("weights").join("abc.bin");
        let url = serve_once("abc.bin", b"abc");
        let observer = Arc::new(RecordingObserver::default());

        fetch_verified(&url, &dest, ABC_SHA256, &observers(&observer)).unwrap();

        assert_eq!(fs::read(&dest).unwrap(), b"abc");
        assert!(!partial_path(&dest).exists());
        let events = observer.events();
        assert_eq!(
            events.first(),
            Some(&CacheProgressEvent::Begin {
                source: url.clone(),
                dest: dest.clone(),
                total: Some(3),
            })
        );
        assert!(events.contains(&CacheProgressEvent::Position(3)));
        assert_eq!(events.last(), Some(&CacheProgressEvent::Finish(Ok(()))));
    }

    /// A digest mismatch is `InvalidResource` with a download-origin digest
    /// cause, leaves nothing at `dest` or beside it, and the observer sees the
    /// failure with the reason.
    #[test]
    fn test_fetch_verified_rejects_a_mismatch_and_leaves_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("abc.bin");
        let url = serve_once("abc.bin", b"abd");
        let observer = Arc::new(RecordingObserver::default());

        let result = fetch_verified(&url, &dest, ABC_SHA256, &observers(&observer));

        let origin = DigestOrigin::Download { url: url.clone() };
        ErrorMatcher::kind(BunsenErrorKind::InvalidResource)
            .cause(predicate(
                "a digest failure from the URL",
                move |f: &FetchFailure| matches!(f, FetchFailure::Digest(m) if m.origin == origin),
            ))
            .assert_err(&result);
        assert!(!dest.exists());
        assert!(!partial_path(&dest).exists());
        match observer.events().last() {
            Some(CacheProgressEvent::Finish(Err(message))) => {
                assert!(message.contains("sha256 is"), "{message}");
                assert!(message.contains(ABC_SHA256), "{message}");
            }
            other => panic!("expected a failed finish, got {other:?}"),
        }
    }

    /// No response at all is `Unavailable`, a transport failure, and no
    /// transfer is reported: there was nothing to begin.
    #[test]
    fn test_fetch_verified_without_a_response_reports_no_transfer() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("gone.bin");
        let url = refused_url("gone.bin");
        let observer = Arc::new(RecordingObserver::default());

        let result = fetch_verified(&url, &dest, ABC_SHA256, &observers(&observer));

        ErrorMatcher::kind(BunsenErrorKind::Unavailable)
            .cause(predicate("a transport failure", |f: &FetchFailure| {
                matches!(f, FetchFailure::Transport { .. })
            }))
            .assert_err(&result);
        assert!(observer.events().is_empty());
        assert!(!dest.exists());
    }

    #[test]
    fn test_fetch_verified_rejects_a_non_file_dest() {
        let observer = Arc::new(RecordingObserver::default());
        let result = fetch_verified(
            "http://127.0.0.1:1/never",
            Path::new("/"),
            ABC_SHA256,
            &observers(&observer),
        );
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("not a file path")
            .assert_err(&result);
        assert!(observer.events().is_empty());
    }

    /// An unpinned file lands on the strength of its length alone, and the
    /// observer sees the same transfer a pinned one gets.
    #[test]
    fn test_fetch_file_unpinned_lands_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("abc.bin");
        let url = serve_once("abc.bin", b"abc");
        let observer = Arc::new(RecordingObserver::default());

        fetch_file(&url, &dest, None, &observers(&observer)).unwrap();

        assert_eq!(fs::read(&dest).unwrap(), b"abc");
        assert!(!partial_path(&dest).exists());
        assert_eq!(
            observer.events().last(),
            Some(&CacheProgressEvent::Finish(Ok(())))
        );
    }

    /// A 404 is a `Lookup` of the URL, with the status underneath, and the
    /// slot the file would have landed in is not created for it.
    #[test]
    fn test_fetch_file_names_the_url_on_an_error_status() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("slot").join("missing.bin");
        let url = serve_status("missing.bin", 404);

        let result = fetch_file(&url, &dest, None, &[]);

        let key = url.clone();
        ErrorMatcher::kind(BunsenErrorKind::Lookup)
            .message_eq(&format!("{url}: not found"))
            .cause(predicate("a missing URL", move |l: &LookupError| {
                l.problem == LookupProblem::Missing && l.key == key
            }))
            .cause(predicate("status 404", |f: &FetchFailure| {
                matches!(f, FetchFailure::Status { status: 404, .. })
            }))
            .assert_err(&result);
        assert!(!dest.parent().unwrap().exists(), "no empty slot is left");
    }

    /// A transfer cut off short of its `Content-Length` is `Unavailable`,
    /// leaves nothing behind, and the observer sees it fail.
    #[test]
    fn test_fetch_file_rejects_a_short_transfer() {
        let dir = tempfile::tempdir().unwrap();
        let dest = dir.path().join("abc.bin");
        let url = serve_once_declaring("abc.bin", b"abc", 10);
        let observer = Arc::new(RecordingObserver::default());

        let result = fetch_file(&url, &dest, None, &observers(&observer));

        ErrorMatcher::kind(BunsenErrorKind::Unavailable)
            .has_cause::<FetchFailure>()
            .assert_err(&result);
        assert!(!dest.exists());
        assert!(!partial_path(&dest).exists());
        assert!(matches!(
            observer.events().last(),
            Some(CacheProgressEvent::Finish(Err(_)))
        ));
    }

    /// A prefix is the file's first bytes; a missing file is a `Lookup`.
    #[test]
    fn test_fetch_prefix() {
        let url = serve_ranges("f.bin", b"abcdef", 1);
        assert_eq!(fetch_prefix(&url, 4).unwrap(), b"abcd");
        ErrorMatcher::kind(BunsenErrorKind::Lookup)
            .assert_err(&fetch_prefix(&serve_status("f.bin", 404), 4));
    }
}