http-ferry 0.2.0

Resumable, checksum-verified streaming byte transfer from HTTP sources to pluggable sinks
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
#![doc = include_str!("../README.md")]

use std::fmt;
use std::fmt::Write as _;
use std::future::Future;
use std::path::PathBuf;
use std::pin::pin;
use std::time::{Duration, Instant};

use futures_core::Stream;
use futures_util::TryStreamExt;
use md5::Md5;
use sha1::{Digest, Sha1};
use url::Url;

mod error;
mod http;
pub mod local;
mod range;
#[cfg(feature = "s3")]
pub mod s3;

pub use error::Error;
use http::is_retryable;
pub use http::{Downloader, DownloaderBuilder};

const PROGRESS_INTERVAL: Duration = Duration::from_millis(500);

/// Expected integrity hash supplied by the caller for a transfer. The engine
/// hashes the byte stream with the matching algorithm and verifies the result;
/// sinks use it for skip-on-match decisions.
#[derive(Debug, Clone)]
pub enum Checksum {
    Sha1(String),
    Md5(String),
}

impl Checksum {
    /// Lowercase hex digest this checksum carries.
    pub fn hex(&self) -> &str {
        match self {
            Checksum::Sha1(h) | Checksum::Md5(h) => h,
        }
    }

    /// Stable short name for the algorithm, used as an object-metadata key.
    pub fn algorithm(&self) -> &'static str {
        match self {
            Checksum::Sha1(_) => "sha1",
            Checksum::Md5(_) => "md5",
        }
    }

    /// A checksum of the same algorithm carrying `value`. Lets a sink rebuild
    /// the expected variant from a stored metadata string.
    pub fn with_value(&self, value: String) -> Checksum {
        match self {
            Checksum::Sha1(_) => Checksum::Sha1(value),
            Checksum::Md5(_) => Checksum::Md5(value),
        }
    }
}

/// Streaming hasher selected from the caller's expected [`Checksum`]. `None`
/// means no checksum was supplied: the engine still counts bytes but reports
/// `verified: false`.
pub enum Hasher {
    None,
    Sha1(Sha1),
    Md5(Md5),
}

impl Hasher {
    pub fn for_checksum(checksum: Option<&Checksum>) -> Self {
        match checksum {
            Some(Checksum::Sha1(_)) => Hasher::Sha1(Sha1::new()),
            Some(Checksum::Md5(_)) => Hasher::Md5(Md5::new()),
            None => Hasher::None,
        }
    }

    pub fn update(&mut self, bytes: &[u8]) {
        match self {
            Hasher::Sha1(h) => h.update(bytes),
            Hasher::Md5(h) => h.update(bytes),
            Hasher::None => {}
        }
    }

    pub fn finalize_hex(self) -> Option<String> {
        match self {
            Hasher::Sha1(h) => Some(to_hex(&h.finalize())),
            Hasher::Md5(h) => Some(to_hex(&h.finalize())),
            Hasher::None => None,
        }
    }
}

fn to_hex(bytes: &[u8]) -> String {
    let mut hex = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        write!(&mut hex, "{b:02x}").expect("writing to String cannot fail");
    }
    hex
}

/// Describes a caller's work item to the engine: its destination `name`, byte
/// `size`, and optional `checksum`. The item value itself is cloned into
/// `Progress` events and handed back in terminal [`Outcome`]s. `name` is also
/// the item's label in [`Outcome`]'s `Display`.
pub trait Source: Clone + Send + 'static {
    fn name(&self) -> &str;
    fn size(&self) -> u64;
    fn checksum(&self) -> Option<Checksum> {
        None
    }
}

/// A simple URL-bearing work item for callers that already know where each file
/// lives. Use with [`drive_downloads`] when no per-item resolver is needed.
#[derive(Debug, Clone)]
pub struct Download {
    pub url: Url,
    pub size: u64,
    pub checksum: Option<Checksum>,
    pub name: String,
}

impl Source for Download {
    fn name(&self) -> &str {
        &self.name
    }

    fn size(&self) -> u64 {
        self.size
    }

    fn checksum(&self) -> Option<Checksum> {
        self.checksum.clone()
    }
}

/// Borrowed view of a [`Source`] item handed to sinks at prepare time. The
/// source URL is resolved by the engine and the caller's item is its own
/// concern, so neither appears here — sinks are domain-agnostic.
#[derive(Clone, Copy)]
pub struct Target<'a> {
    pub name: &'a str,
    pub size: u64,
    pub checksum: Option<&'a Checksum>,
}

pub trait Sink: Send {
    type Location: Send + 'static;

