Skip to content

Commit 12f65cf

Browse files
authored
Merge pull request #1172 from input-output-hk/ensemble/1095/client-snapshot-download-progress-with-json-output
Client snapshot download progress with json output
2 parents bfe3867 + e9dc557 commit 12f65cf

File tree

8 files changed

+176
-39
lines changed

8 files changed

+176
-39
lines changed

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mithril-client/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "mithril-client"
3-
version = "0.3.34"
3+
version = "0.3.35"
44
description = "A Mithril Client"
55
authors = { workspace = true }
66
edition = { workspace = true }

mithril-client/src/aggregator_client/http_client.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
use std::{path::Path, sync::Arc};
2-
31
use async_recursion::async_recursion;
42
use async_trait::async_trait;
53
use futures::StreamExt;
6-
use indicatif::ProgressBar;
74
use reqwest::{Client, Response, StatusCode};
85
use semver::Version;
96
use slog_scope::debug;
7+
use std::{path::Path, sync::Arc};
108
use thiserror::Error;
119
use tokio::{fs, io::AsyncWriteExt, sync::RwLock};
1210

@@ -15,6 +13,8 @@ use mockall::automock;
1513

1614
use mithril_common::{StdError, MITHRIL_API_VERSION_HEADER};
1715

16+
use crate::utils::DownloadProgressReporter;
17+
1818
/// Error tied with the Aggregator client
1919
#[derive(Error, Debug)]
2020
pub enum AggregatorHTTPClientError {
@@ -56,7 +56,7 @@ pub trait AggregatorClient: Sync + Send {
5656
&self,
5757
url: &str,
5858
filepath: &Path,
59-
progress_bar: ProgressBar,
59+
progress_reporter: DownloadProgressReporter,
6060
) -> Result<(), AggregatorHTTPClientError>;
6161

6262
/// Test if the given URL points to a valid location & existing content.
@@ -183,7 +183,7 @@ impl AggregatorClient for AggregatorHTTPClient {
183183
&self,
184184
url: &str,
185185
filepath: &Path,
186-
progress_bar: ProgressBar,
186+
progress_reporter: DownloadProgressReporter,
187187
) -> Result<(), AggregatorHTTPClientError> {
188188
let response = self.get(url).await?;
189189
let mut local_file = fs::File::create(filepath).await.map_err(|e| {
@@ -215,7 +215,7 @@ impl AggregatorClient for AggregatorHTTPClient {
215215
}
216216
})?;
217217
downloaded_bytes += chunk.len() as u64;
218-
progress_bar.set_position(downloaded_bytes);
218+
progress_reporter.report(downloaded_bytes);
219219
}
220220

221221
Ok(())

mithril-client/src/aggregator_client/snapshot_client.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
//! This module contains a struct to exchange snapshot information with the Aggregator
22
3+
use slog_scope::warn;
34
use std::{
45
path::{Path, PathBuf},
56
sync::Arc,
67
};
8+
use thiserror::Error;
79

8-
use indicatif::ProgressBar;
910
use mithril_common::{
1011
entities::Snapshot,
1112
messages::{SnapshotListItemMessage, SnapshotListMessage, SnapshotMessage},
1213
StdResult,
1314
};
14-
use slog_scope::warn;
15-
use thiserror::Error;
1615

17-
use super::AggregatorClient;
16+
use crate::aggregator_client::AggregatorClient;
17+
use crate::utils::DownloadProgressReporter;
1818

1919
/// Error for the Snapshot client
2020
#[derive(Error, Debug)]
@@ -64,7 +64,7 @@ impl SnapshotClient {
6464
&self,
6565
snapshot: &Snapshot,
6666
download_dir: &Path,
67-
progress_bar: ProgressBar,
67+
progress_reporter: DownloadProgressReporter,
6868
) -> StdResult<PathBuf> {
6969
let filepath = PathBuf::new()
7070
.join(download_dir)
@@ -74,7 +74,7 @@ impl SnapshotClient {
7474
if self.http_client.probe(url).await.is_ok() {
7575
match self
7676
.http_client
77-
.download(url, &filepath, progress_bar)
77+
.download(url, &filepath, progress_reporter)
7878
.await
7979
{
8080
Ok(()) => return Ok(filepath),

mithril-client/src/commands/snapshot/download.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
use std::{path::PathBuf, sync::Arc};
2-
31
use clap::Parser;
42
use config::{builder::DefaultState, Config, ConfigBuilder};
5-
use indicatif::ProgressDrawTarget;
3+
use std::{path::PathBuf, sync::Arc};
4+
65
use mithril_common::{messages::FromMessageAdapter, StdResult};
76

8-
use crate::{dependencies::DependenciesBuilder, FromSnapshotMessageAdapter};
7+
use crate::{
8+
dependencies::DependenciesBuilder, utils::ProgressOutputType, FromSnapshotMessageAdapter,
9+
};
910

1011
/// Clap command to download the snapshot and verify the certificate.
1112
#[derive(Parser, Debug, Clone)]
@@ -36,17 +37,17 @@ impl SnapshotDownloadCommand {
3637
let snapshot_service = dependencies_builder.get_snapshot_service().await?;
3738
let snapshot_entity =
3839
FromSnapshotMessageAdapter::adapt(snapshot_service.show(&self.digest).await?);
39-
let progress_target = if self.json {
40-
ProgressDrawTarget::hidden()
40+
let progress_output_type = if self.json {
41+
ProgressOutputType::JsonReporter
4142
} else {
42-
ProgressDrawTarget::stdout()
43+
ProgressOutputType::TTY
4344
};
4445
let filepath = snapshot_service
4546
.download(
4647
&snapshot_entity,
4748
&self.download_dir,
4849
&config.get_string("genesis_verification_key")?,
49-
progress_target,
50+
progress_output_type,
5051
)
5152
.await?;
5253

mithril-client/src/services/snapshot.rs

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use anyhow::Context;
22
use async_trait::async_trait;
33
use futures::Future;
4-
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressState, ProgressStyle};
4+
use indicatif::{MultiProgress, ProgressBar, ProgressState, ProgressStyle};
55
use slog_scope::{debug, warn};
66
use std::{
77
fmt::Write,
@@ -24,7 +24,10 @@ use mithril_common::{
2424

2525
use crate::{
2626
aggregator_client::{AggregatorHTTPClientError, CertificateClient, SnapshotClient},
27-
utils::{SnapshotUnpacker, SnapshotUnpackerError},
27+
utils::{
28+
DownloadProgressReporter, ProgressOutputType, ProgressPrinter, SnapshotUnpacker,
29+
SnapshotUnpackerError,
30+
},
2831
};
2932

3033
/// [SnapshotService] related errors.
@@ -72,7 +75,7 @@ pub trait SnapshotService: Sync + Send {
7275
snapshot_entity: &SignedEntity<Snapshot>,
7376
pathdir: &Path,
7477
genesis_verification_key: &str,
75-
progress_target: ProgressDrawTarget,
78+
progress_output_type: ProgressOutputType,
7679
) -> StdResult<PathBuf>;
7780
}
7881

@@ -210,20 +213,20 @@ impl SnapshotService for MithrilClientSnapshotService {
210213
snapshot_entity: &SignedEntity<Snapshot>,
211214
download_dir: &Path,
212215
genesis_verification_key: &str,
213-
progress_target: ProgressDrawTarget,
216+
progress_output_type: ProgressOutputType,
214217
) -> StdResult<PathBuf> {
215218
debug!("Snapshot service: download.");
216219

217220
let db_dir = download_dir.join("db");
218-
let progress_bar = MultiProgress::with_draw_target(progress_target);
219-
progress_bar.println("1/7 - Checking local disk info…")?;
221+
let progress_bar = ProgressPrinter::new(progress_output_type, 7);
222+
progress_bar.report_step(1, "Checking local disk info…")?;
220223
let unpacker = SnapshotUnpacker;
221224

222225
if let Err(e) = unpacker.check_prerequisites(&db_dir, snapshot_entity.artifact.size) {
223226
self.check_disk_space_error(e)?;
224227
}
225228

226-
progress_bar.println("2/7 - Fetching the certificate's information…")?;
229+
progress_bar.report_step(2, "Fetching the certificate's information…")?;
227230
let certificate = self
228231
.certificate_client
229232
.get(&snapshot_entity.certificate_id)
@@ -234,23 +237,27 @@ impl SnapshotService for MithrilClientSnapshotService {
234237
)
235238
})?;
236239

237-
progress_bar.println("3/7 - Verifying the certificate chain…")?;
240+
progress_bar.report_step(3, "Verifying the certificate chain…")?;
238241
let verifier = self.verify_certificate_chain(genesis_verification_key, &certificate);
239242
self.wait_spinner(&progress_bar, verifier).await?;
240243

241-
progress_bar.println("4/7 - Downloading the snapshot…")?;
244+
progress_bar.report_step(4, "Downloading the snapshot…")?;
242245
let pb = progress_bar.add(ProgressBar::new(snapshot_entity.artifact.size));
243246
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
244247
.unwrap()
245248
.with_key("eta", |state: &ProgressState, w: &mut dyn Write| write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap())
246249
.progress_chars("#>-"));
247250
let snapshot_path = self
248251
.snapshot_client
249-
.download(&snapshot_entity.artifact, download_dir, pb)
252+
.download(
253+
&snapshot_entity.artifact,
254+
download_dir,
255+
DownloadProgressReporter::new(pb, progress_output_type),
256+
)
250257
.await
251258
.with_context(|| format!("Could not download file in '{}'", download_dir.display()))?;
252259

253-
progress_bar.println("5/7 - Unpacking the snapshot…")?;
260+
progress_bar.report_step(5, "Unpacking the snapshot…")?;
254261
let unpacker = unpacker.unpack_snapshot(&snapshot_path, &db_dir);
255262
self.wait_spinner(&progress_bar, unpacker).await?;
256263

@@ -262,14 +269,14 @@ impl SnapshotService for MithrilClientSnapshotService {
262269
);
263270
};
264271

265-
progress_bar.println("6/7 - Computing the snapshot digest…")?;
272+
progress_bar.report_step(6, "Computing the snapshot digest…")?;
266273
let unpacked_snapshot_digest = self
267274
.immutable_digester
268275
.compute_digest(&db_dir, &certificate.beacon)
269276
.await
270277
.with_context(|| format!("Could not compute digest in '{}'", db_dir.display()))?;
271278

272-
progress_bar.println("7/7 - Verifying the snapshot signature…")?;
279+
progress_bar.report_step(7, "Verifying the snapshot signature…")?;
273280
let expected_message = {
274281
let mut protocol_message = certificate.protocol_message.clone();
275282
protocol_message.set_message_part(
@@ -550,7 +557,7 @@ mod tests {
550557
&snapshot,
551558
&test_path,
552559
&genesis_verification_key.to_json_hex().unwrap(),
553-
ProgressDrawTarget::hidden(),
560+
ProgressOutputType::Hidden,
554561
)
555562
.await
556563
.expect("Snapshot download should succeed.");
@@ -590,7 +597,7 @@ mod tests {
590597
&snapshot,
591598
&test_path,
592599
&genesis_verification_key.to_json_hex().unwrap(),
593-
ProgressDrawTarget::hidden(),
600+
ProgressOutputType::Hidden,
594601
)
595602
.await
596603
.expect("Snapshot download should succeed.");
@@ -636,7 +643,7 @@ mod tests {
636643
&signed_entity,
637644
&test_path,
638645
&genesis_verification_key.to_json_hex().unwrap(),
639-
ProgressDrawTarget::hidden(),
646+
ProgressOutputType::Hidden,
640647
)
641648
.await
642649
.expect_err("Snapshot digest comparison should fail.");
@@ -684,7 +691,7 @@ mod tests {
684691
&snapshot,
685692
&test_path,
686693
&genesis_verification_key.to_json_hex().unwrap(),
687-
ProgressDrawTarget::hidden(),
694+
ProgressOutputType::Hidden,
688695
)
689696
.await
690697
.expect_err("Snapshot download should fail.");

mithril-client/src/utils/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
//! Utilities module
22
//! This module contains tools needed mostly in services layers.
33
4+
mod progress_reporter;
45
mod unpacker;
56

7+
pub use progress_reporter::*;
68
pub use unpacker::*;

0 commit comments

Comments
 (0)