mithril_client_cli/utils/
cardano_db_download_checker.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
use std::{
    fs,
    ops::Not,
    path::{Path, PathBuf},
};

use anyhow::Context;
use human_bytes::human_bytes;
use thiserror::Error;

use mithril_client::{common::CompressionAlgorithm, MithrilError, MithrilResult};

/// Checks to apply before downloading a Cardano Db archive to a given directory.
pub struct CardanoDbDownloadChecker;

/// Errors tied with the [CardanoDbDownloadChecker].
#[derive(Debug, Error)]
pub enum CardanoDbDownloadCheckerError {
    /// Not enough space on the disk. There should be at least the ratio given for the
    /// used algorithm (see [CompressionAlgorithm::free_space_snapshot_ratio]) times
    /// the size of the archive to download to ensure it could be unpacked safely.
    #[error("There is only {} remaining in directory '{}' to store and unpack a {} large archive.", human_bytes(*left_space), pathdir.display(), human_bytes(*archive_size))]
    NotEnoughSpace {
        /// Left space on device
        left_space: f64,

        /// Specified location
        pathdir: PathBuf,

        /// Packed cardano db size
        archive_size: f64,
    },

    /// The directory where the files from cardano db are expanded is not empty.
    /// An error is raised to let the user handle what it wants to do with those
    /// files.
    #[error("Unpack directory '{0}' is not empty, please clean up its content.")]
    UnpackDirectoryNotEmpty(PathBuf),

    /// Cannot write in the given directory.
    #[error("Unpack directory '{0}' is not writable, please check own or parents' permissions and ownership.")]
    UnpackDirectoryIsNotWritable(PathBuf, #[source] MithrilError),
}

impl CardanoDbDownloadChecker {
    /// Ensure that the given path exist, create it otherwise
    pub fn ensure_dir_exist(pathdir: &Path) -> MithrilResult<()> {
        if pathdir.exists().not() {
            fs::create_dir_all(pathdir).map_err(|e| {
                CardanoDbDownloadCheckerError::UnpackDirectoryIsNotWritable(
                    pathdir.to_owned(),
                    e.into(),
                )
            })?;
        }

        Ok(())
    }

    /// Check all prerequisites are met before starting to download and unpack
    /// big cardano db archive.
    pub fn check_prerequisites(
        pathdir: &Path,
        size: u64,
        compression_algorithm: CompressionAlgorithm,
    ) -> MithrilResult<()> {
        Self::check_path_is_an_empty_dir(pathdir)?;
        Self::check_dir_writable(pathdir)?;
        Self::check_disk_space(pathdir, size, compression_algorithm)
    }

    fn check_path_is_an_empty_dir(pathdir: &Path) -> MithrilResult<()> {
        if pathdir.is_dir().not() {
            anyhow::bail!("Given path is not a directory: {}", pathdir.display());
        }

        if fs::read_dir(pathdir)
            .with_context(|| {
                format!(
                    "Could not list directory `{}` to check if it's empty",
                    pathdir.display()
                )
            })?
            .next()
            .is_some()
        {
            return Err(
                CardanoDbDownloadCheckerError::UnpackDirectoryNotEmpty(pathdir.to_owned()).into(),
            );
        }

        Ok(())
    }

    fn check_dir_writable(pathdir: &Path) -> MithrilResult<()> {
        // Check if the directory is writable by creating a temporary file
        let temp_file_path = pathdir.join("temp_file");
        fs::File::create(&temp_file_path).map_err(|e| {
            CardanoDbDownloadCheckerError::UnpackDirectoryIsNotWritable(
                pathdir.to_owned(),
                e.into(),
            )
        })?;

        // Delete the temporary file
        fs::remove_file(temp_file_path).map_err(|e| {
            CardanoDbDownloadCheckerError::UnpackDirectoryIsNotWritable(
                pathdir.to_owned(),
                e.into(),
            )
        })?;

        Ok(())
    }

