mithril_client/cardano_database_client/
download_unpack.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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
use std::collections::BTreeSet;
use std::future::Future;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use tokio::task::JoinSet;

use anyhow::anyhow;

use mithril_common::{
    digesters::{IMMUTABLE_DIR, LEDGER_DIR, VOLATILE_DIR},
    entities::{AncillaryLocation, CompressionAlgorithm, ImmutableFileNumber, ImmutablesLocation},
    messages::CardanoDatabaseSnapshotMessage,
};

use crate::feedback::{FeedbackSender, MithrilEvent, MithrilEventCardanoDatabase};
use crate::file_downloader::{DownloadEvent, FileDownloader, FileDownloaderUri};
use crate::MithrilResult;

use super::immutable_file_range::ImmutableFileRange;

/// The future type for downloading an immutable file
type DownloadImmutableFuture = dyn Future<Output = MithrilResult<ImmutableFileNumber>> + Send;

/// Arguments for the immutable file download future builder
struct DownloadImmutableFutureBuilderArgs {
    file_downloader: Arc<dyn FileDownloader>,
    immutable_file_number: ImmutableFileNumber,
    file_downloader_uri: FileDownloaderUri,
    compression_algorithm: CompressionAlgorithm,
    immutable_files_target_dir: PathBuf,
    download_id: String,
    file_size: u64,
}

/// Options for downloading and unpacking a Cardano database
#[derive(Debug)]
pub struct DownloadUnpackOptions {
    /// Allow overriding the destination directory
    pub allow_override: bool,

    /// Include ancillary files in the download
    pub include_ancillary: bool,

    /// Maximum number of parallel downloads
    pub max_parallel_downloads: usize,
}

impl Default for DownloadUnpackOptions {
    fn default() -> Self {
        Self {
            allow_override: false,
            include_ancillary: false,
            max_parallel_downloads: 100,
        }
    }
}

pub struct InternalArtifactDownloader {
    http_file_downloader: Arc<dyn FileDownloader>,
    feedback_sender: FeedbackSender,
    logger: slog::Logger,
}

impl InternalArtifactDownloader {
    /// Constructs a new `InternalArtifactDownloader`.
    pub fn new(
        http_file_downloader: Arc<dyn FileDownloader>,
        feedback_sender: FeedbackSender,
        logger: slog::Logger,
    ) -> Self {
        Self {
            http_file_downloader,
            feedback_sender,
            logger,
        }
    }

    /// Download and unpack the given Cardano database parts data by hash.
    pub async fn download_unpack(
        &self,
        cardano_database_snapshot: &CardanoDatabaseSnapshotMessage,
        immutable_file_range: &ImmutableFileRange,
        target_dir: &Path,
        download_unpack_options: DownloadUnpackOptions,
    ) -> MithrilResult<()> {
        let download_id = MithrilEvent::new_snapshot_download_id();
        let compression_algorithm = cardano_database_snapshot.compression_algorithm;
        let last_immutable_file_number = cardano_database_snapshot.beacon.immutable_file_number;
        let immutable_file_number_range =
            immutable_file_range.to_range_inclusive(last_immutable_file_number)?;
        let immutable_file_range_length =
            immutable_file_number_range.end() - immutable_file_number_range.start() + 1;
        self.feedback_sender
            .send_event(MithrilEvent::CardanoDatabase(
                MithrilEventCardanoDatabase::Started {
                    download_id: download_id.clone(),
                    total_immutable_files: immutable_file_range_length,
                    include_ancillary: download_unpack_options.include_ancillary,
                },
            ))
            .await;
        Self::verify_download_options_compatibility(
            &download_unpack_options,
            &immutable_file_number_range,
            last_immutable_file_number,
        )?;
        Self::verify_can_write_to_target_directory(target_dir, &download_unpack_options)?;
        let immutable_locations = &cardano_database_snapshot.locations.immutables;
        self.download_unpack_immutable_files(
            immutable_locations,
            immutable_file_number_range,
            &compression_algorithm,
            target_dir,
            download_unpack_options.max_parallel_downloads,
            &download_id,
        )
        .await?;
        if download_unpack_options.include_ancillary {
            let ancillary_locations = &cardano_database_snapshot.locations.ancillary;
            self.download_unpack_ancillary_file(
                ancillary_locations,
                &compression_algorithm,
                target_dir,
                &download_id,
            )
            .await?;
        }
        self.feedback_sender
            .send_event(MithrilEvent::CardanoDatabase(
                MithrilEventCardanoDatabase::Completed {
                    download_id: download_id.clone(),
                },
            ))
            .await;

        Ok(())
    }

