Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add better download and sync status reporting #40

Merged
merged 7 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ async-trait = "0.1.81"
sysinfo = "0.31.2"
log4rs = "1.3.0"
keyring = "3.0.5"
nix = {version ="0.29.0", features = ["signal"] }
nix = { version = "0.29.0", features = ["signal"] }
# static bind lzma
xz2 = { version = "0.1.7", features = ["static"] }
humantime = "2.1.0"

# needed for keymanager. TODO: Find a way of creating a keymanager without bundling sqlite
libsqlite3-sys = { version = "0.25.1", features = ["bundled"] }
Expand Down
52 changes: 29 additions & 23 deletions src-tauri/src/binary_resolver.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
use crate::download_utils::{download_file, extract};
use crate::{github, SetupStatusEvent};
use crate::{github, ProgressTracker};
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use log::{error, info, warn};
use log::{info, warn};
use semver::Version;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use tauri::api::path::cache_dir;
use tokio::fs;
use tokio::sync::Mutex;
use tokio::sync::{Mutex, RwLock};

const LOG_TARGET: &str = "tari::universe::binary_resolver";
static INSTANCE: LazyLock<BinaryResolver> = LazyLock::new(|| BinaryResolver::new());

pub struct BinaryResolver {
download_mutex: Mutex<()>,
adapters: HashMap<Binaries, Box<dyn LatestVersionApiAdapter>>,
latest_versions: Arc<RwLock<HashMap<Binaries, Version>>>,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -161,21 +165,24 @@ impl BinaryResolver {
Self {
adapters,
download_mutex: Mutex::new(()),
latest_versions: Arc::new(RwLock::new(HashMap::new())),
}
}

pub fn current() -> Self {
Self::new()
pub fn current() -> &'static Self {
&*INSTANCE
}
pub fn resolve_path(
&self,
binary: Binaries,
version: &Version,
) -> Result<PathBuf, anyhow::Error> {

pub async fn resolve_path(&self, binary: Binaries) -> Result<PathBuf, anyhow::Error> {
dbg!(&self.latest_versions);
let adapter = self
.adapters
.get(&binary)
.ok_or_else(|| anyhow!("No latest version adapter for this binary"))?;
let guard = self.latest_versions.read().await;
let version = guard
.get(&binary)
.ok_or_else(|| anyhow!("No latest version found for binary {}", binary.name()))?;
let base_dir = adapter.get_binary_folder().join(&version.to_string());
match binary {
Binaries::Xmrig => {
Expand All @@ -200,31 +207,30 @@ impl BinaryResolver {
pub async fn ensure_latest(
&self,
binary: Binaries,
window: tauri::Window,
progress_tracker: ProgressTracker,
) -> Result<Version, anyhow::Error> {
let version = self.ensure_latest_inner(binary, false, window).await?;
let version = self
.ensure_latest_inner(binary, false, progress_tracker)
.await?;
self.latest_versions
.write()
.await
.insert(binary, version.clone());
info!(target: LOG_TARGET, "Latest version of {} is {}", binary.name(), version);
Ok(version)
}

async fn ensure_latest_inner(
&self,
binary: Binaries,
force_download: bool,
window: tauri::Window,
progress_tracker: ProgressTracker,
) -> Result<Version, Error> {
let adapter = self
.adapters
.get(&binary)
.ok_or_else(|| anyhow!("No latest version adapter for this binary"))?;
let name = binary.name();
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: format!("Fetching latest version of {}", name),
progress: 0.2,
},
);
let latest_release = adapter.fetch_latest_release().await?;
// TODO: validate that version doesn't have any ".." or "/" in it

Expand Down Expand Up @@ -259,7 +265,7 @@ impl BinaryResolver {
info!(target: LOG_TARGET, "Downloading file from {}", &asset.url);
//
let in_progress_file = in_progress_dir.join(&asset.name);
download_file(&asset.url, &in_progress_file, window).await?;
download_file(&asset.url, &in_progress_file, progress_tracker).await?;
info!(target: LOG_TARGET, "Renaming file");
info!(target: LOG_TARGET, "Extracting file");
let bin_dir = adapter
Expand All @@ -273,7 +279,7 @@ impl BinaryResolver {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Binaries {
Xmrig,
MergeMiningProxy,
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/src/cpu_miner.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::app_config::MiningMode;
use crate::mm_proxy_manager::MmProxyManager;
use crate::xmrig::http_api::XmrigHttpApiClient;
use crate::xmrig_adapter::{XmrigAdapter, XmrigNodeConnection};
use crate::{
CpuMinerConfig, CpuMinerConnection, CpuMinerConnectionStatus, CpuMinerStatus, MiningMode,
CpuMinerConfig, CpuMinerConnection, CpuMinerConnectionStatus, CpuMinerStatus, ProgressTracker,
};
use log::warn;
use std::path::PathBuf;
Expand Down Expand Up @@ -44,7 +45,7 @@ impl CpuMiner {
base_path: PathBuf,
cache_dir: PathBuf,
log_dir: PathBuf,
window: tauri::Window,
progress_tracker: ProgressTracker,
mode: MiningMode,
) -> Result<(), anyhow::Error> {
if self.watcher_task.is_some() {
Expand All @@ -61,7 +62,6 @@ impl CpuMiner {
app_shutdown.clone(),
base_path.clone(),
cpu_miner_config.tari_address.clone(),
window.clone(),
)
.await?;
local_mm_proxy.wait_ready().await?;
Expand All @@ -82,7 +82,7 @@ impl CpuMiner {
cache_dir,
log_dir,
base_path,
window.clone(),
progress_tracker,
cpu_max_percentage,
)?;
self.api_client = Some(client);
Expand Down
29 changes: 10 additions & 19 deletions src-tauri/src/download_utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const LOG_TARGET: &str = "tari::universe::download_utils";

pub async fn download_file(
url: &str,
destination: &Path,
window: tauri::Window,
progress_tracker: ProgressTracker,
) -> Result<(), anyhow::Error> {
println!("Downloading {} to {:?}", url, destination);
let response = reqwest::get(url).await?;
Expand All @@ -18,26 +20,14 @@ pub async fn download_file(
// Stream the response body directly to the file
let mut stream = response.bytes_stream();
while let Some(item) = stream.next().await {
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Downloading".to_string(),
progress: 0.4,
},
);
let _ = progress_tracker.update("Downloading".to_string(), 10).await;
dest.write_all(&item?).await?;
}

let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Downloaded".to_string(),
progress: 0.4,
},
);
println!("Done downloading");
progress_tracker
.update("Download completed".to_string(), 100)
.await;
info!(target: LOG_TARGET, "Done downloading");

Ok(())
}
Expand Down Expand Up @@ -72,11 +62,12 @@ pub async fn extract_gz(gz_path: &Path, dest_dir: &Path) -> std::io::Result<()>
Ok(())
}

use crate::SetupStatusEvent;
use crate::ProgressTracker;
use anyhow::anyhow;
use async_zip::base::read::seek::ZipFileReader;
use flate2::read::GzDecoder;
use futures_util::StreamExt;
use log::info;
use std::path::{Path, PathBuf};
use tar::Archive;
use tokio::fs;
Expand Down
Loading