mithril_client/file_downloader/
interface.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
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
use std::{collections::HashMap, path::Path};

use anyhow::anyhow;
use async_trait::async_trait;

use mithril_common::{
    entities::{
        AncillaryLocation, CompressionAlgorithm, DigestLocation, FileUri, ImmutableFileNumber,
        ImmutablesLocation,
    },
    StdError, StdResult,
};

use crate::feedback::{MithrilEvent, MithrilEventCardanoDatabase};

/// A file downloader URI
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FileDownloaderUri {
    /// A single file URI
    FileUri(FileUri),
}

impl FileDownloaderUri {
    /// Expand the immutable locations to a list of file URIs
    pub fn expand_immutable_files_location_to_file_downloader_uris(
        immutable_files_location: &ImmutablesLocation,
        immutable_files_range: &[ImmutableFileNumber],
    ) -> StdResult<Vec<(ImmutableFileNumber, FileDownloaderUri)>> {
        match immutable_files_location {
            ImmutablesLocation::CloudStorage { uri } => {
                let expand_variables = immutable_files_range
                    .iter()
                    .map(|immutable_file_number| {
                        HashMap::from([(
                            "immutable_file_number".to_string(),
                            format!("{:05}", immutable_file_number),
                        )])
                    })
                    .collect();
                let file_downloader_uris = uri
                    .expand_to_file_uris(expand_variables)?
                    .into_iter()
                    .map(FileDownloaderUri::FileUri);
                let immutable_files_range = immutable_files_range.iter().copied();

                Ok(immutable_files_range.zip(file_downloader_uris).collect())
            }
            ImmutablesLocation::Unknown => {
                Err(anyhow!("Unknown location type to download immutable"))
            }
        }
    }

    /// Get the URI as a string
    pub fn as_str(&self) -> &str {
        match self {
            FileDownloaderUri::FileUri(file_uri) => file_uri.0.as_str(),
        }
    }
}

impl From<String> for FileDownloaderUri {
    fn from(location: String) -> Self {
        Self::FileUri(FileUri(location))
    }
}

impl From<FileUri> for FileDownloaderUri {
    fn from(file_uri: FileUri) -> Self {
        Self::FileUri(file_uri)
    }
}

impl TryFrom<AncillaryLocation> for FileDownloaderUri {
    type Error = StdError;

    fn try_from(location: AncillaryLocation) -> Result<Self, Self::Error> {
        match location {
            AncillaryLocation::CloudStorage { uri } => Ok(Self::FileUri(FileUri(uri))),
            AncillaryLocation::Unknown => {
                Err(anyhow!("Unknown location type to download ancillary"))
            }
        }
    }
}

impl TryFrom<DigestLocation> for FileDownloaderUri {
    type Error = StdError;

    fn try_from(location: DigestLocation) -> Result<Self, Self::Error> {
        match location {
            DigestLocation::CloudStorage { uri } | DigestLocation::Aggregator { uri } => {
                Ok(Self::FileUri(FileUri(uri)))
            }
            DigestLocation::Unknown => Err(anyhow!("Unknown location type to download digest")),
        }
    }
}

/// A download event
///
/// The `download_id` is a unique identifier that allow
/// [feedback receivers][crate::feedback::FeedbackReceiver] to track concurrent downloads.
#[derive(Debug, Clone)]
pub enum DownloadEvent {
    /// Immutable file download
    Immutable {
        /// Unique download identifier
        download_id: String,
        /// Immutable file number
        immutable_file_number: ImmutableFileNumber,
    },
    /// Ancillary file download
    Ancillary {
        /// Unique download identifier
        download_id: String,
    },
    /// Digest file download
    Digest {
        /// Unique download identifier
        download_id: String,
    },
    /// Full database download
    Full {
        /// Unique download identifier
        download_id: String,
    },
}

impl DownloadEvent {
    /// Get the unique download identifier
    pub fn download_id(&self) -> &str {
        match self {
            DownloadEvent::Immutable {
                immutable_file_number: _,
                download_id,
            } => download_id,
            DownloadEvent::Ancillary { download_id }
            | DownloadEvent::Digest { download_id }
            | DownloadEvent::Full { download_id } => download_id,
        }
    }

    /// Build a download started event
    pub fn build_download_progress_event(
        &self,
        downloaded_bytes: u64,
        total_bytes: u64,
    ) -> MithrilEvent {
        match self {
            DownloadEvent::Immutable {
                immutable_file_number,
                download_id,
            } => MithrilEvent::CardanoDatabase(
                MithrilEventCardanoDatabase::ImmutableDownloadProgress {
                    download_id: download_id.to_string(),
                    downloaded_bytes,
                    size: total_bytes,
                    immutable_file_number: *immutable_file_number,
                },
            ),
            DownloadEvent::Ancillary { download_id } => MithrilEvent::CardanoDatabase(
                MithrilEventCardanoDatabase::AncillaryDownloadProgress {
                    download_id: download_id.to_string(),
                    downloaded_bytes,
                    size: total_bytes,
                },
            ),
            DownloadEvent::Digest { download_id } => {
                MithrilEvent::CardanoDatabase(MithrilEventCardanoDatabase::DigestDownloadProgress {
                    download_id: download_id.to_string(),
                    downloaded_bytes,
                    size: total_bytes,
                })
            }
            DownloadEvent::Full { download_id } => MithrilEvent::SnapshotDownloadProgress {
                download_id: download_id.to_string(),
                downloaded_bytes,
                size: total_bytes,
            },
        }
    }
}