    fn immutable_files_target_dir(target_dir: &Path) -> PathBuf {
        target_dir.join(IMMUTABLE_DIR)
    }

    fn volatile_target_dir(target_dir: &Path) -> PathBuf {
        target_dir.join(VOLATILE_DIR)
    }

    fn ledger_target_dir(target_dir: &Path) -> PathBuf {
        target_dir.join(LEDGER_DIR)
    }

    /// Verify if the target directory is writable.
    fn verify_can_write_to_target_directory(
        target_dir: &Path,
        download_unpack_options: &DownloadUnpackOptions,
    ) -> MithrilResult<()> {
        let immutable_files_target_dir = Self::immutable_files_target_dir(target_dir);
        let volatile_target_dir = Self::volatile_target_dir(target_dir);
        let ledger_target_dir = Self::ledger_target_dir(target_dir);
        if !download_unpack_options.allow_override {
            if immutable_files_target_dir.exists() {
                return Err(anyhow!(
                    "Immutable files target directory already exists in: {target_dir:?}"
                ));
            }
            if download_unpack_options.include_ancillary {
                if volatile_target_dir.exists() {
                    return Err(anyhow!(
                        "Volatile target directory already exists in: {target_dir:?}"
                    ));
                }
                if ledger_target_dir.exists() {
                    return Err(anyhow!(
                        "Ledger target directory already exists in: {target_dir:?}"
                    ));
                }
            }
        }

        Ok(())
    }

    /// Verify if the download options are compatible with the immutable file range.
    fn verify_download_options_compatibility(
        download_options: &DownloadUnpackOptions,
        immutable_file_range: &RangeInclusive<ImmutableFileNumber>,
        last_immutable_file_number: ImmutableFileNumber,
    ) -> MithrilResult<()> {
        if download_options.include_ancillary
            && !immutable_file_range.contains(&last_immutable_file_number)
        {
            return Err(anyhow!(
                "The last immutable file number {last_immutable_file_number} is outside the range: {immutable_file_range:?}"
            ));
        }

        Ok(())
    }

    /// Download and unpack the immutable files of the given range.
    ///
    /// The download is attempted for each location until the full range is downloaded.
    /// An error is returned if not all the files are downloaded.
    async fn download_unpack_immutable_files(
        &self,
        locations: &[ImmutablesLocation],
        range: RangeInclusive<ImmutableFileNumber>,
        compression_algorithm: &CompressionAlgorithm,
        immutable_files_target_dir: &Path,
        max_parallel_downloads: usize,
        download_id: &str,
    ) -> MithrilResult<()> {
        let mut locations_sorted = locations.to_owned();
        locations_sorted.sort();
        let mut immutable_file_numbers_to_download =
            range.map(|n| n.to_owned()).collect::<BTreeSet<_>>();
        for location in locations_sorted {
            let immutable_files_numbers_downloaded = self
                .download_unpack_immutable_files_for_location(
                    &location,
                    &immutable_file_numbers_to_download,
                    compression_algorithm,
                    immutable_files_target_dir,
                    max_parallel_downloads,
                    download_id,
                )
                .await?;
            for immutable_file_number in immutable_files_numbers_downloaded {
                immutable_file_numbers_to_download.remove(&immutable_file_number);
            }
            if immutable_file_numbers_to_download.is_empty() {
                return Ok(());
            }
        }

        Err(anyhow!(
                "Failed downloading and unpacking immutable files for immutable_file_numbers: {immutable_file_numbers_to_download:?}"
            ))
    }

