From 966c8a587cce0d2853f1977cb73889ea4d8446d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:01:47 -0800 Subject: [PATCH] Recovery: a cancel stops a background write at its next chunk A save, revert or close during a background recovery write now stops the write at its next piece of output (at most 1 MiB) instead of after the whole package, and a stopped write is not reported as a failure. --- crates/engine/src/lib.rs | 1 + crates/engine/src/recovery.rs | 41 ++++++++++++++++++++++++++--- crates/engine/src/recovery/tests.rs | 20 ++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bb67875b4..363f4e9cd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -414,6 +414,7 @@ pub struct Session { pub recovery_dir: Option, /// This session's number for the background recovery writer, which returns each result to /// the session that queued it. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) recovery_owner: recovery::Owner, /// Copied text with its formatting (a frameless story slice), its plain text, and what pasting /// it needs from its document: a copy holding only the stories its anchored text frames show diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index e2e09a42b..3b4060763 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -725,6 +725,36 @@ struct Written { error: Option, } +/// A writer that fails once `cancelled` says so, checked before each write of at most +/// [`STOP_CHECK_BYTES`]. +struct StopWhen<'a, W, C> { + out: &'a mut W, + cancelled: &'a C, +} + +/// The most [`StopWhen`] writes between two checks for a cancel. +const STOP_CHECK_BYTES: usize = 1 << 20; + +impl bool> std::io::Write for StopWhen<'_, W, C> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if (self.cancelled)() { + return Err(std::io::Error::other("recovery write cancelled")); + } + // A large placed file is written in pieces, so a cancel does not wait for all of it. + self.out.write(&buf[..buf.len().min(STOP_CHECK_BYTES)]) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.out.flush() + } +} + +impl std::io::Seek for StopWhen<'_, W, C> { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.out.seek(pos) + } +} + /// Publish a document's recovery entry before its optional metadata. `cancelled` says whether the /// document was saved, reverted or closed since the write started: its snapshot is then dropped /// instead of published, so a crash cannot offer back a copy older than the saved file. @@ -735,7 +765,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let published = publish_recovery_written( &doc, entry.own, - |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), + // A cancel stops the write at its next chunk instead of after the whole package. + |out| { + designcraft_format::write(&mut StopWhen { out, cancelled: &cancelled }, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())) + }, &cancelled, // Written: in a folder that is not this run's own, the entry is now this run's to replace // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the @@ -748,8 +781,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { ); match published { Ok(true) => {} - // Cancelled while writing: no snapshot and no metadata for it. + // Cancelled while writing: no snapshot and no metadata for it. A write stopped part way + // reports an error, which is the cancel's and not a failure. Ok(false) => return Written { published: false, error: None }, + Err(_) if cancelled() => return Written { published: false, error: None }, Err(e) => return Written { published: false, error: Some(e) }, } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); @@ -758,7 +793,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let error = publish_recovery_written( &meta, entry.own, - |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), + |out| std::io::Write::write_all(out, bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), &cancelled, || {}, ) diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index c59c5ee76..4534c3c37 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -514,6 +514,26 @@ fn a_write_cancelled_midway_publishes_nothing() { ); } +#[test] +fn a_cancel_stops_a_write_before_the_package_is_finished() { + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + // Cancelled once the write has started: the first check passes, every later one fails. + let checks = std::cell::Cell::new(0); + let written = write_snapshot(&entry, || { + checks.set(checks.get() + 1); + checks.get() > 1 + }); + assert!(!written.published && written.error.is_none(), "a stopped write is not an error"); + assert!(checks.get() >= 2, "the write checked again before it finished"); + assert!(!files(dir.path(), entry.uid).0.exists(), "nothing was published"); + assert!( + std::fs::read_dir(dir.path()).unwrap().all(|e| e.is_ok_and(|e| !e.file_name().to_string_lossy().starts_with(".designcraft-recovery-"))), + "no temporary file is left" + ); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn only_a_queued_write_is_cancelled() {