I'm creating rust code with react that downloads files, in a test I did the download bar goes completely crazy, it keeps going back and forth
the bytes of the files are correct, I don't understand why this is happening
I have following code
test.lua
local updates = {
{ version = 1, file_name = "100MB.bin" },
{ version = 2, file_name = "1GB.bin" },
{ version = 3, file_name = "10GB.bin" }
}
return updates
use mlua::{Lua, Result as LuaResult};
use reqwest::Client;
use std::path::PathBuf;
use std::env;
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tauri::{Window, Emitter};
fn get_executable_directory() -> PathBuf {
env::current_exe()
.expect("Failed to get current executable path")
.parent()
.expect("Failed to get executable directory")
.to_path_buf()
}
fn parse_lua_file(file_path: &str) -> LuaResult<Vec<(u32, String)>> {
let lua = Lua::new();
let lua_code = std::fs::read_to_string(file_path).expect("Failed to read Lua file");
code
let updates: mlua::Table = lua.load(&lua_code).eval()?;
let mut files = Vec::new();
for pair in updates.sequence_values::<mlua::Table>() {
let table = pair?;
let version: u32 = table.get("version")?;
let file_name: String = table.get("file_name")?;
files.push((version, file_name));
}
Ok(files)
}
#[tauri::command]
pub async fn download_files(window: Window) -> Result<(), String> {
// Obtém o diretório do executável
let exe_dir = get_executable_directory();
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Define o caminho para a pasta `patchs`
let patchs_dir = exe_dir.join("patchs");
// Verifica e cria o diretório `patchs` se ele não existir
fs::create_dir_all(&patchs_dir).await.map_err(|e| format!("Failed to create patchs directory: {}", e))?;
// Carrega o arquivo Lua e obtém os arquivos a serem baixados
let lua_file_path = exe_dir.join("test.lua");
let lua_file_path_str = lua_file_path.to_str().ok_or("Invalid file path")?;
let files_to_download = parse_lua_file(lua_file_path_str)
.map_err(|e| format!("Failed to parse Lua file: {}", e))?;
let total_files = files_to_download.len();
let client = Client::new();
for (current_file, (_version, file_name)) in files_to_download.iter().enumerate() {
let url = format!("https://hil-speed.hetzner.com/{}", file_name);
let mut response = client
.get(&url)
.send()
.await
.map_err(|e| format!("Failed to download {}: {}", file_name, e))?;
let total_bytes = response.content_length().unwrap_or(0);
let mut downloaded_bytes = 0;
// Define o caminho completo para o arquivo na pasta `patchs`
let file_path = patchs_dir.join(file_name);
let mut file = File::create(&file_path).await.map_err(|e| format!("Failed to create file {}: {}", file_name, e))?;
// Baixa o arquivo em chunks e grava o progresso
while let Some(chunk) = response.chunk().await.map_err(|e| format!("Failed to read chunk for {}: {}", file_name, e))? {
downloaded_bytes += chunk.len() as u64;
file.write_all(&chunk).await.map_err(|e| format!("Failed to write chunk for {}: {}", file_name, e))?;
// Emite o progresso atualizado
window.emit(
"download-progress",
DownloadProgress {
current_file: current_file + 1,
total_files,
file_name: file_name.clone(),
downloaded_bytes,
total_bytes,
},
).map_err(|e| format!("Failed to send event for {}: {}", file_name, e))?;
}
}
Ok(())
}
React
import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
The erratic behavior of your download progress bar is likely due to how the progress is being tracked and updated for multiple files. Specifically, each file's download progress is being tracked individually, causing the progress bar to reset or jump back when a new file starts downloading. To provide a smooth and consistent progress bar, you should track the cumulative progress across all files rather than tracking each file separately.
Why the Progress Bar is Erratic
Per-File Progress Tracking: Your current implementation tracks the progress of each file individually. When a new file starts downloading, the downloaded_bytes and total_bytes reset, causing the progress bar to jump back to 0% and start progressing again. This creates the illusion of the progress bar "going back and forth."
State Updates in React: The React component updates the state for each chunk downloaded. If multiple events are emitted rapidly or out of order, it can cause the progress bar to behave unpredictably.
Solution: Implement Cumulative Progress Tracking
To achieve a smooth progress bar, you should:
Calculate the Total Bytes for All Files: Before starting the download, determine the total number of bytes to be downloaded across all files.
Track Cumulative Downloaded Bytes: As each file downloads, add the bytes downloaded to a running total.
Emit Cumulative Progress Events: Instead of emitting progress for each file individually, emit a cumulative progress event that reflects the total progress across all files.
Update the React Component Accordingly: Use the cumulative progress to update the progress bar, ensuring it only moves forward.
Step-by-Step Implementation
1. Update the Rust Backend
a. Modify DownloadProgress to Include Cumulative Progress
First, update the DownloadProgress struct to include cumulative downloaded bytes and total bytes:
rust
#[derive(serde::Serialize, Clone)]
struct DownloadProgress {
current_file: usize,
total_files: usize,
file_name: String,
downloaded_bytes: u64, // Bytes downloaded for the current file
total_bytes: u64, // Total bytes for the current file
cumulative_downloaded: u64, // Total bytes downloaded across all files
cumulative_total: u64, // Total bytes to download across all files
}
b. Calculate Total Bytes Before Downloading
Before downloading, iterate through all files to calculate the total bytes. This ensures you have an accurate cumulative_total.
rust
#[tauri::command]
pub async fn download_files(window: Window) -> Result<(), String> {
let exe_dir = get_executable_directory();
let patchs_dir = exe_dir.join("patchs");
fs::create_dir_all(&patchs_dir).await.map_err(|e| format!("Failed to create patchs directory: {}", e))?;
let lua_file_path = exe_dir.join("test.lua");
let lua_file_path_str = lua_file_path.to_str().ok_or("Invalid file path")?;
let files_to_download = parse_lua_file(lua_file_path_str)
.map_err(|e| format!("Failed to parse Lua file: {}", e))?;
let total_files = files_to_download.len();
let client = Client::new();
// Calculate the cumulative total bytes
let mut cumulative_total: u64 = 0;
let mut file_sizes = Vec::new();
for (_version, file_name) in &files_to_download {
let url = format!("https://hil-speed.hetzner.com/{}", file_name);
let head_resp = client.head(&url).send().await.map_err(|e| format!("Failed to send HEAD request for {}: {}", file_name, e))?;
let size = head_resp
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(0);
cumulative_total += size;
file_sizes.push(size);
}
let mut cumulative_downloaded: u64 = 0;
for (i, ((version, file_name), &file_size)) in files_to_download.iter().zip(file_sizes.iter()).enumerate() {
let url = format!("https://hil-speed.hetzner.com/{}", file_name);
let mut response = client
.get(&url)
.send()
.await
.map_err(|e| format!("Failed to download {}: {}", file_name, e))?;
let total_bytes = response.content_length().unwrap_or(0);
let mut downloaded_bytes = 0;
let file_path = patchs_dir.join(file_name);
let mut file = File::create(&file_path).await.map_err(|e| format!("Failed to create file {}: {}", file_name, e))?;
while let Some(chunk) = response.chunk().await.map_err(|e| format!("Failed to read chunk for {}: {}", file_name, e))? {
downloaded_bytes += chunk.len() as u64;
cumulative_downloaded += chunk.len() as u64;
file.write_all(&chunk).await.map_err(|e| format!("Failed to write chunk for {}: {}", file_name, e))?;
// Emit the cumulative progress
window.emit(
"download-progress",
DownloadProgress {
current_file: i + 1,
total_files,
file_name: file_name.clone(),
downloaded_bytes,
total_bytes,
cumulative_downloaded,
cumulative_total,
},
).map_err(|e| format!("Failed to send event for {}: {}", file_name, e))?;
}
}
Ok(())
}
Explanation:
HEAD Requests: Before downloading, send a HEAD request for each file to obtain the Content-Length, which gives the file size. This is essential for calculating the cumulative_total.
Cumulative Tracking: As each chunk is downloaded, update both downloaded_bytes (for the current file) and cumulative_downloaded (across all files).
Emit Cumulative Progress: Emit the DownloadProgress event with both per-file and cumulative progress data.
Note: Ensure that the server supports HEAD requests. If not, you might need to handle cases where Content-Length is unavailable.
2. Update the React Frontend
a. Modify the DownloadProgress Interface
Include cumulative progress in your TypeScript interface:
Cumulative State: Added cumulativeDownloaded and cumulativeTotal to track the overall progress.
Progress Calculation: The progressPercent is now based on the cumulative bytes downloaded versus the total bytes to be downloaded across all files.
UI Update: The progress bar reflects the overall download progress, ensuring it only moves forward and does not reset with each new file.
3. Handling Edge Cases
Unknown File Sizes: If some files do not provide Content-Length, you might need to handle cases where cumulative_total is incorrect. Consider skipping such files or handling them separately.
Error Handling: Ensure that errors in downloading one file do not crash the entire download process unless that's the desired behavior.
Performance Considerations: For very large downloads (e.g., 10GB), consider optimizing how progress updates are handled to prevent UI lag.
Final Thoughts
By implementing cumulative progress tracking, you ensure that the progress bar accurately reflects the overall download status across all files. This approach prevents the progress bar from jumping back and forth, providing a smoother and more intuitive user experience.
If you still experience issues after these changes, consider adding more detailed logging on both the Rust and React sides to trace the exact flow of progress updates and identify any inconsistencies.