    /// Download and unpack the immutable files of the given range.
    ///
    /// The download is attempted for each location until the full range is downloaded.
    /// An error is returned if not all the files are downloaded.
    async fn batch_download_unpack_immutable_files(
        &self,
        file_downloader: Arc<dyn FileDownloader>,
        file_downloader_uris_chunk: Vec<(ImmutableFileNumber, FileDownloaderUri)>,
        compression_algorithm: &CompressionAlgorithm,
        immutable_files_target_dir: &Path,
        download_id: &str,
        file_size: u64,
    ) -> MithrilResult<BTreeSet<ImmutableFileNumber>> {
        let mut immutable_file_numbers_downloaded = BTreeSet::new();
        let mut join_set: JoinSet<MithrilResult<ImmutableFileNumber>> = JoinSet::new();
        for (immutable_file_number, file_downloader_uri) in file_downloader_uris_chunk.into_iter() {
            join_set.spawn(self.spawn_immutable_download_future(
                DownloadImmutableFutureBuilderArgs {
                    file_downloader: file_downloader.clone(),
                    immutable_file_number,
                    file_downloader_uri,
                    compression_algorithm: compression_algorithm.to_owned(),
                    immutable_files_target_dir: immutable_files_target_dir.to_path_buf(),
                    download_id: download_id.to_string(),
                    file_size,
                },
            )?);
        }
        while let Some(result) = join_set.join_next().await {
            match result? {
                Ok(immutable_file_number) => {
                    immutable_file_numbers_downloaded.insert(immutable_file_number);
                }
                Err(e) => {
                    slog::error!(
                        self.logger,
                        "Failed downloading and unpacking immutable files"; "error" => ?e, "target_dir" => immutable_files_target_dir.display()
                    );
                }
            }
        }

        Ok(immutable_file_numbers_downloaded)
    }

    fn spawn_immutable_download_future(
        &self,
        args: DownloadImmutableFutureBuilderArgs,
    ) -> MithrilResult<Pin<Box<DownloadImmutableFuture>>> {
        let feedback_receiver_clone = self.feedback_sender.clone();
        let logger_clone = self.logger.clone();
        let download_id_clone = args.download_id.to_string();
        let file_downloader = args.file_downloader;
        let file_downloader_uri = args.file_downloader_uri;
        let compression_algorithm = args.compression_algorithm;
        let immutable_files_target_dir = args.immutable_files_target_dir;
        let immutable_file_number = args.immutable_file_number;
        let file_size = args.file_size;
        let download_future = async move {
            feedback_receiver_clone
                .send_event(MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::ImmutableDownloadStarted {
                        immutable_file_number,
                        download_id: download_id_clone.clone(),
                        size: file_size,
                    },
                ))
                .await;
            let downloaded = file_downloader
                .download_unpack(
                    &file_downloader_uri,
                    &immutable_files_target_dir,
                    Some(compression_algorithm),
                    DownloadEvent::Immutable {
                        immutable_file_number,
                        download_id: download_id_clone.clone(),
                    },
                )
                .await;
            match downloaded {
                Ok(_) => {
                    feedback_receiver_clone
                        .send_event(MithrilEvent::CardanoDatabase(
                            MithrilEventCardanoDatabase::ImmutableDownloadCompleted {
                                immutable_file_number,
                                download_id: download_id_clone,
                            },
                        ))
                        .await;

                    Ok(immutable_file_number)
                }
                Err(e) => {
                    slog::error!(
                        logger_clone,
                        "Failed downloading and unpacking immutable file {immutable_file_number} for location {file_downloader_uri:?}"; "error" => ?e
                    );
                    Err(e.context(format!("Failed downloading and unpacking immutable file {immutable_file_number} for location {file_downloader_uri:?}")))
                }
            }
        };

