Certainly! Let's improve and optimize both your Rust backend code and your React frontend code. Here are the enhanced versions along with explanations of the improvements made.
Improved Rust Code (Tauri v2)
rust
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tauri::{AppHandle, Manager};
use reqwest::Client;
use tokio::fs as tokio_fs;
use tokio::io::{self, AsyncWriteExt, BufWriter};
use std::time::{Duration, Instant};
use futures_util::StreamExt;
use thiserror::Error;
#[derive(Debug, Deserialize)]
struct PatchEntry {
file_name: String,
}
#[derive(Debug, Serialize, Clone)]
struct DownloadMessage {
message: String,
}
#[derive(Debug, Serialize, Clone)]
struct DownloadInfo {
current_file: usize,
total_files: usize,
file_name: String,
downloaded_bytes: u64,
total_bytes: u64,
}
#[derive(Error, Debug)]
enum DownloadError {
#[error("I/O error")]
Io(#[from] io::Error),
#[error("HTTP error")]
Http(#[from] reqwest::Error),
#[error("Serialization error")]
Serde(#[from] serde_json::Error),
#[error("{0}")]
Custom(String),
}
fn get_exe_dir() -> Result<PathBuf, DownloadError> {
let exe_path = std::env::current_exe()
.map_err(|e| DownloadError::Custom(format!("Failed to get current exe: {}", e)))?;
let exe_dir = exe_path
.parent()
.ok_or_else(|| DownloadError::Custom("Failed to get parent directory".into()))?
.to_path_buf();
Ok(exe_dir)
}
async fn read_patch_file(path: &Path) -> Result<Vec<PatchEntry>, DownloadError> {
let content = tokio_fs::read_to_string(path).await?;
let patches: Vec<PatchEntry> = serde_json::from_str(&content)?;
Ok(patches)
}
async fn download_file(
app_handle: &AppHandle,
client: &Client,
entry: &PatchEntry,
download_dir: &Path,
current_file: usize,
total_files: usize,
) -> Result<(), DownloadError> {
let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name);
let file_path = download_dir.join(&entry.file_name);
// Ensure the parent directory exists
if let Some(parent_dir) = file_path.parent() {
tokio_fs::create_dir_all(parent_dir).await?;
} else {
return Err(DownloadError::Custom("Failed to get parent directory".into()));
}
let response = client.get(&url).send().await?;
if !response.status().is_success() {
return Err(DownloadError::Custom(format!(
"Failed to download {}: HTTP {}",
entry.file_name,
response.status()
)));
}
let total_bytes = response.content_length().unwrap_or(0);
let file = tokio_fs::OpenOptions::new()
.write(true)
.create(true)
.open(&file_path)
.await?;
let mut writer = BufWriter::new(file);
let mut downloaded_bytes = 0u64;
let start_time = Instant::now();
let mut last_emit_time = Instant::now();
app_handle.emit_all("download_message", DownloadMessage {
message: format!("Baixando {}", entry.file_name),
})?;
// Use stream to download in chunks
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
writer.write_all(&chunk).await?;
downloaded_bytes += chunk.len() as u64;
let now = Instant::now();
if now.duration_since(last_emit_time) >= Duration::from_millis(500) {
let elapsed_time = now.duration_since(start_time).as_secs_f64();
let speed = if elapsed_time > 0.0 {
downloaded_bytes as f64 / elapsed_time
} else {
0.0
};
app_handle.emit_all("download_info", DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
})?;
app_handle.emit_all("download_speed", speed)?;
last_emit_time = now;
}
}
// Final flush and emit
writer.flush().await?;
let total_elapsed_time = Instant::now().duration_since(start_time).as_secs_f64();
let average_speed = if total_elapsed_time > 0.0 {
downloaded_bytes as f64 / total_elapsed_time
} else {
0.0
};
app_handle.emit_all("download_info", DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
})?;
app_handle.emit_all("download_speed", average_speed)?;
app_handle.emit_all("download_message", DownloadMessage {
message: format!("Download de {} concluído", entry.file_name),
})?;
Ok(())
}
async fn check_server_connection(client: &Client, url: &str) -> Result<(), DownloadError> {
let response = client.get(url).send().await?;
if response.status().is_success() {
Ok(())
} else {
Err(DownloadError::Custom("Failed to connect to the server".into()))
}
}
#[tauri::command]
pub async fn start_downloads(app_handle: AppHandle) -> Result<(), DownloadError> {
let exe_dir = get_exe_dir()?;
let patch_file_path = exe_dir.join("patch.json");
let download_dir = exe_dir.join("patches"); // Corrected from "patchs"
tokio_fs::create_dir_all(&download_dir).await?;
let patches = read_patch_file(&patch_file_path).await?;
let client = Client::new();
let total_files = patches.len();
app_handle.emit_all("download_message", DownloadMessage {
message: "Conectando ao servidor...".into(),
})?;
let server_url = "https://hil-speed.hetzner.com/";
if let Err(err) = check_server_connection(&client, server_url).await {
app_handle.emit_all("download_message", DownloadMessage {
message: format!("Erro ao conectar ao servidor: {}", err),
})?;
return Err(err);
}
app_handle.emit_all("download_message", DownloadMessage {
message: "Conexão estabelecida com sucesso. Iniciando downloads...".into(),
})?;
// Sequentially download files
for (index, entry) in patches.iter().enumerate() {
let current_file = index + 1;
if let Err(err) = download_file(
&app_handle,
&client,
entry,
&download_dir,
current_file,
total_files,
)
.await
{
eprintln!("Erro ao baixar arquivo {}: {}", entry.file_name, err);
app_handle.emit_all("download_message", DownloadMessage {
message: format!("Erro ao baixar arquivo {}: {}", entry.file_name, err),
})?;
// Optionally, you can stop the process here by returning Err, or continue with the next file
// return Err(err);
continue;
}
}
app_handle.emit_all("download_message", DownloadMessage {
message: "Todos os downloads foram concluídos com sucesso.".into(),
})?;
Ok(())
}
Improvements and Optimizations:
Error Handling:
Introduced a custom DownloadError enum using the thiserror crate for more descriptive and manageable error handling.
Replaced Box<dyn std::error::Error> with the custom DownloadError type.
Avoided unwrap and Used Proper Error Propagation:
Replaced calls to unwrap() with proper error handling using ? and custom error messages to prevent panics.
Optimized File Writing with BufWriter:
Used BufWriter to buffer writes to the file, which reduces the number of system calls and improves performance.
Efficient Directory Handling:
Ensured that parent directories for files are created before attempting to write to them.
Controlled Event Emission:
Reduced the frequency of emitting events to the frontend by adding a time check (last_emit_time) to emit updates every 500 milliseconds.
Used emit_all instead of emit which broadcasts to all windows, ensuring consistent event delivery.
Improved Progress Reporting:
Calculated and emitted the average download speed at the end of each file download.
Ensured that the final progress update is sent after the download completes.
Code Readability:
Added comments for clarity.
Corrected variable names and spellings (e.g., changed "patchs" to "patches").
Used References to Avoid Unnecessary Cloning:
Passed entry as a reference to avoid unnecessary cloning, improving memory efficiency.
Improved React Code
jsx
Improvements and Optimizations:
Optimized Event Listeners:
Wrapped the event listener setup in an asynchronous IIFE (Immediately Invoked Function Expression) to use await cleanly.
Ensured that unlisten functions are called properly in the cleanup function of useEffect.
State Updates and Prevented Unnecessary Re-renders:
Removed the dependency on isDownloading in the useEffect dependency array as the listeners only need to be set up once.
Used Math.min in progressPercent to cap the progress at 100%.
User Experience Enhancements:
Disabled the "Iniciar Download" button while downloads are in progress to prevent multiple invocations.
Updated the button text to indicate when a download is in progress.
Error Handling and Logging:
Added console.error to log errors for debugging purposes.
Ensured that the error message is informative to the user.
Code Simplification:
Removed unused imports and simplified the code where possible.
Ensured consistent formatting and readability.
Ensured Clean-up of Event Listeners:
Properly assigned and called the unlisten functions returned by the listen calls to prevent memory leaks.
Additional Notes:
In both the backend and frontend code, proper error handling and resource management are crucial. The optimized code ensures that errors are caught and communicated effectively to the user.
Reducing the frequency of event emissions from the backend decreases the load on the frontend and prevents potential performance bottlenecks due to excessive re-renders.
Using buffering mechanisms (like BufWriter in Rust) enhances file I/O performance by minimizing disk write operations.
Ensuring that event listeners are properly cleaned up in React prevents memory leaks and unintended side effects.
By applying these optimizations and improvements, the application should perform more efficiently and provide a better user experience.