mithril_aggregator/artifact_builder/
cardano_immutable_files_full.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
use anyhow::Context;
use async_trait::async_trait;
use semver::Version;
use slog::{debug, warn, Logger};
use std::path::Path;
use std::sync::Arc;
use thiserror::Error;

use crate::{file_uploaders::FileUri, snapshotter::OngoingSnapshot, FileUploader, Snapshotter};

use super::ArtifactBuilder;
use mithril_common::logging::LoggerExtensions;
use mithril_common::{
    entities::{
        CardanoDbBeacon, Certificate, CompressionAlgorithm, ProtocolMessagePartKey, Snapshot,
    },
    CardanoNetwork, StdResult,
};

/// [CardanoImmutableFilesFullArtifact] error
/// to fail.
#[derive(Debug, Error)]
pub enum CardanoImmutableFilesFullArtifactError {
    /// Protocol message part is missing
    #[error("Missing protocol message for beacon: '{0}'.")]
    MissingProtocolMessage(CardanoDbBeacon),
}

/// A [CardanoImmutableFilesFullArtifact] builder
pub struct CardanoImmutableFilesFullArtifactBuilder {
    cardano_network: CardanoNetwork,
    cardano_node_version: Version,
    snapshotter: Arc<dyn Snapshotter>,
    snapshot_uploader: Arc<dyn FileUploader>,
    compression_algorithm: CompressionAlgorithm,
    logger: Logger,
}

impl CardanoImmutableFilesFullArtifactBuilder {
    /// CardanoImmutableFilesFull artifact builder factory
    pub fn new(
        cardano_network: CardanoNetwork,
        cardano_node_version: &Version,
        snapshotter: Arc<dyn Snapshotter>,
        snapshot_uploader: Arc<dyn FileUploader>,
        compression_algorithm: CompressionAlgorithm,
        logger: Logger,
    ) -> Self {
        Self {
            cardano_network,
            cardano_node_version: cardano_node_version.clone(),
            snapshotter,
            snapshot_uploader,
            compression_algorithm,
            logger: logger.new_with_component_name::<Self>(),
        }
    }

    async fn create_snapshot_archive(
        &self,
        beacon: &CardanoDbBeacon,
        snapshot_digest: &str,
    ) -> StdResult<OngoingSnapshot> {
        debug!(self.logger, ">> create_snapshot_archive");

        let snapshotter = self.snapshotter.clone();
        let snapshot_name = format!(
            "{}-e{}-i{}.{}.{}",
            self.cardano_network,
            *beacon.epoch,
            beacon.immutable_file_number,
            snapshot_digest,
            self.compression_algorithm.tar_file_extension()
        );
        // spawn a separate thread to prevent blocking
        let ongoing_snapshot =
            tokio::task::spawn_blocking(move || -> StdResult<OngoingSnapshot> {
                snapshotter.snapshot_all(Path::new(&snapshot_name))
            })
            .await??;

        debug!(self.logger, " > Snapshot created: '{ongoing_snapshot:?}'");

        Ok(ongoing_snapshot)
    }

    async fn upload_snapshot_archive(
        &self,
        ongoing_snapshot: &OngoingSnapshot,
    ) -> StdResult<Vec<FileUri>> {
        debug!(self.logger, ">> upload_snapshot_archive");
        let location = self
            .snapshot_uploader
            .upload(ongoing_snapshot.get_file_path())
            .await;

        if let Err(error) = tokio::fs::remove_file(ongoing_snapshot.get_file_path()).await {
            warn!(
                self.logger, " > Post upload ongoing snapshot file removal failure";
                "error" => error
            );
        }

        Ok(vec![location?])
    }

    async fn create_snapshot(
        &self,
        beacon: CardanoDbBeacon,
        ongoing_snapshot: &OngoingSnapshot,
        snapshot_digest: String,
        remote_locations: Vec<String>,
    ) -> StdResult<Snapshot> {
        debug!(self.logger, ">> create_snapshot");

        let snapshot = Snapshot::new(
            snapshot_digest,
            self.cardano_network,
            beacon,
            *ongoing_snapshot.get_file_size(),
            remote_locations,
            self.compression_algorithm,
            &self.cardano_node_version,
        );

        Ok(snapshot)
    }
}