    fn prepare(
        &mut self,
        target: Target<'_>,
    ) -> impl Future<Output = Result<Prepared<Self::Location>, Error>> + Send;

    fn write_chunk(&mut self, chunk: &[u8]) -> impl Future<Output = Result<(), Error>> + Send;

    fn restart(&mut self) -> impl Future<Output = Result<(), Error>> + Send;

    fn finalize(self) -> impl Future<Output = Result<Self::Location, Error>> + Send;
}

/// Builds a per-item `Sink`. One factory drives a whole stream of items
/// (singular call sites pass a one-element stream).
pub trait SinkFactory: Send {
    type Sink: Sink<Location = Self::Location> + 'static;
    type Location: DownloadLocation;

    fn make(
        &mut self,
        target: Target<'_>,
    ) -> impl Future<Output = Result<Self::Sink, Error>> + Send;
}

/// Renders a transfer destination for log lines.
///
/// Implemented by location types used with [`Outcome`], such as local paths
/// and S3 object locations.
pub trait DownloadLocation: Send + 'static {
    fn fmt_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
}

impl DownloadLocation for PathBuf {
    fn fmt_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.display())
    }
}

impl DownloadLocation for String {
    fn fmt_location(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self)
    }
}

/// Per-item outcome of a transfer stream, generic over the caller's item type
/// `M`. `Failed` carries per-item errors so a single bad item in a batch
/// doesn't tear down the whole stream. `StreamFailed` carries errors that
/// happen before an item is available, such as a failed listing request or
/// destination preflight.
#[derive(Debug)]
pub enum Outcome<M, L = PathBuf> {
    Downloaded {
        file: M,
        location: L,
        verified: bool,
    },
    Failed {
        file: M,
        error: Error,
    },
    Progress {
        file: M,
        received: u64,
        total: u64,
    },
    Skipped {
        file: M,
        location: L,
    },
    StreamFailed {
        error: Error,
    },
}

impl<M: Source, L: DownloadLocation> fmt::Display for Outcome<M, L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Progress {
                file,
                received,
                total,
            } => {
                let pct = if *total == 0 {
                    100.0
                } else {
                    (*received as f64 / *total as f64) * 100.0
                };
                write!(f, "{}: {pct:.1}% ({received} / {total} bytes)", file.name())
            }
            Self::Downloaded {
                location, verified, ..
            } => {
                write!(f, "downloaded ")?;
                location.fmt_location(f)?;
                write!(
                    f,
                    " ({})",
                    if *verified { "verified" } else { "unverified" }
                )
            }
            Self::Failed { file, error } => write!(f, "failed {}: {error}", file.name()),
            Self::Skipped { location, .. } => {
                write!(f, "skipped ")?;
                location.fmt_location(f)?;
                write!(f, " (already present)")
            }
            Self::StreamFailed { error } => write!(f, "stream failed: {error}"),
        }
    }
}

pub enum Prepared<L> {
    /// Destination already holds this file. Engine yields `Skipped` and stops.
    Skip { location: L },
    /// Begin or resume; engine should fetch starting at `received` and continue
    /// hashing from `partial`. `received == size` is valid and means the engine
    /// skips the byte fetch and goes straight to finalize.
    Resume { received: u64, partial: Hasher },
}

/// One driver for every download path. Pulls items from the input stream,
/// resolves each item's source URL, asks the factory for a per-item sink, and
/// runs `run_download`. Per-item errors (url resolution, sink build, transport
/// failure) yield `Failed` and the loop continues to the next item — a
/// one-element input stream therefore yields exactly one terminal outcome.
pub fn drive<'a, M, F, R>(
    http: &'a Downloader,
    items: impl Stream<Item = Result<M, Error>> + Send + 'a,
    mut resolve: R,
    factory: F,
) -> impl Stream<Item = Outcome<M, F::Location>> + Send + 'a
where
    M: Source,
    F: SinkFactory + 'a,
    R: FnMut(&M) -> Result<Url, Error> + Send + 'a,
{
    async_stream::stream! {
        let mut factory = factory;
        let mut items = pin!(items);
        loop {
            let item = match items.try_next().await {
                Ok(Some(item)) => item,
                Ok(None) => break,
                Err(error) => {
                    yield Outcome::StreamFailed { error };
                    return;
                }
            };
            let url = match resolve(&item) {
                Ok(u) => u,
                Err(error) => {
                    yield Outcome::Failed { file: item, error };
                    continue;
                }
            };
            let checksum = item.checksum();
            let target = Target {
                name: item.name(),
                size: item.size(),
                checksum: checksum.as_ref(),
            };
            let sink = match factory.make(target).await {
                Ok(s) => s,
                Err(error) => {
                    yield Outcome::Failed { file: item, error };
                    continue;
                }
            };
            let item_for_err = item.clone();
            let mut events = pin!(run_download(http, url, item, sink));
            loop {
                match events.try_next().await {
                    Ok(Some(outcome)) => yield outcome,
                    Ok(None) => break,
                    Err(error) => {
                        yield Outcome::Failed {
                            file: item_for_err,
                            error,
                        };
                        break;
                    }
                }
            }
        }
    }
}

