Skip to content

Commit

Permalink
Buffer emit_all to potentially reduce crashes
Browse files Browse the repository at this point in the history
  • Loading branch information
EliteAsian123 committed Jun 11, 2024
1 parent 4088554 commit 3092daf
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions src-tauri/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use futures_util::StreamExt;
use reqwest;
use sevenz_rust::Password;
use std::path::Path;
use std::time::{Duration, Instant};
use std::{fs::File, io::Write};
use tauri::{AppHandle, Manager};

use crate::app_profile::ProgressPayload;

const LETTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const EMIT_BUFFER_RATE: f64 = 1.0 / 15.0;

pub fn clear_folder(path: &Path) -> Result<(), String> {
std::fs::remove_dir_all(path).ok();
Expand All @@ -27,13 +29,8 @@ pub async fn download(
url: &str,
output_path: &Path,
) -> Result<(), String> {
// Create the downloading client
let client = reqwest::Client::new();

// Send the initial request
let download = client
.get(url)
.send()
let download = reqwest::get(url)
.await
.map_err(|e| format!("Failed to initialize download from `{}`.\n{:?}", &url, e))?;
let total_size = download.content_length().unwrap();
Expand All @@ -49,6 +46,8 @@ pub async fn download(
let mut current_downloaded: u64 = 0;
let mut stream = download.bytes_stream();

let mut emit_timer = Instant::now();

// Download into the file
while let Some(item) = stream.next().await {
let chunk = item.map_err(|e| format!("Error while downloading file.\n{:?}", e))?;
Expand All @@ -57,21 +56,25 @@ pub async fn download(

// Cap the downloaded at the total size
current_downloaded += chunk.len() as u64;

if current_downloaded > total_size {
current_downloaded = total_size;
}

// Emit the download progress
if let Some(app) = app {
let _ = app.emit_all(
"progress_info",
ProgressPayload {
state: "downloading".to_string(),
current: current_downloaded,
total: total_size,
},
);
// Emitting too often could cause crashes, so buffer it to the buffer rate
if emit_timer.elapsed() >= Duration::from_secs_f64(EMIT_BUFFER_RATE) {
let _ = app.emit_all(
"progress_info",
ProgressPayload {
state: "downloading".to_string(),
current: current_downloaded,
total: total_size,
},
);

emit_timer = Instant::now();
}
}
}

Expand Down

0 comments on commit 3092daf

Please sign in to comment.