#[async_trait]
impl ArtifactBuilder<CardanoDbBeacon, Snapshot> for CardanoImmutableFilesFullArtifactBuilder {
    async fn compute_artifact(
        &self,
        beacon: CardanoDbBeacon,
        certificate: &Certificate,
    ) -> StdResult<Snapshot> {
        let snapshot_digest = certificate
            .protocol_message
            .get_message_part(&ProtocolMessagePartKey::SnapshotDigest)
            .ok_or_else(|| {
                CardanoImmutableFilesFullArtifactError::MissingProtocolMessage(beacon.clone())
            })?
            .to_owned();

        let ongoing_snapshot = self
            .create_snapshot_archive(&beacon, &snapshot_digest)
            .await
            .with_context(|| {
                "Cardano Immutable Files Full Artifact Builder can not create snapshot archive"
            })?;
        let locations = self
            .upload_snapshot_archive(&ongoing_snapshot)
            .await
            .with_context(|| {
                format!("Cardano Immutable Files Full Artifact Builder can not upload snapshot archive to path: '{:?}'", ongoing_snapshot.get_file_path())
            })?;

        let snapshot = self
            .create_snapshot(
                beacon,
                &ongoing_snapshot,
                snapshot_digest,
                locations.into_iter().map(Into::into).collect(),
            )
            .await?;

        Ok(snapshot)
    }
}

#[cfg(test)]
mod tests {
    use anyhow::anyhow;
    use std::path::Path;
    use tempfile::NamedTempFile;

    use mithril_common::{entities::CompressionAlgorithm, test_utils::fake_data};

    use crate::{
        file_uploaders::MockFileUploader, test_tools::TestLogger, DumbSnapshotter, DumbUploader,
    };

    use super::*;

    #[tokio::test]
    async fn should_compute_valid_artifact() {
        let beacon = fake_data::beacon();
        let certificate = fake_data::certificate("certificate-123".to_string());
        let snapshot_digest = certificate
            .protocol_message
            .get_message_part(&ProtocolMessagePartKey::SnapshotDigest)
            .unwrap();

        let dumb_snapshotter = Arc::new(DumbSnapshotter::new());
        let dumb_snapshot_uploader = Arc::new(DumbUploader::new());

        let cardano_immutable_files_full_artifact_builder =
            CardanoImmutableFilesFullArtifactBuilder::new(
                fake_data::network(),
                &Version::parse("1.0.0").unwrap(),
                dumb_snapshotter.clone(),
                dumb_snapshot_uploader.clone(),
                CompressionAlgorithm::Zstandard,
                TestLogger::stdout(),
            );
        let artifact = cardano_immutable_files_full_artifact_builder
            .compute_artifact(beacon.clone(), &certificate)
            .await
            .unwrap();
        let last_ongoing_snapshot = dumb_snapshotter
            .get_last_snapshot()
            .unwrap()
            .expect("A snapshot should have been 'created'");

        let remote_locations = vec![dumb_snapshot_uploader
            .get_last_upload()
            .unwrap()
            .map(Into::into)
            .expect("A snapshot should have been 'uploaded'")];
        let artifact_expected = Snapshot::new(
            snapshot_digest.to_owned(),
            fake_data::network(),
            beacon,
            *last_ongoing_snapshot.get_file_size(),
            remote_locations,
            CompressionAlgorithm::Zstandard,
            &Version::parse("1.0.0").unwrap(),
        );
        assert_eq!(artifact_expected, artifact);
    }

