Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
fix: keep failed and concurrent downloads from corrupting files
Tw933d41e52381a2
diff --git a/src-tauri/src/app/invoke.rs b/src-tauri/src/app/invoke.rsindex 183d57ef..6d9e46e2 100644--- a/src-tauri/src/app/invoke.rs+++ b/src-tauri/src/app/invoke.rs@@ -270,6 +270,30 @@ async fn download_response(}}+/// Reserve the destination with `create_new`, so two downloads that resolve the+/// same free name at the same time cannot write into one file.+async fn create_unique_file(path: &str) -> std::io::Result<(tokio::fs::File, String)> {+ let mut candidate = check_file_or_append(path);+ for _ in 0..100 {+ match tokio::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&candidate)+ .await+ {+ Ok(file) => return Ok((file, candidate)),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {+ candidate = check_file_or_append(&candidate);+ }+ Err(error) => return Err(error),+ }+ }+ Err(std::io::Error::new(+ std::io::ErrorKind::AlreadyExists,+ "no free download filename",+ ))+}+#[command]pub async fn download_file(window: WebviewWindow,@@ -294,8 +318,6 @@ pub async fn download_file(let path_str = output_path.to_str().ok_or("Invalid output path")?;- let file_path = check_file_or_append(path_str);-let url = Url::from_str(¶ms.url).map_err(|e| format!("Invalid URL: {}", e))?;let page_url = trusted_page_url(params.page_url.as_deref(), window.url().ok().as_ref());@@ -325,7 +347,7 @@ pub async fn download_file(return Err(format!("Download failed with HTTP status {}", res.status()));}- let mut file = tokio::fs::File::create(&file_path).await.map_err(|e| {+ let (mut file, file_path) = create_unique_file(path_str).await.map_err(|e| {show_toast(&window,&get_download_message_with_lang(@@ -336,12 +358,33 @@ pub async fn download_file(format!("Failed to create file: {e}")})?;- while let Some(chunk) = res- .chunk()- .await- .map_err(|e| format!("Failed to get chunk: {}", e))?- {- file.write_all(&chunk).await.map_err(|e| {+ // The error flags disk failures, which get the directory toast.+ let written: Result<(), (bool, String)> = async {+ while let Some(chunk) = res+ .chunk()+ .await+ .map_err(|e| (false, format!("Failed to get chunk: {e}")))?+ {+ file.write_all(&chunk)+ .await+ .map_err(|e| (true, format!("Failed to write chunk: {e}")))?;+ }+ file.flush()+ .await+ .map_err(|e| (true, format!("Failed to finish writing file: {e}")))+ }+ .await;++ if let Err((disk_failure, error)) = written {+ // A truncated file under the final name looks like a finished+ // download, so remove it before reporting the failure.+ drop(file);+ if let Err(remove_error) = tokio::fs::remove_file(&file_path).await {+ eprintln!(+ "[Pake] Failed to remove partial download {file_path}: {remove_error}"+ );+ }+ if disk_failure {show_toast(&window,&get_download_message_with_lang(@@ -349,21 +392,10 @@ pub async fn download_file(params.language.clone(),),);- format!("Failed to write chunk: {e}")- })?;+ }+ return Err(error);}- file.flush().await.map_err(|e| {- show_toast(- &window,- &get_download_message_with_lang(- MessageType::DirectoryFailure,- params.language.clone(),- ),- );- format!("Failed to finish writing file: {e}")- })?;-show_toast(&window,&get_download_message_with_lang(MessageType::Success, params.language.clone()),@@ -476,6 +508,30 @@ pub fn webview_navigate(window: WebviewWindow, action: String) -> Result<(), Strmod tests {use super::*;+ #[test]+ fn concurrent_downloads_of_one_name_reserve_distinct_files() {+ let dir = std::env::temp_dir().join(format!("pake-unique-file-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let target = dir.join("report.pdf");+ std::fs::write(&target, b"existing").unwrap();+ let path = target.to_str().unwrap();+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();++ let (first, second) = runtime+ .block_on(async { tokio::join!(create_unique_file(path), create_unique_file(path)) });+ let (_first_file, first) = first.unwrap();+ let (_second_file, second) = second.unwrap();++ assert_ne!(first, second);+ assert_ne!(first, path);+ assert_ne!(second, path);+ assert_eq!(std::fs::read(&target).unwrap(), b"existing");+ std::fs::remove_dir_all(&dir).unwrap();+ }+fn headers(cookie: Option<&str>,user_agent: Option<&str>,diff --git a/tests/unit/download-http-status.test.ts b/tests/unit/download-http-status.test.tsindex 350b3835..b5a93b11 100644--- a/tests/unit/download-http-status.test.ts+++ b/tests/unit/download-http-status.test.ts@@ -12,6 +12,12 @@ const eventSource = fs.readFileSync('utf8',);+const downloadFunction = () =>+ invokeSource.slice(+ invokeSource.indexOf('pub async fn download_file'),+ invokeSource.indexOf('pub fn send_notification'),+ );+describe('download HTTP status handling', () => {it('rejects non-success HTTP responses before writing the file', () => {expect(invokeSource).toContain('res.status().is_success()');@@ -19,26 +25,51 @@ describe('download HTTP status handling', () => {/if !res\.status\(\)\.is_success\(\) \{[\s\S]*?MessageType::Failure/,);// File creation must come after the status gate so 403 bodies are not saved.- const statusIdx = invokeSource.indexOf('res.status().is_success()');- const createIdx = invokeSource.indexOf('File::create');+ const downloadFn = downloadFunction();+ const statusIdx = downloadFn.indexOf('res.status().is_success()');+ const createIdx = downloadFn.indexOf('create_unique_file(path_str)');expect(statusIdx).toBeGreaterThan(-1);expect(createIdx).toBeGreaterThan(statusIdx);});- it.each(['File::create(&file_path)', 'file.write_all(&chunk)'])(- 'reports download directory failure when %s fails',- (operation) => {- const start = invokeSource.indexOf(operation);- const end = invokeSource.indexOf('})?;', start);- expect(start).toBeGreaterThan(-1);- expect(end).toBeGreaterThan(start);- const handler = invokeSource.slice(start, end);- expect(handler).toMatch(/\.map_err\(\|e\|\s*\{/);- expect(handler).toMatch(- /show_toast\(\s*&window,\s*&get_download_message_with_lang\(\s*MessageType::DirectoryFailure,/,- );- },- );+ it('reports download directory failure when the file cannot be created', () => {+ const start = invokeSource.indexOf(+ 'create_unique_file(path_str).await.map_err(|e| {',+ );+ const end = invokeSource.indexOf('})?;', start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ expect(invokeSource.slice(start, end)).toMatch(+ /show_toast\(\s*&window,\s*&get_download_message_with_lang\(\s*MessageType::DirectoryFailure,/,+ );+ });++ it('reserves the destination atomically so concurrent downloads never share a file', () => {+ const helper = invokeSource.slice(+ invokeSource.indexOf('async fn create_unique_file('),+ invokeSource.indexOf('pub async fn download_file'),+ );+ expect(helper).toContain('.create_new(true)');+ expect(helper).toContain('ErrorKind::AlreadyExists');+ });++ it('reports disk write failures and removes the partial file', () => {+ const downloadFn = downloadFunction();+ expect(downloadFn).toMatch(+ /file\.write_all\(&chunk\)\s*\.await\s*\.map_err\(\|e\| \(true,/,+ );+ expect(downloadFn).toMatch(+ /\.chunk\(\)\s*\.await\s*\.map_err\(\|e\| \(false,/,+ );+ const failure = downloadFn.slice(+ downloadFn.indexOf('if let Err((disk_failure, error)) = written {'),+ downloadFn.indexOf('return Err(error);'),+ );+ expect(failure).toContain('tokio::fs::remove_file(&file_path).await');+ expect(failure).toMatch(+ /if disk_failure \{\s*show_toast\(\s*&window,\s*&get_download_message_with_lang\(\s*MessageType::DirectoryFailure,/,+ );+ });it('keeps download path heuristics narrow (no SPA roots)', () => {const patternsBlock = eventSource.match(@@ -71,15 +102,12 @@ describe('download HTTP status handling', () => {});it('waits for the final asynchronous disk write before reporting success', () => {- const downloadFn = invokeSource.slice(- invokeSource.indexOf('pub async fn download_file'),- invokeSource.indexOf('pub fn send_notification'),- );- const flush = downloadFn.indexOf('file.flush().await');+ const downloadFn = downloadFunction();+ const flush = downloadFn.search(/file\.flush\(\)\s*\.await/);expect(flush).toBeGreaterThan(downloadFn.indexOf('file.write_all(&chunk)'));expect(flush).toBeLessThan(downloadFn.indexOf('MessageType::Success'));- expect(- downloadFn.slice(flush, downloadFn.indexOf('})?;', flush)),- ).toContain('MessageType::DirectoryFailure');+ expect(downloadFn.slice(flush, flush + 200)).toMatch(+ /\.map_err\(\|e\| \(true,/,+ );});});