diff --git a/crates/voelin-core/src/files.rs b/crates/voelin-core/src/files.rs index d0e416d..8ea23fc 100644 --- a/crates/voelin-core/src/files.rs +++ b/crates/voelin-core/src/files.rs @@ -199,19 +199,22 @@ async fn receive( let mut done = offset; match sink { Sink::File { part, dest, append } => { + // The directory and the file are made in one step, without a pause in + // which the task could be stopped: a cancel stops the task, waits for + // it and then removes the part file, so what the task made must be + // there by then (a pending open on the blocking pool would not be). if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) { - tokio::fs::create_dir_all(dir) - .await - .map_err(|e| format!("{}: {e}", dir.display()))?; + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; } - let mut file = tokio::fs::OpenOptions::new() - .create(true) - .write(true) - .append(*append) - .truncate(!*append) - .open(part) - .await - .map_err(|e| format!("{}: {e}", part.display()))?; + let mut file = tokio::fs::File::from_std( + std::fs::OpenOptions::new() + .create(true) + .write(true) + .append(*append) + .truncate(!*append) + .open(part) + .map_err(|e| format!("{}: {e}", part.display()))?, + ); let received = async { while done < size { let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?; diff --git a/crates/voelin-core/src/link/session_link.rs b/crates/voelin-core/src/link/session_link.rs index c1ecb59..33ada6b 100644 --- a/crates/voelin-core/src/link/session_link.rs +++ b/crates/voelin-core/src/link/session_link.rs @@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use tokio::sync::mpsc; -use tokio::task::AbortHandle; +use tokio::task::JoinHandle; use tracing::{debug, info, warn}; use voelin_audio::EncodedVoice; use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId}; @@ -325,7 +325,7 @@ async fn drive( /// A transfer a user can cancel. struct Running { - task: AbortHandle, + task: JoinHandle<()>, part: Option, report: Report, /// The server has opened it (a part file may exist). @@ -1479,7 +1479,7 @@ impl Conn { receive.await; } }); - self.running(transfer, Running { task: task.abort_handle(), part, report, started }); + self.running(transfer, Running { task, part, report, started }); } fn upload( @@ -1560,7 +1560,7 @@ impl Conn { let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) }; files::upload_to(body, stored, from, size, offset, progress, task_report).await; }); - self.running(transfer, Running { task: task.abort_handle(), part: None, report, started }); + self.running(transfer, Running { task, part: None, report, started }); } fn running(&mut self, transfer: Option, running: Running) { @@ -1572,15 +1572,21 @@ impl Conn { fn cancel(&mut self, id: TransferId) { match self.transfers.remove(&id) { - Some(running) if !running.task.is_finished() => { - running.task.abort(); - // A part file exists once the server has opened the transfer. - if running.started.load(Ordering::Acquire) - && let Some(part) = running.part - { - let _ = std::fs::remove_file(part); - } - (running.report)(TransferState::Cancelled); + Some(Running { task, part, report, started }) if !task.is_finished() => { + task.abort(); + // The part file goes once the task has stopped, not at once: the task + // opens it in one step (files::download), so it is there or it never + // will be, and a removal that came before the open would leave it. + tokio::spawn(async move { + let _ = task.await; + // A part file exists once the server has opened the transfer. + if started.load(Ordering::Acquire) + && let Some(part) = part + { + let _ = std::fs::remove_file(part); + } + report(TransferState::Cancelled); + }); } _ => debug!(id, "cancel: no such transfer (finished?)"), } diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index 5d71f0a..6645675 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -598,20 +598,21 @@ async fn a_file_is_downloaded_through_the_connection_the_link_opens() { report, }); let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") }; - // A file whose bytes do not come: the transfer waits in the middle, with - // its part file made. `Started` is reported just before the part file is - // opened, and a cancel in between would find nothing to remove while the - // open still goes on, so the part file is what is waited for. + // A file whose bytes do not come: the transfer waits in the middle. let (server, client) = tokio::io::duplex(64); let _ = reply.send(Ok((1 << 20, Box::pin(client)))); for _ in 0..500 { - if part.exists() { + if states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })) { break; } tokio::time::sleep(Duration::from_millis(10)).await; } - assert!(part.exists(), "the transfer made its part file: {:?}", states.lock().unwrap()); - assert!(states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. }))); + assert!( + states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })), + "the transfer started: {:?}", + states.lock().unwrap() + ); + // Cancelled the moment it is Started, when its part file may be opening. rig.give(LinkCmd::CancelTransfer(3)); assert_eq!(final_state(&states).await, TransferState::Cancelled); rig.quiet();