    fn check_disk_space(
        pathdir: &Path,
        size: u64,
        compression_algorithm: CompressionAlgorithm,
    ) -> MithrilResult<()> {
        let free_space = fs2::available_space(pathdir)? as f64;
        if free_space < compression_algorithm.free_space_snapshot_ratio() * size as f64 {
            return Err(CardanoDbDownloadCheckerError::NotEnoughSpace {
                left_space: free_space,
                pathdir: pathdir.to_owned(),
                archive_size: size as f64,
            }
            .into());
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use mithril_common::test_utils::TempDir;

    use super::*;

    fn create_temporary_empty_directory(name: &str) -> PathBuf {
        TempDir::create("client-cli-unpacker", name)
    }

    #[test]
    fn create_directory_if_it_doesnt_exist() {
        let pathdir =
            create_temporary_empty_directory("directory_does_not_exist").join("target_directory");

        CardanoDbDownloadChecker::ensure_dir_exist(&pathdir)
            .expect("ensure_dir_exist should not fail");

        assert!(pathdir.exists());
    }

    #[test]
    fn return_error_if_path_is_a_file() {
        let pathdir =
            create_temporary_empty_directory("fail_if_pathdir_is_file").join("target_directory");
        fs::File::create(&pathdir).unwrap();

        CardanoDbDownloadChecker::check_prerequisites(
            &pathdir,
            12,
            CompressionAlgorithm::default(),
        )
        .expect_err("check_prerequisites should fail");
    }

    #[test]
    fn return_ok_if_unpack_directory_exist_and_empty() {
        let pathdir =
            create_temporary_empty_directory("existing_directory").join("target_directory");
        fs::create_dir_all(&pathdir).unwrap();

        CardanoDbDownloadChecker::check_prerequisites(
            &pathdir,
            12,
            CompressionAlgorithm::default(),
        )
        .expect("check_prerequisites should not fail");
    }

    #[test]
    fn return_error_if_unpack_directory_exists_and_not_empty() {
        let pathdir = create_temporary_empty_directory("existing_directory_not_empty");
        fs::create_dir_all(&pathdir).unwrap();
        fs::File::create(pathdir.join("file.txt")).unwrap();

        let error = CardanoDbDownloadChecker::check_prerequisites(
            &pathdir,
            12,
            CompressionAlgorithm::default(),
        )
        .expect_err("check_prerequisites should fail");

        assert!(
            matches!(
                error.downcast_ref::<CardanoDbDownloadCheckerError>(),
                Some(CardanoDbDownloadCheckerError::UnpackDirectoryNotEmpty(_))
            ),
            "Unexpected error: {:?}",
            error
        );
    }

    #[test]
    fn return_error_if_not_enough_available_space() {
        let pathdir =
            create_temporary_empty_directory("enough_available_space").join("target_directory");
        fs::create_dir_all(&pathdir).unwrap();
        let archive_size = u64::MAX;

        let error = CardanoDbDownloadChecker::check_prerequisites(
            &pathdir,
            archive_size,
            CompressionAlgorithm::default(),
        )
        .expect_err("check_prerequisites should fail");

        assert!(
            matches!(
                error.downcast_ref::<CardanoDbDownloadCheckerError>(),
                Some(CardanoDbDownloadCheckerError::NotEnoughSpace {
                    left_space: _,
                    pathdir: _,
                    archive_size: _
                })
            ),
            "Unexpected error: {:?}",
            error
        );
    }

    // Those test are not on Windows because `set_readonly` is ignored for directories on Windows 7+
    // https://doc.rust-lang.org/std/fs/struct.Permissions.html#method.set_readonly
    #[cfg(not(target_os = "windows"))]
    mod unix_only {
        use super::*;

        fn make_readonly(path: &Path) {
            let mut perms = fs::metadata(path).unwrap().permissions();
            perms.set_readonly(true);
            fs::set_permissions(path, perms).unwrap();
        }

        #[test]
        fn return_error_if_directory_could_not_be_created() {
            let pathdir = create_temporary_empty_directory("read_only_directory");
            let targetdir = pathdir.join("target_directory");
            make_readonly(&pathdir);

            let error = CardanoDbDownloadChecker::ensure_dir_exist(&targetdir)
                .expect_err("ensure_dir_exist should fail");

            assert!(
                matches!(
                    error.downcast_ref::<CardanoDbDownloadCheckerError>(),
                    Some(CardanoDbDownloadCheckerError::UnpackDirectoryIsNotWritable(
                        _,
                        _
                    ))
                ),
                "Unexpected error: {:?}",
                error
            );
        }

        // This test is not run on Windows because `set_readonly` is ignored for directory on Windows 7+
        // https://doc.rust-lang.org/std/fs/struct.Permissions.html#method.set_readonly
        #[test]
        fn return_error_if_existing_directory_is_not_writable() {
            let pathdir =
                create_temporary_empty_directory("existing_directory_not_writable").join("db");
            fs::create_dir(&pathdir).unwrap();
            make_readonly(&pathdir);

            let error = CardanoDbDownloadChecker::check_prerequisites(
                &pathdir,
                12,
                CompressionAlgorithm::default(),
            )
            .expect_err("check_prerequisites should fail");

            assert!(
                matches!(
                    error.downcast_ref::<CardanoDbDownloadCheckerError>(),
                    Some(CardanoDbDownloadCheckerError::UnpackDirectoryIsNotWritable(
                        _,
                        _
                    ))
                ),
                "Unexpected error: {:?}",
                error
            );
        }
    }
}