        Ok(Box::pin(download_future))
    }

    async fn download_unpack_immutable_files_for_location(
        &self,
        location: &ImmutablesLocation,
        immutable_file_numbers_to_download: &BTreeSet<ImmutableFileNumber>,
        compression_algorithm: &CompressionAlgorithm,
        immutable_files_target_dir: &Path,
        max_parallel_downloads: usize,
        download_id: &str,
    ) -> MithrilResult<BTreeSet<ImmutableFileNumber>> {
        let mut immutable_file_numbers_downloaded = BTreeSet::new();
        // The size will be completed with the uncompressed file size when available in the location
        // (see https://github.com/input-output-hk/mithril/issues/2291)
        let file_size = 0;
        let file_downloader = match &location {
            ImmutablesLocation::CloudStorage { .. } => self.http_file_downloader.clone(),
            ImmutablesLocation::Unknown => {
                return Err(anyhow!("Unknown location type to download immutable"));
            }
        };
        let file_downloader_uris =
            FileDownloaderUri::expand_immutable_files_location_to_file_downloader_uris(
                location,
                immutable_file_numbers_to_download
                    .clone()
                    .into_iter()
                    .collect::<Vec<_>>()
                    .as_slice(),
            )?;
        let file_downloader_uri_chunks = file_downloader_uris
            .chunks(max_parallel_downloads)
            .map(|x| x.to_vec())
            .collect::<Vec<_>>();
        for file_downloader_uris_chunk in file_downloader_uri_chunks {
            let immutable_file_numbers_downloaded_chunk = self
                .batch_download_unpack_immutable_files(
                    file_downloader.clone(),
                    file_downloader_uris_chunk,
                    compression_algorithm,
                    immutable_files_target_dir,
                    download_id,
                    file_size,
                )
                .await?;
            immutable_file_numbers_downloaded.extend(immutable_file_numbers_downloaded_chunk);
        }

        Ok(immutable_file_numbers_downloaded)
    }

    /// Download and unpack the ancillary files.
    pub(crate) async fn download_unpack_ancillary_file(
        &self,
        locations: &[AncillaryLocation],
        compression_algorithm: &CompressionAlgorithm,
        ancillary_file_target_dir: &Path,
        download_id: &str,
    ) -> MithrilResult<()> {
        let mut locations_sorted = locations.to_owned();
        locations_sorted.sort();
        for location in locations_sorted {
            // The size will be completed with the uncompressed file size when available in the location
            // (see https://github.com/input-output-hk/mithril/issues/2291)
            let file_size = 0;
            self.feedback_sender
                .send_event(MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::AncillaryDownloadStarted {
                        download_id: download_id.to_string(),
                        size: file_size,
                    },
                ))
                .await;
            let file_downloader = match &location {
                AncillaryLocation::CloudStorage { .. } => self.http_file_downloader.clone(),
                AncillaryLocation::Unknown => {
                    continue;
                }
            };
            let file_downloader_uri = location.try_into()?;
            let downloaded = file_downloader
                .download_unpack(
                    &file_downloader_uri,
                    ancillary_file_target_dir,
                    Some(compression_algorithm.to_owned()),
                    DownloadEvent::Ancillary {
                        download_id: download_id.to_string(),
                    },
                )
                .await;
            match downloaded {
                Ok(_) => {
                    self.feedback_sender
                        .send_event(MithrilEvent::CardanoDatabase(
                            MithrilEventCardanoDatabase::AncillaryDownloadCompleted {
                                download_id: download_id.to_string(),
                            },
                        ))
                        .await;
                    return Ok(());
                }
                Err(e) => {
                    slog::error!(
                        self.logger,
                        "Failed downloading and unpacking ancillaries for location {file_downloader_uri:?}"; "error" => ?e
                    );
                }
            }
        }

        Err(anyhow!(
            "Failed downloading and unpacking ancillaries for all locations"
        ))
    }
}

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

    use mithril_common::{
        entities::{CardanoDbBeacon, Epoch, MultiFilesUri, TemplateUri},
        messages::{
            ArtifactsLocationsMessagePart,
            CardanoDatabaseSnapshotMessage as CardanoDatabaseSnapshot,
        },
        test_utils::TempDir,
    };

    use crate::cardano_database_client::CardanoDatabaseClientDependencyInjector;
    use crate::feedback::StackFeedbackReceiver;
    use crate::file_downloader::{MockFileDownloader, MockFileDownloaderBuilder};
    use crate::test_utils;

    use super::*;

    mod download_unpack {

        use super::*;

        #[tokio::test]
        async fn download_unpack_fails_with_invalid_immutable_file_range() {
            let immutable_file_range = ImmutableFileRange::Range(1, 0);
            let download_unpack_options = DownloadUnpackOptions::default();
            let cardano_db_snapshot = CardanoDatabaseSnapshot {
                hash: "hash-123".to_string(),
                ..CardanoDatabaseSnapshot::dummy()
            };
            let target_dir = Path::new(".");
            let client =
                CardanoDatabaseClientDependencyInjector::new().build_cardano_database_client();

            client
                .download_unpack(
                    &cardano_db_snapshot,
                    &immutable_file_range,
                    target_dir,
                    download_unpack_options,
                )
                .await
                .expect_err("download_unpack should fail");
        }

        #[tokio::test]
        async fn download_unpack_fails_when_immutable_files_download_fail() {
            let total_immutable_files = 10;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let download_unpack_options = DownloadUnpackOptions::default();
            let cardano_db_snapshot = CardanoDatabaseSnapshot {
                hash: "hash-123".to_string(),
                locations: ArtifactsLocationsMessagePart {
                    immutables: vec![ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    ..ArtifactsLocationsMessagePart::default()
                },
                ..CardanoDatabaseSnapshot::dummy()
            };
            let target_dir = TempDir::new(
                "cardano_database_client",
                "download_unpack_fails_when_immutable_files_download_fail",
            )
            .build();
            let client = CardanoDatabaseClientDependencyInjector::new()
                .with_http_file_downloader(Arc::new({
                    MockFileDownloaderBuilder::default()
                        .with_times(total_immutable_files as usize)
                        .with_failure()
                        .build()
                }))
                .build_cardano_database_client();

            client
                .download_unpack(
                    &cardano_db_snapshot,
                    &immutable_file_range,
                    &target_dir,
                    download_unpack_options,
                )
                .await
                .expect_err("download_unpack should fail");
        }

        #[tokio::test]
        async fn download_unpack_fails_when_target_dir_would_be_overwritten_without_allow_override()
        {
            let immutable_file_range = ImmutableFileRange::Range(1, 10);
            let download_unpack_options = DownloadUnpackOptions::default();
            let cardano_db_snapshot = CardanoDatabaseSnapshot {
                hash: "hash-123".to_string(),
                ..CardanoDatabaseSnapshot::dummy()
            };
            let target_dir = &TempDir::new(
                "cardano_database_client",
                "download_unpack_fails_when_target_dir_would_be_overwritten_without_allow_override",
            )
            .build();
            fs::create_dir_all(target_dir.join("immutable")).unwrap();
            let client =
                CardanoDatabaseClientDependencyInjector::new().build_cardano_database_client();

            client
                .download_unpack(
                    &cardano_db_snapshot,
                    &immutable_file_range,
                    target_dir,
                    download_unpack_options,
                )
                .await
                .expect_err("download_unpack should fail");
        }

        #[tokio::test]
        async fn download_unpack_succeeds_with_valid_range() {
            let immutable_file_range = ImmutableFileRange::Range(1, 2);
            let download_unpack_options = DownloadUnpackOptions {
                include_ancillary: true,
                ..DownloadUnpackOptions::default()
            };
            let cardano_db_snapshot = CardanoDatabaseSnapshot {
                hash: "hash-123".to_string(),
                beacon: CardanoDbBeacon {
                    immutable_file_number: 2,
                    epoch: Epoch(123),
                },
                locations: ArtifactsLocationsMessagePart {
                    immutables: vec![ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    ancillary: vec![AncillaryLocation::CloudStorage {
                        uri: "http://whatever/ancillary.tar.gz".to_string(),
                    }],
                    digests: vec![],
                },
                ..CardanoDatabaseSnapshot::dummy()
            };
            let target_dir = TempDir::new(
                "cardano_database_client",
                "download_unpack_succeeds_with_valid_range",
            )
            .build();
            let client = CardanoDatabaseClientDependencyInjector::new()
                .with_http_file_downloader(Arc::new({
                    MockFileDownloaderBuilder::default()
                        .with_file_uri("http://whatever/00001.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_success()
                        .next_call()
                        .with_file_uri("http://whatever/00002.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_success()
                        .next_call()
                        .with_file_uri("http://whatever/ancillary.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_compression(Some(CompressionAlgorithm::default()))
                        .with_success()
                        .build()
                }))
                .build_cardano_database_client();

            client
                .download_unpack(
                    &cardano_db_snapshot,
                    &immutable_file_range,
                    &target_dir,
                    download_unpack_options,
                )
                .await
                .unwrap();
        }
    }

    mod verify_download_options_compatibility {

        use super::*;

        #[test]
        fn verify_download_options_compatibility_succeeds_if_without_ancillary_download() {
            let download_options = DownloadUnpackOptions {
                include_ancillary: false,
                ..DownloadUnpackOptions::default()
            };
            let immutable_file_range = ImmutableFileRange::Range(1, 10);
            let last_immutable_file_number = 10;

            InternalArtifactDownloader::verify_download_options_compatibility(
                &download_options,
                &immutable_file_range
                    .to_range_inclusive(last_immutable_file_number)
                    .unwrap(),
                last_immutable_file_number,
            )
            .unwrap();
        }

        #[test]
        fn verify_download_options_compatibility_succeeds_if_with_ancillary_download_and_compatible_range(
        ) {
            let download_options = DownloadUnpackOptions {
                include_ancillary: true,
                ..DownloadUnpackOptions::default()
            };
            let immutable_file_range = ImmutableFileRange::Range(7, 10);
            let last_immutable_file_number = 10;

            InternalArtifactDownloader::verify_download_options_compatibility(
                &download_options,
                &immutable_file_range
                    .to_range_inclusive(last_immutable_file_number)
                    .unwrap(),
                last_immutable_file_number,
            )
            .unwrap();
        }

        #[test]
        fn verify_download_options_compatibility_fails_if_with_ancillary_download_and_incompatible_range(
        ) {
            let download_options = DownloadUnpackOptions {
                include_ancillary: true,
                ..DownloadUnpackOptions::default()
            };
            let immutable_file_range = ImmutableFileRange::Range(7, 10);
            let last_immutable_file_number = 123;

            InternalArtifactDownloader::verify_download_options_compatibility(
                    &download_options,
                    &immutable_file_range
                        .to_range_inclusive(last_immutable_file_number)
                        .unwrap(),
                    last_immutable_file_number,
                )
                .expect_err("verify_download_options_compatibility should fail as the last immutable file number is outside the range");
        }
    }

    mod verify_can_write_to_target_dir {

        use super::*;

        #[test]
        fn verify_can_write_to_target_dir_always_succeeds_with_allow_overwrite() {
            let target_dir = TempDir::new(
                "cardano_database_client",
                "verify_can_write_to_target_dir_always_succeeds_with_allow_overwrite",
            )
            .build();

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: true,
                    include_ancillary: false,
                    ..DownloadUnpackOptions::default()
                },
            )
            .unwrap();

            fs::create_dir_all(InternalArtifactDownloader::immutable_files_target_dir(
                &target_dir,
            ))
            .unwrap();
            fs::create_dir_all(InternalArtifactDownloader::volatile_target_dir(&target_dir))
                .unwrap();
            fs::create_dir_all(InternalArtifactDownloader::ledger_target_dir(&target_dir)).unwrap();
            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: true,
                    include_ancillary: false,
                    ..DownloadUnpackOptions::default()
                },
            )
            .unwrap();
            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: true,
                    include_ancillary: true,
                    ..DownloadUnpackOptions::default()
                },
            )
            .unwrap();
        }

        #[test]
        fn verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_immutable_target_dir(
        ) {
            let target_dir = TempDir::new("cardano_database_client", "verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_immutable_target_dir").build();
            fs::create_dir_all(InternalArtifactDownloader::immutable_files_target_dir(
                &target_dir,
            ))
            .unwrap();

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: false,
                    ..DownloadUnpackOptions::default()
                },
            )
            .expect_err("verify_can_write_to_target_dir should fail");

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: true,
                    ..DownloadUnpackOptions::default()
                },
            )
            .expect_err("verify_can_write_to_target_dir should fail");
        }

        #[test]
        fn verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_ledger_target_dir(
        ) {
            let target_dir = TempDir::new("cardano_database_client", "verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_ledger_target_dir").build();
            fs::create_dir_all(InternalArtifactDownloader::ledger_target_dir(&target_dir)).unwrap();

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: true,
                    ..DownloadUnpackOptions::default()
                },
            )
            .expect_err("verify_can_write_to_target_dir should fail");

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: false,
                    ..DownloadUnpackOptions::default()
                },
            )
            .unwrap();
        }

        #[test]
        fn verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_volatile_target_dir(
        ) {
            let target_dir = TempDir::new("cardano_database_client", "verify_can_write_to_target_dir_fails_without_allow_overwrite_and_non_empty_volatile_target_dir").build();
            fs::create_dir_all(InternalArtifactDownloader::volatile_target_dir(&target_dir))
                .unwrap();

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: true,
                    ..DownloadUnpackOptions::default()
                },
            )
            .expect_err("verify_can_write_to_target_dir should fail");

            InternalArtifactDownloader::verify_can_write_to_target_directory(
                &target_dir,
                &DownloadUnpackOptions {
                    allow_override: false,
                    include_ancillary: false,
                    ..DownloadUnpackOptions::default()
                },
            )
            .unwrap();
        }
    }

    mod download_unpack_immutable_files {

        use super::*;

        #[tokio::test]
        async fn download_unpack_immutable_files_fails_if_one_is_not_retrieved() {
            let total_immutable_files = 2;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = TempDir::new(
                "cardano_database_client",
                "download_unpack_immutable_files_succeeds",
            )
            .build();
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(
                    MockFileDownloaderBuilder::default()
                        .with_failure()
                        .next_call()
                        .with_success()
                        .build(),
                ),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    &target_dir,
                    1,
                    "download_id",
                )
                .await
                .expect_err("download_unpack_immutable_files should fail");
        }

        #[tokio::test]
        async fn download_unpack_immutable_files_fails_if_location_is_unknown() {
            let total_immutable_files = 2;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = TempDir::new("cardano_database_client", "download_unpack").build();
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloader::new()),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[ImmutablesLocation::Unknown {}],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    &target_dir,
                    1,
                    "download_id",
                )
                .await
                .expect_err("download_unpack_immutable_files should fail");
        }

        #[tokio::test]
        async fn download_unpack_immutable_files_succeeds_if_all_are_retrieved_with_same_location()
        {
            let total_immutable_files = 2;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = TempDir::new(
                "cardano_database_client",
                "download_unpack_immutable_files_succeeds",
            )
            .build();
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(
                    MockFileDownloaderBuilder::default()
                        .with_times(2)
                        .with_success()
                        .build(),
                ),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever-1/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    &target_dir,
                    1,
                    "download_id",
                )
                .await
                .unwrap();
        }

        #[tokio::test]
        async fn download_unpack_immutable_files_succeeds_if_all_are_retrieved_with_different_locations(
        ) {
            let total_immutable_files = 2;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = TempDir::new(
                "cardano_database_client",
                "download_unpack_immutable_files_succeeds",
            )
            .build();
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(
                    MockFileDownloaderBuilder::default()
                        .with_file_uri("http://whatever-1/00001.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_failure()
                        .next_call()
                        .with_file_uri("http://whatever-1/00002.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_success()
                        .next_call()
                        .with_file_uri("http://whatever-2/00001.tar.gz")
                        .with_target_dir(target_dir.clone())
                        .with_success()
                        .build(),
                ),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[
                        ImmutablesLocation::CloudStorage {
                            uri: MultiFilesUri::Template(TemplateUri(
                                "http://whatever-1/{immutable_file_number}.tar.gz".to_string(),
                            )),
                        },
                        ImmutablesLocation::CloudStorage {
                            uri: MultiFilesUri::Template(TemplateUri(
                                "http://whatever-2/{immutable_file_number}.tar.gz".to_string(),
                            )),
                        },
                    ],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    &target_dir,
                    1,
                    "download_id",
                )
                .await
                .unwrap();
        }

        #[tokio::test]
        async fn download_unpack_immutable_files_sends_feedbacks_when_succeeds() {
            let total_immutable_files = 1;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = Path::new(".");
            let feedback_receiver = Arc::new(StackFeedbackReceiver::new());
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloaderBuilder::default().with_success().build()),
                FeedbackSender::new(&[feedback_receiver.clone()]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    target_dir,
                    1,
                    "download_id",
                )
                .await
                .unwrap();

            let sent_events = feedback_receiver.stacked_events();
            let id = sent_events[0].event_id();
            let expected_events = vec![
                MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::ImmutableDownloadStarted {
                        immutable_file_number: 1,
                        download_id: id.to_string(),
                        size: 0,
                    },
                ),
                MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::ImmutableDownloadCompleted {
                        immutable_file_number: 1,
                        download_id: id.to_string(),
                    },
                ),
            ];
            assert_eq!(expected_events, sent_events);
        }

        #[tokio::test]
        async fn download_unpack_immutable_files_sends_feedbacks_when_fails() {
            let total_immutable_files = 1;
            let immutable_file_range = ImmutableFileRange::Range(1, total_immutable_files);
            let target_dir = Path::new(".");
            let feedback_receiver = Arc::new(StackFeedbackReceiver::new());
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloaderBuilder::default().with_failure().build()),
                FeedbackSender::new(&[feedback_receiver.clone()]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_immutable_files(
                    &[ImmutablesLocation::CloudStorage {
                        uri: MultiFilesUri::Template(TemplateUri(
                            "http://whatever/{immutable_file_number}.tar.gz".to_string(),
                        )),
                    }],
                    immutable_file_range
                        .to_range_inclusive(total_immutable_files)
                        .unwrap(),
                    &CompressionAlgorithm::default(),
                    target_dir,
                    1,
                    "download_id",
                )
                .await
                .expect_err("download_unpack_immutable_files should fail");

            let sent_events = feedback_receiver.stacked_events();
            let id = sent_events[0].event_id();
            let expected_events = vec![MithrilEvent::CardanoDatabase(
                MithrilEventCardanoDatabase::ImmutableDownloadStarted {
                    immutable_file_number: 1,
                    download_id: id.to_string(),
                    size: 0,
                },
            )];
            assert_eq!(expected_events, sent_events);
        }
    }

    mod download_unpack_ancillary_file {

        use super::*;

        #[tokio::test]
        async fn download_unpack_ancillary_file_fails_if_no_location_is_retrieved() {
            let target_dir = Path::new(".");
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloaderBuilder::default().with_failure().build()),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_ancillary_file(
                    &[AncillaryLocation::CloudStorage {
                        uri: "http://whatever-1/ancillary.tar.gz".to_string(),
                    }],
                    &CompressionAlgorithm::default(),
                    target_dir,
                    "download_id",
                )
                .await
                .expect_err("download_unpack_ancillary_file should fail");
        }

        #[tokio::test]
        async fn download_unpack_ancillary_files_fails_if_location_is_unknown() {
            let target_dir = Path::new(".");
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloader::new()),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_ancillary_file(
                    &[AncillaryLocation::Unknown {}],
                    &CompressionAlgorithm::default(),
                    target_dir,
                    "download_id",
                )
                .await
                .expect_err("download_unpack_ancillary_file should fail");
        }

        #[tokio::test]
        async fn download_unpack_ancillary_file_succeeds_if_at_least_one_location_is_retrieved() {
            let target_dir = Path::new(".");
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(
                    MockFileDownloaderBuilder::default()
                        .with_file_uri("http://whatever-1/ancillary.tar.gz")
                        .with_target_dir(target_dir.to_path_buf())
                        .with_failure()
                        .next_call()
                        .with_file_uri("http://whatever-2/ancillary.tar.gz")
                        .with_target_dir(target_dir.to_path_buf())
                        .with_success()
                        .build(),
                ),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_ancillary_file(
                    &[
                        AncillaryLocation::CloudStorage {
                            uri: "http://whatever-1/ancillary.tar.gz".to_string(),
                        },
                        AncillaryLocation::CloudStorage {
                            uri: "http://whatever-2/ancillary.tar.gz".to_string(),
                        },
                    ],
                    &CompressionAlgorithm::default(),
                    target_dir,
                    "download_id",
                )
                .await
                .unwrap();
        }

        #[tokio::test]
        async fn download_unpack_ancillary_file_succeeds_when_first_location_is_retrieved() {
            let target_dir = Path::new(".");
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(
                    MockFileDownloaderBuilder::default()
                        .with_file_uri("http://whatever-1/ancillary.tar.gz")
                        .with_target_dir(target_dir.to_path_buf())
                        .with_success()
                        .build(),
                ),
                FeedbackSender::new(&[]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_ancillary_file(
                    &[
                        AncillaryLocation::CloudStorage {
                            uri: "http://whatever-1/ancillary.tar.gz".to_string(),
                        },
                        AncillaryLocation::CloudStorage {
                            uri: "http://whatever-2/ancillary.tar.gz".to_string(),
                        },
                    ],
                    &CompressionAlgorithm::default(),
                    target_dir,
                    "download_id",
                )
                .await
                .unwrap();
        }

        #[tokio::test]
        async fn download_unpack_ancillary_files_sends_feedbacks() {
            let target_dir = Path::new(".");
            let feedback_receiver = Arc::new(StackFeedbackReceiver::new());
            let artifact_downloader = InternalArtifactDownloader::new(
                Arc::new(MockFileDownloaderBuilder::default().with_success().build()),
                FeedbackSender::new(&[feedback_receiver.clone()]),
                test_utils::test_logger(),
            );

            artifact_downloader
                .download_unpack_ancillary_file(
                    &[AncillaryLocation::CloudStorage {
                        uri: "http://whatever-1/ancillary.tar.gz".to_string(),
                    }],
                    &CompressionAlgorithm::default(),
                    target_dir,
                    "download_id",
                )
                .await
                .unwrap();

            let sent_events = feedback_receiver.stacked_events();
            let id = sent_events[0].event_id();
            let expected_events = vec![
                MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::AncillaryDownloadStarted {
                        download_id: id.to_string(),
                        size: 0,
                    },
                ),
                MithrilEvent::CardanoDatabase(
                    MithrilEventCardanoDatabase::AncillaryDownloadCompleted {
                        download_id: id.to_string(),
                    },
                ),
            ];
            assert_eq!(expected_events, sent_events);
        }
    }
}