/// A file downloader
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait FileDownloader: Sync + Send {
    /// Download and unpack (if necessary) a file on the disk.
    ///
    async fn download_unpack(
        &self,
        location: &FileDownloaderUri,
        target_dir: &Path,
        compression_algorithm: Option<CompressionAlgorithm>,
        download_event_type: DownloadEvent,
    ) -> StdResult<()>;
}

#[cfg(test)]
mod tests {
    use mithril_common::entities::{MultiFilesUri, TemplateUri};

    use super::*;

    #[test]
    fn immutable_files_location_to_file_downloader_uris() {
        let immutable_files_location = ImmutablesLocation::CloudStorage {
            uri: MultiFilesUri::Template(TemplateUri(
                "http://whatever/{immutable_file_number}.tar.gz".to_string(),
            )),
        };
        let immutable_files_range: Vec<ImmutableFileNumber> = (1..=3).collect();

        let file_downloader_uris =
            FileDownloaderUri::expand_immutable_files_location_to_file_downloader_uris(
                &immutable_files_location,
                &immutable_files_range,
            )
            .unwrap();

        assert_eq!(
            file_downloader_uris,
            vec![
                (
                    1,
                    FileDownloaderUri::FileUri(FileUri("http://whatever/00001.tar.gz".to_string()))
                ),
                (
                    2,
                    FileDownloaderUri::FileUri(FileUri("http://whatever/00002.tar.gz".to_string()))
                ),
                (
                    3,
                    FileDownloaderUri::FileUri(FileUri("http://whatever/00003.tar.gz".to_string()))
                ),
            ]
        );
    }

    #[test]
    fn immutable_files_location_to_file_downloader_uris_return_error_when_location_is_unknown() {
        let immutable_files_location = ImmutablesLocation::Unknown;
        let immutable_files_range: Vec<ImmutableFileNumber> = (1..=1).collect();

        FileDownloaderUri::expand_immutable_files_location_to_file_downloader_uris(
            &immutable_files_location,
            &immutable_files_range,
        )
        .expect_err("expand_immutable_files_location_to_file_downloader_uris should fail");
    }

    #[test]
    fn download_event_type_builds_correct_event() {
        let download_event_type = DownloadEvent::Immutable {
            download_id: "download-123".to_string(),
            immutable_file_number: 123,
        };
        let event = download_event_type.build_download_progress_event(123, 1234);
        assert_eq!(
            MithrilEvent::CardanoDatabase(MithrilEventCardanoDatabase::ImmutableDownloadProgress {
                immutable_file_number: 123,
                download_id: "download-123".to_string(),
                downloaded_bytes: 123,
                size: 1234,
            }),
            event,
        );

        let download_event_type = DownloadEvent::Ancillary {
            download_id: "download-123".to_string(),
        };
        let event = download_event_type.build_download_progress_event(123, 1234);
        assert_eq!(
            MithrilEvent::CardanoDatabase(MithrilEventCardanoDatabase::AncillaryDownloadProgress {
                download_id: "download-123".to_string(),
                downloaded_bytes: 123,
                size: 1234,
            }),
            event,
        );

        let download_event_type = DownloadEvent::Digest {
            download_id: "download-123".to_string(),
        };
        let event = download_event_type.build_download_progress_event(123, 1234);
        assert_eq!(
            MithrilEvent::CardanoDatabase(MithrilEventCardanoDatabase::DigestDownloadProgress {
                download_id: "download-123".to_string(),
                downloaded_bytes: 123,
                size: 1234,
            }),
            event,
        );

        let download_event_type = DownloadEvent::Full {
            download_id: "download-123".to_string(),
        };
        let event = download_event_type.build_download_progress_event(123, 1234);
        assert_eq!(
            MithrilEvent::SnapshotDownloadProgress {
                download_id: "download-123".to_string(),
                downloaded_bytes: 123,
                size: 1234,
            },
            event,
        );
    }

    #[test]
    fn file_downloader_uri_from_ancillary_location() {
        let location = AncillaryLocation::CloudStorage {
            uri: "http://whatever/ancillary-1".to_string(),
        };
        let file_downloader_uri: FileDownloaderUri = location.try_into().unwrap();

        assert_eq!(
            FileDownloaderUri::FileUri(FileUri("http://whatever/ancillary-1".to_string())),
            file_downloader_uri
        );
    }
    #[test]
    fn file_downloader_uri_from_unknown_ancillary_location() {
        let location = AncillaryLocation::Unknown;
        let file_downloader_uri: StdResult<FileDownloaderUri> = location.try_into();

        file_downloader_uri.expect_err("try_into should fail on Unknown ancillary location");
    }

    #[test]
    fn file_downloader_uri_from_digest_location() {
        let location = DigestLocation::CloudStorage {
            uri: "http://whatever/digest-1".to_string(),
        };
        let file_downloader_uri: FileDownloaderUri = location.try_into().unwrap();

        assert_eq!(
            FileDownloaderUri::FileUri(FileUri("http://whatever/digest-1".to_string())),
            file_downloader_uri
        );
    }
    #[test]
    fn file_downloader_uri_from_unknown_digest_location() {
        let location = DigestLocation::Unknown;
        let file_downloader_uri: StdResult<FileDownloaderUri> = location.try_into();

        file_downloader_uri.expect_err("try_into should fail on Unknown digest location");
    }
}