mithril_client/utils/
unpacker.rs

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
use anyhow::Context;
use flate2::read::GzDecoder;
use flume::Receiver;
use std::path::Path;
use tar::Archive;

use crate::common::CompressionAlgorithm;
use crate::utils::StreamReader;
use crate::MithrilResult;

/// Unpack a downloaded archive in a given directory.
#[derive(Default)]
pub struct SnapshotUnpacker;

impl SnapshotUnpacker {
    /// Unpack the snapshot from the given stream into the given directory.
    pub fn unpack_snapshot(
        &self,
        stream: Receiver<Vec<u8>>,
        compression_algorithm: CompressionAlgorithm,
        unpack_dir: &Path,
    ) -> MithrilResult<()> {
        let input = StreamReader::new(stream);

        match compression_algorithm {
            CompressionAlgorithm::Gzip => {
                let gzip_decoder = GzDecoder::new(input);
                let mut snapshot_archive = Archive::new(gzip_decoder);
                snapshot_archive.unpack(unpack_dir).with_context(|| {
                    format!(
                        "Could not unpack from streamed data snapshot to directory '{}'",
                        unpack_dir.display()
                    )
                })?;
            }
            CompressionAlgorithm::Zstandard => {
                let zstandard_decoder = zstd::Decoder::new(input)
                    .with_context(|| "Unpack failed: Create Zstandard decoder error")?;
                let mut snapshot_archive = Archive::new(zstandard_decoder);
                snapshot_archive.unpack(unpack_dir).with_context(|| {
                    format!(
                        "Could not unpack from streamed data snapshot to directory '{}'",
                        unpack_dir.display()
                    )
                })?;
            }
        };

        Ok(())
    }
}