    #[tokio::test]
    async fn remove_snapshot_archive_after_upload() {
        let file = NamedTempFile::new().unwrap();
        let file_path = file.path();
        let snapshot = OngoingSnapshot::new(file_path.to_path_buf(), 7331);

        let cardano_immutable_files_full_artifact_builder =
            CardanoImmutableFilesFullArtifactBuilder::new(
                fake_data::network(),
                &Version::parse("1.0.0").unwrap(),
                Arc::new(DumbSnapshotter::new()),
                Arc::new(DumbUploader::new()),
                CompressionAlgorithm::default(),
                TestLogger::stdout(),
            );

        cardano_immutable_files_full_artifact_builder
            .upload_snapshot_archive(&snapshot)
            .await
            .expect("Snapshot upload should not fail");

        assert!(
            !file_path.exists(),
            "Ongoing snapshot file should have been removed after upload"
        );
    }

    #[tokio::test]
    async fn snapshot_archive_name_after_beacon_values() {
        let network = fake_data::network();
        let beacon = CardanoDbBeacon::new(20, 145);
        let digest = "test+digest";

        let cardano_immutable_files_full_artifact_builder =
            CardanoImmutableFilesFullArtifactBuilder::new(
                network,
                &Version::parse("1.0.0").unwrap(),
                Arc::new(DumbSnapshotter::new()),
                Arc::new(DumbUploader::new()),
                CompressionAlgorithm::Gzip,
                TestLogger::stdout(),
            );

        let ongoing_snapshot = cardano_immutable_files_full_artifact_builder
            .create_snapshot_archive(&beacon, digest)
            .await
            .expect("create_snapshot_archive should not fail");

        assert_eq!(
            Path::new(&format!(
                "{}-e{}-i{}.{digest}.tar.gz",
                network, *beacon.epoch, beacon.immutable_file_number,
            )),
            ongoing_snapshot.get_file_path()
        );
    }

    #[tokio::test]
    async fn snapshot_archive_name_after_compression_algorithm() {
        let mut invalid_result: Vec<CompressionAlgorithm> = vec![];

        for algorithm in CompressionAlgorithm::list() {
            let cardano_immutable_files_full_artifact_builder =
                CardanoImmutableFilesFullArtifactBuilder::new(
                    fake_data::network(),
                    &Version::parse("1.0.0").unwrap(),
                    Arc::new(DumbSnapshotter::new()),
                    Arc::new(DumbUploader::new()),
                    algorithm,
                    TestLogger::stdout(),
                );

            let ongoing_snapshot = cardano_immutable_files_full_artifact_builder
                .create_snapshot_archive(&CardanoDbBeacon::default(), "test+digest")
                .await
                .expect("create_snapshot_archive should not fail");
            let file_name = ongoing_snapshot
                .get_file_path()
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap();
            let expected_extension = algorithm.tar_file_extension();

            if !file_name.ends_with(&expected_extension) {
                invalid_result.push(algorithm);
            }
        }

        assert!(
            invalid_result.is_empty(),
            "Archive name did not contain some algorithms extension after snapshot, failing algorithm(s): {invalid_result:?}",
        );
    }

    #[tokio::test]
    async fn remove_snapshot_archive_after_upload_even_if_an_error_occurred() {
        let file = NamedTempFile::new().unwrap();
        let file_path = file.path();
        let snapshot = OngoingSnapshot::new(file_path.to_path_buf(), 7331);
        let mut snapshot_uploader = MockFileUploader::new();
        snapshot_uploader
            .expect_upload()
            .return_once(|_| Err(anyhow!("an error")))
            .once();

        let cardano_immutable_files_full_artifact_builder =
            CardanoImmutableFilesFullArtifactBuilder::new(
                fake_data::network(),
                &Version::parse("1.0.0").unwrap(),
                Arc::new(DumbSnapshotter::new()),
                Arc::new(snapshot_uploader),
                CompressionAlgorithm::default(),
                TestLogger::stdout(),
            );

        cardano_immutable_files_full_artifact_builder
            .upload_snapshot_archive(&snapshot)
            .await
            .expect_err("Snapshot upload should have failed");

        assert!(
            !file_path.exists(),
            "Ongoing snapshot file should have been removed even after upload failure"
        );
    }
}