diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 642059d1e..08aa94c6b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -188,6 +188,20 @@ impl Sel { } } +/// Whether the document differs from the one its file holds, as last worked out for this pair +/// of documents at this revision. The window asks every frame for every tab (the tab strip, the +/// autosave), and a large design compared field by field cost more than the rest of an idle +/// frame. Holding both documents keeps their contents fixed and their addresses unused by +/// another document while the answer stands: shared, a document can't be edited in place (an +/// edit copies it to a new address), and [`Session::doc_mut`] lets the answer go first so an +/// edit stays in place. +struct DirtyAnswer { + revision: u64, + doc: Arc, + saved: Arc, + differs: bool, +} + /// A body rename between two designs (see `Session::body_renames`). #[derive(Clone)] struct BodyRename { @@ -481,6 +495,8 @@ pub struct Session { removed_later_cache: std::sync::Mutex>, occurrence_bodies_cache: std::sync::Mutex>, placement_index_cache: std::sync::Mutex>, + /// The last answer of [`Session::is_dirty`] on the document (see [`DirtyAnswer`]). + dirty_cache: std::sync::Mutex>, /// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with /// scratch copies): a body that did not change or move is not measured again. clearance_cache: std::sync::Arc>, @@ -687,6 +703,7 @@ impl Session { removed_later_cache: Default::default(), occurrence_bodies_cache: Default::default(), placement_index_cache: Default::default(), + dirty_cache: Default::default(), clearance_cache: Default::default(), body_renames: Vec::new(), contact_meshes: Default::default(), @@ -752,9 +769,34 @@ impl Session { /// The design has changes not in its file: in the document, or in what is hidden. pub fn is_dirty(&self) -> bool { - (!Arc::ptr_eq(&self.doc, &self.saved) && *self.doc != *self.saved) || self.visibility != self.saved_visibility + self.document_differs() || self.visibility != self.saved_visibility } + + /// The document is not the one its file holds: compared once per pair of documents and + /// revision ([`DirtyAnswer`]). + fn document_differs(&self) -> bool { + if Arc::ptr_eq(&self.doc, &self.saved) { + return false; + } + let Ok(mut answer) = self.dirty_cache.lock() else { return *self.doc != *self.saved }; + let same = |a: &DirtyAnswer| a.revision == self.revision && Arc::ptr_eq(&a.doc, &self.doc) && Arc::ptr_eq(&a.saved, &self.saved); + if let Some(a) = answer.as_ref().filter(|a| same(a)) { + return a.differs; + } + let differs = *self.doc != *self.saved; + *answer = Some(DirtyAnswer { revision: self.revision, doc: self.doc.clone(), saved: self.saved.clone(), differs }); + differs + } + + /// Let the unsaved-changes answer go, with the documents it holds. + fn forget_dirty_answer(&self) { + if let Ok(mut answer) = self.dirty_cache.lock() { + *answer = None; + } + } + pub fn mark_saved(&mut self) { + self.forget_dirty_answer(); self.saved = self.doc.clone(); self.saved_visibility = self.visibility.clone(); } @@ -860,6 +902,7 @@ impl Session { if let Ok(mut index) = self.placement_index_cache.lock() { *index = None; } + self.forget_dirty_answer(); Arc::make_mut(&mut self.doc) } @@ -1300,6 +1343,7 @@ impl Session { if let Ok(mut index) = self.placement_index_cache.lock() { *index = None; } + self.forget_dirty_answer(); self.model.adopt_solved_sketches(Arc::make_mut(&mut self.doc)); } Ok(()) @@ -1593,6 +1637,7 @@ impl Session { removed_later_cache: Default::default(), occurrence_bodies_cache: Default::default(), placement_index_cache: Default::default(), + dirty_cache: Default::default(), clearance_cache: self.clearance_cache.clone(), body_renames: self.body_renames.clone(), contact_meshes: self.contact_meshes.clone(), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ab64553fb..aa1b4f250 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3437,6 +3437,48 @@ fn computed_import_preserves_file_and_earlier_undo_history() { assert!(s.model.state().bodies.is_empty()); } +/// The unsaved-changes answer is worked out once per pair of documents and revision, and stays +/// right through every way the design changes: an edit in place (`doc_mut`, which stays in +/// place), one that bypasses it, a new document equal to the saved one, Save, a change of what +/// is hidden, and undo back to the saved design. Each answer is checked against the plain +/// comparison it stands for. +#[test] +fn the_unsaved_changes_answer_follows_every_change() { + let plain = |s: &Session| (!std::sync::Arc::ptr_eq(&s.doc, &s.saved) && *s.doc != *s.saved) || s.visibility != s.saved_visibility; + let check = |s: &Session, want: bool, why: &str| { + for _ in 0..2 { + assert_eq!(s.is_dirty(), want, "{why}"); + assert_eq!(plain(s), want, "{why}: the plain comparison"); + } + }; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + s.mark_saved(); + check(&s, false, "saved"); + // An edit in place: the cached answer holds the document, yet the edit is not a copy. + s.doc = std::sync::Arc::new((*s.doc).clone()); + check(&s, false, "an equal copy of the saved design"); + let at = std::sync::Arc::as_ptr(&s.doc); + s.doc_mut().name = "Renamed".into(); + assert_eq!(std::sync::Arc::as_ptr(&s.doc), at, "doc_mut edits in place"); + check(&s, true, "renamed in place, same revision"); + s.doc_mut().name = s.saved.name.clone(); + check(&s, false, "named back in place"); + // An edit that goes around doc_mut while the answer holds the document copies it. + std::sync::Arc::make_mut(&mut s.doc).name = "Elsewhere".into(); + check(&s, true, "edited past doc_mut"); + s.mark_saved(); + check(&s, false, "saved again"); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [30, 0, 0]})); + check(&s, true, "a command"); + run(&mut s, "edit.undo", json!({})); + check(&s, false, "undone back to the saved design"); + s.visibility.hidden_bodies.push("Body1".into()); + check(&s, true, "a body hidden"); + s.visibility.hidden_bodies.clear(); + check(&s, false, "shown again"); +} + /// Commands evaluated ahead (off the window thread) and then run for real take what was /// evaluated: on a design whose states are past the shared cache's budget the second run /// evaluated everything again, so an off-thread command cost twice its time. diff --git a/crates/io/src/safe_write.rs b/crates/io/src/safe_write.rs index 71f890fb1..ebe9184a2 100644 --- a/crates/io/src/safe_write.rs +++ b/crates/io/src/safe_write.rs @@ -1,7 +1,8 @@ //! Crash-safe file writes: the new content goes to a temporary file next to the target, is //! flushed to disk, and replaces the target in one rename. A crash or power cut at any moment //! leaves the old file or the new one, never a torn mix. The previous version can be kept as -//! `.bak` (itself written the same way). +//! `.bak`: the old file itself under that name (a hard link) where the file system allows, +//! else a copy written the same way. use std::fs::{self, OpenOptions}; use std::io::Write; @@ -145,6 +146,45 @@ fn rename_with_retry( result } +/// Keep the file a save is about to replace as its backup without copying it: a second name for +/// the same file (a hard link) under a temporary name beside it, renamed over the old backup in +/// one step. The target keeps its name at every moment, and a save never writes into a file it +/// replaces (it renames a new one over it), so the backup stays the version it was. `Ok(false)`: +/// this file system refuses links (FAT and exFAT drives, many network shares and synced cloud +/// folders) or the old file could not be flushed first; the caller copies it then, as before. A +/// refused rename fails the save, as it does for a copy. +/// +/// What differs from a copy: the backup is the old file itself, so it keeps that file's +/// modification time (the previous save's, where a copy has the time of this save), its owner +/// and its permissions (a copy is given the same permissions), and until the target is replaced +/// the two names share one file. +fn link_backup(path: &Path) -> std::io::Result { + #[cfg(test)] + if tests::LINKS_REFUSED.with(std::cell::Cell::get) { + return Ok(false); + } + // Flushed first, as a copy is: data still only in memory would be lost with it in a power cut. + if open_to_flush(path).and_then(|f| flush(&f)).is_err() { + return Ok(false); + } + let bak_tmp = temp_beside(path, "bak"); + if fs::hard_link(path, &bak_tmp).is_err() { + return Ok(false); + } + if let Err(e) = replace_synced(&bak_tmp, &backup_path(path)) { + // Only the second name this call just made: the old file keeps its own. + let _ = fs::remove_file(&bak_tmp); + return Err(e); + } + Ok(true) +} + +/// Open the file a save replaces so it can be flushed. Windows flushes only a file opened for +/// writing (nothing is written, and it is not truncated); elsewhere reading is enough. +fn open_to_flush(path: &Path) -> std::io::Result { + OpenOptions::new().read(true).write(cfg!(windows)).open(path) +} + fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> std::io::Result<()> { let permissions = fs::metadata(path).ok().filter(|m| m.is_file()).map(|m| m.permissions()); let tmp = temp_beside(path, "new"); @@ -156,7 +196,15 @@ fn write_steps(path: &Path, bytes: &[u8], backup: bool, stop: Option) -> s if stop == Some(Step::TempWritten) { return Ok(()); } - if backup && path.is_file() { + let linked = if backup && path.is_file() { link_backup(path) } else { Ok(false) }; + let linked = match linked { + Ok(linked) => linked, + Err(e) => { + let _ = fs::remove_file(&tmp); + return Err(e); + } + }; + if backup && !linked && path.is_file() { // Copy (not move) the old file, so the target exists at every moment. let old = fs::read(path); let bak_tmp = temp_beside(path, "bak"); @@ -245,6 +293,86 @@ pub fn stale_temps(path: &Path) -> Vec { mod tests { use super::*; + thread_local! { + /// This thread's saves find hard links refused ([`link_backup`]), as on a FAT drive: the + /// backup is copied, exactly as it is there. + pub(super) static LINKS_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// A new, empty folder of its own for one test (nothing in it is removed). + fn fresh_dir(tag: &str) -> PathBuf { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let d = std::env::temp_dir().join(format!("solidcraft-safe-write-{tag}-{}-{nanos}", std::process::id())); + fs::create_dir_all(&d).unwrap(); + d + } + + /// The time of a save with its backup, the backup linked against the backup copied (links + /// refused, as before hard links were used), taking turns. The file saved is + /// `SOLIDCRAFT_SAVE_BENCH_FILE` (a design), in a new folder in `SOLIDCRAFT_SAVE_BENCH_DIR` + /// (on the drive to measure; else the temporary folder). Run with `--ignored --nocapture`. + #[test] + #[ignore = "manual save measurement"] + fn save_time_with_the_backup_linked_or_copied() { + let Some(file) = std::env::var_os("SOLIDCRAFT_SAVE_BENCH_FILE") else { return }; + let bytes = fs::read(file).unwrap(); + let base = std::env::var_os("SOLIDCRAFT_SAVE_BENCH_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let d = base.join(format!("save-bench-{}-{nanos}", std::process::id())); + fs::create_dir_all(&d).unwrap(); + let p = d.join("design.solidcraft"); + write_atomic(&p, &bytes, true).unwrap(); + let rounds: usize = std::env::var("SOLIDCRAFT_SAVE_BENCH_ROUNDS").ok().and_then(|n| n.parse().ok()).unwrap_or(11); + let mut times = [Vec::new(), Vec::new()]; + for round in 0..2 * rounds { + let refused = round % 2 == 1; + LINKS_REFUSED.with(|r| r.set(refused)); + let t = std::time::Instant::now(); + write_atomic(&p, &bytes, true).unwrap(); + times[usize::from(refused)].push(t.elapsed().as_secs_f64() * 1000.0); + } + LINKS_REFUSED.with(|r| r.set(false)); + for (name, mut t) in ["linked", "copied"].into_iter().zip(times) { + t.sort_by(f64::total_cmp); + println!( + "SAVEBENCH bytes={} backup={name} median_ms={:.2} min_ms={:.2} max_ms={:.2} n={}", + bytes.len(), + t[t.len() / 2], + t[0], + t[t.len() - 1], + t.len() + ); + } + } + + /// Saves keep the previous version as the backup, stopped after any step or not, whether the + /// file system links the old file as the backup or refuses links (a FAT drive, a share) so it + /// is copied: the design file is the old version or the new one, whole, and the backup is + /// the version before it, never the one being written. + #[test] + fn the_backup_is_the_previous_version_linked_or_copied_and_a_stopped_save_keeps_both() { + for refused in [false, true] { + LINKS_REFUSED.with(|r| r.set(refused)); + let d = fresh_dir(if refused { "bak-copied" } else { "bak-linked" }); + let p = d.join("a.solidcraft"); + write_atomic(&p, b"one", true).unwrap(); + write_atomic(&p, b"two", true).unwrap(); + assert_eq!((fs::read(&p).unwrap(), fs::read(backup_path(&p)).unwrap()), (b"two".to_vec(), b"one".to_vec()), "refused {refused}"); + for stop in [Step::TempWritten, Step::BackupWritten] { + write_steps(&p, b"three", true, Some(stop)).unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"two", "{stop:?}, refused {refused}"); + let bak = fs::read(backup_path(&p)).unwrap(); + let want: &[u8] = if stop == Step::TempWritten { b"one" } else { b"two" }; + assert_eq!(bak, want, "{stop:?}, refused {refused}"); + assert!(!stale_temps(&p).is_empty(), "the stopped save's temporary file is left over"); + } + write_atomic(&p, b"four", true).unwrap(); + write_atomic(&p, b"five", true).unwrap(); + assert_eq!((fs::read(&p).unwrap(), fs::read(backup_path(&p)).unwrap()), (b"five".to_vec(), b"four".to_vec()), "refused {refused}"); + } + LINKS_REFUSED.with(|r| r.set(false)); + } + /// #5467: a lock is someone else's while it is refreshed; one left by a crash goes stale, and /// this app's own lock never counts as the design being open elsewhere. Writing a design's /// file changes its stamp. @@ -471,6 +599,34 @@ mod tests { let _ = fs::remove_dir_all(&d); } + /// Where links work the backup is the old file itself, not a copy: its inode, its + /// modification time and its permissions, with one name again once the save is done; + /// where they are refused it is a copy with the old file's permissions. + #[test] + fn the_backup_is_the_old_file_linked_or_a_copy_where_links_are_refused() { + use std::os::unix::fs::MetadataExt; + for refused in [false, true] { + LINKS_REFUSED.with(|r| r.set(refused)); + let d = fresh_dir(if refused { "inode-copied" } else { "inode-linked" }); + let p = d.join("a.solidcraft"); + write_atomic(&p, b"one", true).unwrap(); + fs::set_permissions(&p, fs::Permissions::from_mode(0o640)).unwrap(); + let old = fs::metadata(&p).unwrap(); + write_atomic(&p, b"two", true).unwrap(); + let bak = fs::metadata(backup_path(&p)).unwrap(); + let new = fs::metadata(&p).unwrap(); + assert_ne!(new.ino(), old.ino(), "the design file is a new file"); + assert_eq!(bak.ino() == old.ino(), !refused, "linked: the backup is the old file"); + if !refused { + assert_eq!(bak.modified().unwrap(), old.modified().unwrap(), "it keeps the old file's time"); + } + assert_eq!((bak.nlink(), new.nlink()), (1, 1), "one name each once the save is done"); + assert_eq!((mode(&p), mode(&backup_path(&p))), (0o640, 0o640), "refused {refused}"); + assert_eq!(fs::read(backup_path(&p)).unwrap(), b"one"); + } + LINKS_REFUSED.with(|r| r.set(false)); + } + #[test] fn a_save_through_a_link_keeps_the_targets_permissions() { let d = dir("linkmode"); diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index c4afcbc25..94e24aa65 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -407,6 +407,39 @@ fn frame_cost_of_a_design_file() { } } +/// A design from a file (`SOLIDCRAFT_SCALE_DESIGN`) open in two tabs, both with an unsaved change +/// the comparison with the saved design finds only at its end (a favourite, as a changed +/// appearance is): the time of an idle frame, and of one unsaved-changes check +/// (`Session::is_dirty`, which the tab strip and the autosave ask every frame). +#[test] +#[ignore = "manual measurement on a design file"] +fn idle_frame_cost_of_two_unsaved_tabs() { + let Some(path) = std::env::var_os("SOLIDCRAFT_SCALE_DESIGN") else { return }; + let path = path.to_string_lossy().to_string(); + let open = || { + let (doc, saved) = solidcraft_engine::io::read_design_file(&path, None::).unwrap(); + let mut s = solidcraft_engine::Session::opened(doc, saved.as_ref()); + s.doc_mut().favorites.insert("idle-measurement".into()); + s.revision += 1; + s + }; + let mut h = Harness::new(); + h.app.session = open(); + crate::documents::open_tab(&mut h.app, open()).unwrap(); + assert!(h.app.session.is_dirty()); + h.frames(5); + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + (v[v.len() / 2], v[0], v[v.len() - 1]) + }; + let (frame, frame_min, frame_max) = median((0..30).map(|_| ms(|| h.frame())).collect()); + let (dirty, dirty_min, dirty_max) = median((0..30).map(|_| ms(|| assert!(std::hint::black_box(h.app.session.is_dirty())))).collect()); + let bodies = h.app.session.model.state().bodies.len(); + println!( + "IDLE2TABS bodies={bodies} idle_frame_ms={frame:.3} ({frame_min:.3}-{frame_max:.3}) is_dirty_ms={dirty:.4} ({dirty_min:.4}-{dirty_max:.4})" + ); +} + /// A whole assembly's hover highlight: the model's own triangles (its display plans on the GPU) /// against the copy of every triangle it used to build here. Run with `--ignored --nocapture`. #[test]