/// Simpler driver for transfers whose source URL is already known. For
/// domain-specific items that need fallible URL resolution, use [`drive`].
pub fn drive_downloads<'a, F>(
    http: &'a Downloader,
    items: impl Stream<Item = Result<Download, Error>> + Send + 'a,
    factory: F,
) -> impl Stream<Item = Outcome<Download, F::Location>> + Send + 'a
where
    F: SinkFactory + 'a,
{
    drive(http, items, |download| Ok(download.url.clone()), factory)
}

/// Streams one item's download. Only emits the happy-path `Outcome` variants
/// (`Progress`, `Skipped`, `Downloaded`); per-item faults bubble out as `Err`
/// and `drive` turns them into `Failed`. `StreamFailed` is never produced
/// here — it's reserved for pre-item errors at the `drive` layer.
pub fn run_download<M, S>(
    http: &Downloader,
    url: Url,
    item: M,
    sink: S,
) -> impl Stream<Item = Result<Outcome<M, S::Location>, Error>> + Send + '_
where
    M: Source,
    S: Sink + Send + 'static,
{
    async_stream::try_stream! {
        let mut sink = sink;
        let size = item.size();
        let checksum = item.checksum();

        let (mut received, mut hasher) = match sink
            .prepare(Target {
                name: item.name(),
                size,
                checksum: checksum.as_ref(),
            })
            .await?
        {
            Prepared::Skip { location } => {
                yield Outcome::Skipped { file: item, location };
                return;
            }
            Prepared::Resume { received, partial } => (received, partial),
        };

        let mut last_progress: Option<Instant> = None;
        let mut attempts_left = http.max_attempts();
        let mut delay = http.backoff();

        if received > 0 && received < size {
            yield Outcome::Progress {
                file: item.clone(),
                received,
                total: size,
            };
            last_progress = Some(Instant::now());
        }

        'download: while received < size {
            let mut response = http.get_response_range(url.clone(), received).await?;

            if received > 0 {
                match response.status() {
                    reqwest::StatusCode::OK => {
                        sink.restart().await?;
                        received = 0;
                        hasher = Hasher::for_checksum(checksum.as_ref());
                        attempts_left = http.max_attempts();
                        delay = http.backoff();
                    }
                    reqwest::StatusCode::PARTIAL_CONTENT => {
                        range::validate_content_range(&response, received, size, &url)?;
                    }
                    status => {
                        Err(Error::InvalidRangeResponse {
                            url: url.to_string(),
                            details: format!("expected 200 or 206 for resume, got {status}"),
                        })?;
                    }
                }
            }

            loop {
                let chunk = match response.chunk().await {
                    Ok(Some(chunk)) => chunk,
                    Ok(None) => break 'download,
                    Err(e) => {
                        let err = Error::from(e);
                        if attempts_left > 1 && is_retryable(&err) {
                            attempts_left -= 1;
                            tokio::time::sleep(delay).await;
                            delay = delay.saturating_mul(2);
                            continue 'download;
                        }
                        Err(err)?;
                        unreachable!();
                    }
                };

                sink.write_chunk(&chunk).await?;
                hasher.update(&chunk);
                received += chunk.len() as u64;
                attempts_left = http.max_attempts();
                delay = http.backoff();

                let emit = match last_progress {
                    None => true,
                    Some(t) => t.elapsed() >= PROGRESS_INTERVAL,
                };
                if emit {
                    yield Outcome::Progress {
                        file: item.clone(),
                        received,
                        total: size,
                    };
                    last_progress = Some(Instant::now());
                }
            }
        }

        if received != size {
            Err(Error::SizeMismatch {
                url: url.to_string(),
                expected: size,
                actual: received,
            })?;
        }

        let verified = match (checksum.as_ref(), hasher.finalize_hex()) {
            (Some(expected), Some(actual)) => {
                if actual != expected.hex() {
                    Err(Error::ChecksumMismatch {
                        algorithm: expected.algorithm(),
                        url: url.to_string(),
                        expected: expected.hex().to_owned(),
                        actual,
                    })?;
                }
                true
            }
            _ => false,
        };

        let location = sink.finalize().await?;
        yield Outcome::Downloaded { file: item, location, verified };
    }
}