From ccfa5fbdac9a8e700deb97217fb16654690501ca Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 17 Nov 2026 16:19:38 +0000 Subject: [PATCH] theme-store: save over a library theme Store::save_theme replaces a library theme under the suite lock when its file still has the stamp the caller loaded it with (StoreError::Changed otherwise; built-ins refused) and bumps library_revision, sharing the import/delete write steps. The disk backend replaces through craft_atomic with the existing pre-rename guard, which now checks bytes for selection.json and the stamp for a theme. Op::Save / OpOutput::Saved on the worker; SuiteClient::save_theme, is_saving and take_saved, one save in flight. Tests: store save, changed stamp, built-in refusal, client round trip, and a save child in two_processes. --- crates/theme-store/README.md | 6 +- crates/theme-store/src/backend.rs | 21 ++++++- crates/theme-store/src/client.rs | 70 +++++++++++++++++++++- crates/theme-store/src/client/tests.rs | 30 +++++++++- crates/theme-store/src/disk.rs | 73 ++++++++++++++++++----- crates/theme-store/src/lib.rs | 2 +- crates/theme-store/src/store.rs | 61 ++++++++++++++++++- crates/theme-store/src/tests.rs | 63 ++++++++++++++++++- crates/theme-store/src/watch.rs | 12 ++++ crates/theme-store/tests/two_processes.rs | 42 +++++++++---- docs/suite-themes.md | 7 ++- 11 files changed, 345 insertions(+), 42 deletions(-) diff --git a/crates/theme-store/README.md b/crates/theme-store/README.md index c941aa4b3..aee95da6a 100644 --- a/crates/theme-store/README.md +++ b/crates/theme-store/README.md @@ -30,13 +30,13 @@ match store.update(&base, SelectionChange::pick_theme(&picked)) { | Item | What it is | |---|---| | `SuiteDir` | `CRAFT_SUITE_DIR` (empty: in memory), in memory for isolated apps, else `ArtCraft/themes` in the local config folder | -| `Store` | `load_selection`, `update`, `import`, `delete`, `export`, `library`, `load_theme`, `theme` (a `resolve` lookup) | +| `Store` | `load_selection`, `update`, `import`, `save_theme`, `delete`, `export`, `library`, `load_theme`, `theme` (a `resolve` lookup) | | `SelectionChange` | the fields the user changed (`theme_light`, `theme_dark`, `mode`, `contrast`, `size`, `text_size`); only these are written, each merged on its own | | `Accepted` | `suite` (craft-theme's `SuiteChoice`: each field `None` until a user chooses it), `revision`, `library_revision`; serde, for the copy apps keep in their preferences | -| `StoreError` | `Busy`, `Conflict { disk }`, `IdExists`, `InUse`, … ; nothing on disk changed | +| `StoreError` | `Busy`, `Conflict { disk }`, `Changed` (a library file another app saved over), `IdExists`, `InUse`, … ; nothing on disk changed | | `Problem` | damaged, too new or unreadable files; the store keeps its last accepted state | | `ThemeRecord`, `ThemeEntry`, `format` | a parsed user theme file (`craft-design-theme` v1, craft-theme's `format`) with its stored bytes, unknown keys included; the library skips files in another format, such as the pilot's `craft-theme` | -| `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card | +| `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card, `save_theme` and `take_saved` for a theme editor | | `SuiteWatch`, `Snapshot`, `Op`, `OpOutput` | the store on a worker thread: snapshots by generation, queued operations with results | | `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size and UI Font Size; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page | | `FileStamp`, `library_files`, `selection_stamp`, `theme_stamp`, `parse_counts` | cheap change checks for a watcher | diff --git a/crates/theme-store/src/backend.rs b/crates/theme-store/src/backend.rs index 1534bf1b1..596816874 100644 --- a/crates/theme-store/src/backend.rs +++ b/crates/theme-store/src/backend.rs @@ -38,8 +38,8 @@ pub struct LibraryFile { // Only the disk backend fails these ways; web builds have none. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) enum WriteError { - /// `selection.json` changed between the read under the lock and the rename: another - /// writer ignored the lock (network file systems). + /// The file changed between the read under the lock and the rename: another writer ignored + /// the lock (network file systems). For a theme, also a file that isn't the expected one. Raced, Io(io::Error), } @@ -209,6 +209,23 @@ impl Backend { } } + /// Replaces a theme file whose stamp is `expected` and returns the new file's stamp; + /// [`WriteError::Raced`] when the file is missing or has another stamp. + pub fn replace_theme(&mut self, stem: &str, bytes: &[u8], expected: FileStamp) -> Result { + match self { + Backend::Memory(m) => { + if m.library.get(stem).is_none_or(|(b, s)| mem_stamp(b, *s) != expected) { + return Err(WriteError::Raced); + } + let serial = m.next(); + m.library.insert(stem.to_owned(), (Arc::from(bytes), serial)); + Ok(mem_stamp(bytes, serial)) + } + #[cfg(not(target_arch = "wasm32"))] + Backend::Disk(d) => d.replace_theme(stem, bytes, expected), + } + } + /// Renames a theme to a hidden name that listings skip; `NotFound` when there is none. pub fn hide_theme(&mut self, stem: &str) -> io::Result<()> { match self { diff --git a/crates/theme-store/src/client.rs b/crates/theme-store/src/client.rs index e7cb5e352..72cea2c6d 100644 --- a/crates/theme-store/src/client.rs +++ b/crates/theme-store/src/client.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use craft_theme::{SuiteChoice, ThemeDef, ThemeId, ThemePair}; -use crate::{Accepted, Op, Problem, SelectionChange, Snapshot, StoreError, SuiteWatch, watch::with_library_theme}; +use crate::{Accepted, FileStamp, Op, OpOutput, Problem, SelectionChange, Snapshot, StoreError, SuiteWatch, watch::with_library_theme}; /// A change sent to the watch and not answered yet. #[derive(Clone, Debug)] @@ -24,6 +24,9 @@ struct Pending { /// At most one change is in flight. Picks made meanwhile merge into one queued change (a later /// pick of a field replaces the earlier one), which goes out with the new accepted state as /// base when the first result arrives, so quick picks never conflict with each other. +/// +/// A theme editor saves with [`save_theme`](Self::save_theme), one save at a time, and takes the +/// answer with [`take_saved`](Self::take_saved). pub struct SuiteClient { watch: SuiteWatch, generation: Option, @@ -32,6 +35,9 @@ pub struct SuiteClient { queued: Option, conflict: Option<(Accepted, SelectionChange)>, failure: Option<(SelectionChange, StoreError)>, + /// The save in flight: its request id and theme. + saving: Option<(u64, ThemeId)>, + saved: Option<(ThemeId, Result)>, app_theme: Option, /// Open couldn't read `selection.json`: changes wait in the queue for the worker's first /// snapshot instead of merging against a state nobody read. @@ -44,7 +50,19 @@ impl SuiteClient { let snapshot = watch.snapshot(); let app_theme = watch.initial_app_theme().cloned(); let hold = !watch.selection_read(); - SuiteClient { watch, generation: None, snapshot, pending: None, queued: None, conflict: None, failure: None, app_theme, hold } + SuiteClient { + watch, + generation: None, + snapshot, + pending: None, + queued: None, + conflict: None, + failure: None, + saving: None, + saved: None, + app_theme, + hold, + } } /// An in-memory suite, for app constructors, tests and web builds. @@ -70,9 +88,57 @@ impl SuiteClient { } } self.settle(); + self.settle_save(); true } + fn settle_save(&mut self) { + let Some((request, _)) = &self.saving else { + return; + }; + let request = *request; + let result = match self.snapshot.result(request) { + Some(Ok(OpOutput::Saved(stamp))) => Ok(*stamp), + Some(Err(error)) => Err(error.clone()), + // A save's result is always `Saved`. + Some(Ok(_)) => Err(StoreError::Lost), + // Pushed out of the snapshot by newer results before this sync. + None if self.snapshot.results.first().is_some_and(|(id, _)| *id > request) => Err(StoreError::Lost), + None => return, + }; + if let Some((_, id)) = self.saving.take() { + self.saved = Some((id, result)); + } + } + + /// Saves `bytes` over library theme `id` ([`Store::save_theme`](crate::Store::save_theme)). + /// `expected` is the file's stamp when the app loaded it, or the stamp the last save of it + /// returned. One save at a time: while one is in flight this sends nothing and returns false. + /// The answer of an earlier save not yet taken is dropped. + pub fn save_theme(&mut self, id: ThemeId, bytes: Arc<[u8]>, expected: FileStamp) -> bool { + if self.saving.is_some() { + return false; + } + self.saved = None; + let request = self.watch.request(Op::Save { id: id.clone(), bytes, expected }); + self.saving = Some((request, id)); + true + } + + /// True while a save is in flight. + pub fn is_saving(&self) -> bool { + self.saving.is_some() + } + + /// The answer to the last save, once [`sync`](Self::sync) has seen it: the theme and the new + /// file's stamp, the `expected` stamp for its next save. [`StoreError::Changed`] means + /// another app saved over the theme since it was loaded; [`StoreError::Lost`] that the answer + /// was gone before the client looked, and the theme's entry in the snapshot's index shows + /// what is on disk. + pub fn take_saved(&mut self) -> Option<(ThemeId, Result)> { + self.saved.take() + } + fn settle(&mut self) { let Some(pending) = &self.pending else { return; diff --git a/crates/theme-store/src/client/tests.rs b/crates/theme-store/src/client/tests.rs index 04c10a5c5..54768ed7d 100644 --- a/crates/theme-store/src/client/tests.rs +++ b/crates/theme-store/src/client/tests.rs @@ -10,7 +10,7 @@ use craft_theme::{ContrastChoice, ModeChoice, SuiteChoice, TextSize, ThemeId, Th use super::SuiteClient; use crate::{ - Op, SelectionChange, StoreOptions, SuiteDir, SuiteWatch, + Op, SelectionChange, StoreError, StoreOptions, SuiteDir, SuiteWatch, testing::{SAMPLE_THEME_ID, SAMPLE_THEME_JSON}, }; @@ -127,3 +127,31 @@ fn a_library_theme_on_its_way_never_shows_the_app_default() { own.sync(); assert!(!own.is_loading(&id("gone"))); } + +#[trial] +fn a_save_through_the_client_reports_the_new_stamp() { + let mut client = SuiteClient::memory(); + client.sync(); + client.watch().request(Op::Import { bytes: Arc::from(SAMPLE_THEME_JSON.as_bytes()), as_copy: false }); + client.sync(); + let sample = id(SAMPLE_THEME_ID); + let entry = |client: &SuiteClient| client.snapshot().index.iter().find(|e| e.id == sample).cloned().unwrap(); + let loaded = entry(&client).stamp; + let edited: Arc<[u8]> = Arc::from(SAMPLE_THEME_JSON.replace("\"version\": 3", "\"version\": 4").as_bytes()); + + assert!(client.save_theme(sample.clone(), Arc::clone(&edited), loaded)); + // One save at a time. + assert!(!client.save_theme(sample.clone(), Arc::clone(&edited), loaded)); + assert!(client.is_saving()); + client.sync(); + assert!(!client.is_saving()); + let (saved, stamp) = client.take_saved().unwrap(); + let stamp = stamp.unwrap(); + assert_eq!(saved, sample); + assert_eq!((entry(&client).stamp, entry(&client).version), (stamp, 4)); + + // The stamp from before the save is stale now. + assert!(client.save_theme(sample.clone(), edited, loaded)); + client.sync(); + assert!(matches!(client.take_saved(), Some((_, Err(StoreError::Changed(_)))))); +} diff --git a/crates/theme-store/src/disk.rs b/crates/theme-store/src/disk.rs index fac920528..0c0f5d776 100644 --- a/crates/theme-store/src/disk.rs +++ b/crates/theme-store/src/disk.rs @@ -77,8 +77,24 @@ impl Disk { pub fn write_selection(&self, bytes: &[u8], expected: Option<&[u8]>) -> Result<(), WriteError> { let path = self.selection_path(); - let guard = Guarded { inner: &*self.fs, path: &path, expected, raced: Cell::new(false) }; - match private().atomic_write_custom(&guard, RenameRetry::platform(), &path, bytes) { + self.write_guarded(&path, bytes, Expected::Bytes(expected)) + } + + pub fn replace_theme(&self, stem: &str, bytes: &[u8], expected: FileStamp) -> Result { + let path = self.theme_path(stem); + self.write_guarded(&path, bytes, Expected::Stamp(expected))?; + match self.stamp(&path) { + Ok(Some(stamp)) => Ok(stamp), + Ok(None) => Err(WriteError::Io(io::ErrorKind::NotFound.into())), + Err(e) => Err(WriteError::Io(e)), + } + } + + /// Replaces `path` atomically, unless it no longer is what `expected` says just before the + /// rename. + fn write_guarded(&self, path: &Path, bytes: &[u8], expected: Expected<'_>) -> Result<(), WriteError> { + let guard = Guarded { inner: &*self.fs, path, expected, raced: Cell::new(false) }; + match private().atomic_write_custom(&guard, RenameRetry::platform(), path, bytes) { Ok(()) => Ok(()), Err(_) if guard.raced.get() => Err(WriteError::Raced), Err(e) => Err(WriteError::Io(e)), @@ -172,9 +188,10 @@ fn locking_unsupported(e: &io::Error) -> bool { e.kind() == io::ErrorKind::Unsupported || e.raw_os_error() == Some(ENOLCK) } -/// Library files are written once (an import creates one, a delete removes it), so their stamps -/// are the only change check: a hand edit in place that keeps length and modification time goes -/// unnoticed. `selection.json`, which is replaced on every write, also gets byte comparisons. +/// Library files change only by whole-file writes (an import creates one, a save replaces it, a +/// delete removes it), each a new file, so their stamps are the only change check: a hand edit in +/// place that keeps length and modification time goes unnoticed. `selection.json`, which is +/// replaced on every write, also gets byte comparisons. fn stamp_of(meta: &fs::Metadata) -> FileStamp { let modified_nanos = meta.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_nanos()); #[cfg(unix)] @@ -184,16 +201,45 @@ fn stamp_of(meta: &fs::Metadata) -> FileStamp { FileStamp { len: meta.len(), modified_nanos, identity } } -/// Checks `selection.json` once more just before the rename that replaces it. Advisory locks -/// can be unreliable on network file systems; a file that changed under the lock means another -/// writer, and the write is abandoned instead of overwriting its change. +/// What a guarded write expects to replace. +#[derive(Clone, Copy)] +enum Expected<'a> { + /// `selection.json`'s bytes as read under the lock; `None` for a missing file. + Bytes(Option<&'a [u8]>), + /// A library file's stamp when the caller loaded it. + Stamp(FileStamp), +} + +/// Checks the file once more just before the rename that replaces it. Advisory locks can be +/// unreliable on network file systems; a file that changed under the lock means another writer, +/// and the write is abandoned instead of overwriting its change. struct Guarded<'a> { inner: &'a dyn AtomicFs, path: &'a Path, - expected: Option<&'a [u8]>, + expected: Expected<'a>, raced: Cell, } +impl Guarded<'_> { + fn unchanged(&self) -> io::Result { + match self.expected { + Expected::Bytes(expected) => { + let now = match fs::read(self.path) { + Ok(bytes) => Some(bytes), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => return Err(e), + }; + Ok(now.as_deref() == expected) + } + Expected::Stamp(expected) => match fs::metadata(self.path) { + Ok(meta) => Ok(stamp_of(&meta) == expected), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e), + }, + } + } +} + impl AtomicFs for Guarded<'_> { fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { self.inner.create_new(path, permissions) @@ -204,14 +250,9 @@ impl AtomicFs for Guarded<'_> { } fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { - let now = match fs::read(self.path) { - Ok(bytes) => Some(bytes), - Err(e) if e.kind() == io::ErrorKind::NotFound => None, - Err(e) => return Err(e), - }; - if now.as_deref() != self.expected { + if !self.unchanged()? { self.raced.set(true); - return Err(io::Error::other("selection.json changed while it was being written")); + return Err(io::Error::other(format!("{} changed while it was being written", self.path.display()))); } self.inner.rename(from, to) } diff --git a/crates/theme-store/src/lib.rs b/crates/theme-store/src/lib.rs index a1868c5d9..ce039617d 100644 --- a/crates/theme-store/src/lib.rs +++ b/crates/theme-store/src/lib.rs @@ -57,7 +57,7 @@ pub use craft_theme::format; pub use craft_theme::format::{FormatError, FormatErrors, MAX_THEME_BYTES}; pub use dir::{DirSource, SUITE_DIR_ENV, SuiteDir}; pub use selection::{Accepted, MAX_SELECTION_BYTES, SELECTION_SCHEMA_VERSION, SelectionChange, SelectionError}; -pub use store::{Imported, LOCK_TIMEOUT, Library, ParseCounts, Problem, Store, StoreError, StoreOptions, ThemeEntry, ThemeRecord}; +pub use store::{Imported, LOCK_TIMEOUT, Library, ParseCounts, Problem, Saved, Store, StoreError, StoreOptions, ThemeEntry, ThemeRecord}; pub use watch::{Op, OpOutput, RESULTS_KEPT, STAT_INTERVAL, Snapshot, SuiteWatch, VERIFY_INTERVAL}; #[cfg(test)] diff --git a/crates/theme-store/src/store.rs b/crates/theme-store/src/store.rs index 6babf39c1..70fb59c18 100644 --- a/crates/theme-store/src/store.rs +++ b/crates/theme-store/src/store.rs @@ -112,7 +112,10 @@ pub enum StoreError { InUse(ThemeId), /// No library theme has this id. NotFound(ThemeId), - /// Built-in themes can't be deleted. + /// The library theme's file changed since the caller loaded it: another app saved over it. + /// Offer to reload it, to overwrite it, or to save as a new theme. + Changed(ThemeId), + /// Built-in themes can't be changed or deleted. BuiltIn(ThemeId), /// The watch no longer had the result of this change when the client looked, and the /// suite's state doesn't show it. Retry. @@ -260,6 +263,17 @@ pub struct Imported { pub accepted: Accepted, } +/// A successful save. +#[derive(Clone, Debug)] +pub struct Saved { + /// The stored theme. + pub record: ThemeRecord, + /// The new file's stamp: the `expected` stamp for the next save. + pub stamp: FileStamp, + /// The selection after the save. + pub accepted: Accepted, +} + /// How many times the store has parsed each kind of file, for tests that check work is not /// repeated. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -457,6 +471,48 @@ impl Store { Err(StoreError::IdExists(id)) } + /// Replaces library theme `id` with `bytes`, keeping them exactly, when its file still has + /// the stamp `expected` it had when the caller loaded it; otherwise [`StoreError::Changed`] + /// and the file stays as it is. The file's `id` must be `id`. Built-ins are refused. Like an + /// import, a save bumps `library_revision`, so watchers list the new file. + pub fn save_theme(&mut self, id: &ThemeId, bytes: &[u8], expected: FileStamp) -> Result { + if id.is_builtin() { + return Err(StoreError::BuiltIn(id.clone())); + } + let stem = user_stem(id)?; + let record = self.parse_theme_counted(bytes).map_err(StoreError::Format)?; + if record.theme.id != *id { + return Err(StoreError::FileName { id: record.theme.id }); + } + let _lock = self.lock()?; + let base = self.accepted.clone(); + let disk = self.read_for_write(&base)?; + match self.backend.theme_stamp(stem)? { + None => return Err(StoreError::NotFound(id.clone())), + Some(stamp) if stamp != expected => return Err(StoreError::Changed(id.clone())), + Some(_) => {} + } + let old = self.backend.read_theme(stem, MAX_THEME_BYTES)?.ok_or_else(|| StoreError::NotFound(id.clone()))?; + // The file goes first, so a watcher that sees the new library revision lists it. + let stamp = match self.backend.replace_theme(stem, &record.bytes, expected) { + Ok(stamp) => stamp, + Err(WriteError::Raced) => return Err(StoreError::Changed(id.clone())), + Err(WriteError::Io(e)) => return Err(e.into()), + }; + match self.commit(&disk, library_bump(&disk.accepted)) { + Ok(accepted) => Ok(Saved { record, stamp, accepted }), + Err(e) => { + // The old bytes go back as a new file, so on disk its stamp is not `expected` + // any more (it includes the inode): a retry with that stamp gets `Changed`. A + // file over the size limit was read only in part and is left replaced. + if old.len() <= MAX_THEME_BYTES { + let _ = self.backend.replace_theme(stem, &old, stamp); + } + Err(e) + } + } + } + /// Removes a library theme. A theme in either slot of the suite selection can't be deleted; /// per-app choices that name it fall back to the app default when they resolve. /// @@ -681,7 +737,8 @@ impl fmt::Display for StoreError { StoreError::IdExists(id) => write!(f, "a theme with the id {id} is already installed"), StoreError::InUse(id) => write!(f, "{id} is a suite theme; choose another theme before deleting it"), StoreError::NotFound(id) => write!(f, "there is no theme {id}"), - StoreError::BuiltIn(id) => write!(f, "{id} is a built-in theme and can't be deleted"), + StoreError::Changed(id) => write!(f, "{id} was changed in another Craft app since it was opened"), + StoreError::BuiltIn(id) => write!(f, "{id} is a built-in theme; it can't be changed or deleted"), StoreError::Lost => f.write_str("the result of this change was lost; it may not have been saved"), } } diff --git a/crates/theme-store/src/tests.rs b/crates/theme-store/src/tests.rs index c08a11803..62a41a71a 100644 --- a/crates/theme-store/src/tests.rs +++ b/crates/theme-store/src/tests.rs @@ -6,7 +6,7 @@ use std::{fs, path::Path, time::Duration}; use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Selection, Size, TextSize, ThemeId, ThemePair}; use crate::{ - Accepted, Problem, SelectionChange, SelectionError, Store, StoreError, StoreOptions, SuiteDir, + Accepted, FileStamp, Problem, SelectionChange, SelectionError, Store, StoreError, StoreOptions, SuiteDir, testing::{FailAt, FailingFs, SAMPLE_THEME_JSON}, }; @@ -117,9 +117,70 @@ fn ids_users_cant_create_never_reach_the_file_system() { assert!(matches!(store.export(&con), Err(StoreError::NotFound(_)))); assert!(matches!(store.delete(&con), Err(StoreError::NotFound(_)))); assert!(store.theme(&con).is_none()); + let listed = store.library_files().unwrap()[0].stamp; + assert!(matches!(store.save_theme(&con, theme_json("con", "").as_bytes(), listed), Err(StoreError::NotFound(_)))); + let graphite = id("craft.graphite"); + assert!(matches!(store.save_theme(&graphite, theme_json("con", "").as_bytes(), listed), Err(StoreError::BuiltIn(_)))); // A library theme that doesn't exist is never written as the suite's, in either slot. assert!(matches!(store.update(&Accepted::default(), theme("con")), Err(StoreError::NotFound(_)))); assert!(matches!(store.update(&Accepted::default(), SelectionChange::theme_dark(id("gone"))), Err(StoreError::NotFound(_)))); assert!(library.join("con.json").exists()); assert!(!tmp.path().join("selection.json").exists()); } + +#[trial] +fn a_save_replaces_the_library_file_and_moves_the_library_revision() { + let tmp = tempfile::tempdir().unwrap(); + for dir in [SuiteDir::at(tmp.path()), SuiteDir::memory()] { + let mut store = Store::open(&dir, options()); + let imported = store.import(theme_json("one", "").as_bytes(), false).unwrap().accepted; + let loaded = store.theme_stamp(&id("one")).unwrap().unwrap(); + let second = theme_json("one", r#","version":2"#); + let saved = store.save_theme(&id("one"), second.as_bytes(), loaded).unwrap(); + assert_eq!(&*store.load_theme(&id("one")).unwrap().bytes, second.as_bytes()); + assert_eq!(store.theme_stamp(&id("one")).unwrap(), Some(saved.stamp)); + assert_ne!(saved.stamp, loaded); + let moved = (saved.accepted.revision, saved.accepted.library_revision); + assert_eq!(moved, (imported.revision + 1, imported.library_revision + 1)); + // The next save goes from the stamp the last one returned. + store.save_theme(&id("one"), theme_json("one", r#","version":3"#).as_bytes(), saved.stamp).unwrap(); + assert_eq!(store.load_theme(&id("one")).unwrap().theme.version, 3); + } +} + +#[trial] +fn a_save_over_a_changed_file_is_refused_and_leaves_it() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("library").join("one.json"); + let mut mine = open(tmp.path()); + let mut other = open(tmp.path()); + mine.import(theme_json("one", "").as_bytes(), false).unwrap(); + let loaded = mine.theme_stamp(&id("one")).unwrap().unwrap(); + let save = |store: &mut Store, stamp: FileStamp, version: u32| { + store.save_theme(&id("one"), theme_json("one", &format!(r#","version":{version}"#)).as_bytes(), stamp) + }; + assert!(matches!(mine.save_theme(&id("one"), theme_json("two", "").as_bytes(), loaded), Err(StoreError::FileName { .. }))); + + // Another app saved over it. + other.save_theme(&id("one"), theme_json("one", r#","version":2"#).as_bytes(), loaded).unwrap(); + let theirs = fs::read_to_string(&path).unwrap(); + mine.load_selection().unwrap(); + let before = mine.accepted().clone(); + assert!(matches!(save(&mut mine, loaded, 3), Err(StoreError::Changed(_)))); + assert_eq!(fs::read_to_string(&path).unwrap(), theirs); + mine.load_selection().unwrap(); + assert_eq!(mine.accepted(), &before); + + // Edited by hand (another length, so the stamp moves however coarse the clock). + let now = mine.theme_stamp(&id("one")).unwrap().unwrap(); + let hand = theme_json("one", r#","version":40"#); + fs::write(&path, &hand).unwrap(); + assert!(matches!(save(&mut mine, now, 5), Err(StoreError::Changed(_)))); + assert_eq!(fs::read_to_string(&path).unwrap(), hand); + + // Deleted. + let now = mine.theme_stamp(&id("one")).unwrap().unwrap(); + mine.delete(&id("one")).unwrap(); + assert!(matches!(save(&mut mine, now, 6), Err(StoreError::NotFound(_)))); + assert!(!path.exists()); +} diff --git a/crates/theme-store/src/watch.rs b/crates/theme-store/src/watch.rs index 5301b4c3d..1bed2bb8e 100644 --- a/crates/theme-store/src/watch.rs +++ b/crates/theme-store/src/watch.rs @@ -49,6 +49,15 @@ pub enum Op { /// Give the theme a new id when its id is already in the library, instead of failing. as_copy: bool, }, + /// Replaces a library theme ([`Store::save_theme`]); the result is [`OpOutput::Saved`]. + Save { + /// The library theme to replace. + id: ThemeId, + /// The new theme file's contents. + bytes: Arc<[u8]>, + /// The file's stamp when the app loaded it, or from its last save. + expected: FileStamp, + }, /// Removes a library theme ([`Store::delete`]). Delete(ThemeId), /// A theme file for sharing ([`Store::export`]); the result is [`OpOutput::Exported`]. @@ -71,6 +80,8 @@ pub enum OpOutput { Exported(Arc<[u8]>), /// The stored id; for an import as copy, the new one. Imported(ThemeId), + /// The saved file's stamp: the `expected` stamp for the next save. + Saved(FileStamp), } /// The state of the suite folder at one generation. Snapshots never change; a new one replaces @@ -694,6 +705,7 @@ impl Engine { let result = match op { Op::Update { base, change } => self.store.update(&base, change).map(|_| OpOutput::Done), Op::Import { bytes, as_copy } => self.store.import(&bytes, as_copy).map(|i| OpOutput::Imported(i.record.theme.id)), + Op::Save { id, bytes, expected } => self.store.save_theme(&id, &bytes, expected).map(|s| OpOutput::Saved(s.stamp)), Op::Delete(theme) => self.store.delete(&theme).map(|_| OpOutput::Done), Op::Export(theme) => self.store.export(&theme).map(OpOutput::Exported), Op::Rescan => { diff --git a/crates/theme-store/tests/two_processes.rs b/crates/theme-store/tests/two_processes.rs index 22ea365be..b7044e6b8 100644 --- a/crates/theme-store/tests/two_processes.rs +++ b/crates/theme-store/tests/two_processes.rs @@ -1,5 +1,7 @@ -//! Two processes updating different fields of the suite selection at once: every update lands -//! and neither overwrites the other's field. The test binary runs itself as the two children. +//! Three processes writing the suite folder at once, two updating different fields of the suite +//! selection and one saving over a library theme: every write lands, neither update overwrites +//! the other's field, and another process reads the last save. The test binary runs itself as +//! the three children. #![cfg(not(target_arch = "wasm32"))] use craft_ui::testing::trial; @@ -13,11 +15,20 @@ const DIR: &str = "CRAFT_THEME_STORE_TEST_DIR"; const UPDATES: u64 = 200; const THEMES: [&str; 2] = ["craft.graphite", "craft.studio"]; const MODES: [ModeChoice; 2] = [ModeChoice::Light, ModeChoice::Dark]; +const SAVED: &str = "saved"; fn both(theme: &str) -> SelectionChange { SelectionChange::themes(ThemePair::same(ThemeId::parse(theme).unwrap())) } +/// The library theme the save child writes, at `version`. +fn saved_file(version: u64) -> String { + format!( + r##"{{"schema":"craft-design-theme","schema_version":1,"id":"{SAVED}","name":"Saved","version":{version},"variants":"dark", + "seeds":{{"accent":"#4b8bf5","neutral":"#26262a","status":{{"good":"#3fd6b8","warn":"#ffc14d","bad":"#ff6259","info":"#4b8bf5"}}}}}}"## + ) +} + #[trial] fn two_processes_keep_every_update() { if let (Ok(role), Ok(dir)) = (std::env::var(ROLE), std::env::var(DIR)) { @@ -28,9 +39,10 @@ fn two_processes_keep_every_update() { // Both children start from an existing selection, so neither takes the no-base path. let mut store = Store::open(&SuiteDir::at(tmp.path()), StoreOptions::new("parent")); store.update(&Accepted::default(), both("craft.artcraft").then(SelectionChange::mode(ModeChoice::System))).unwrap(); + store.import(saved_file(1).as_bytes(), false).unwrap(); let exe = std::env::current_exe().unwrap(); - let children: Vec<_> = ["theme", "mode"] + let children: Vec<_> = ["theme", "mode", "save"] .into_iter() .map(|role| { Command::new(&exe) @@ -50,30 +62,36 @@ fn two_processes_keep_every_update() { store.load_selection().unwrap(); let last = (UPDATES - 1) as usize % 2; let accepted = store.accepted(); - assert_eq!(accepted.revision, 1 + 2 * UPDATES); + assert_eq!((accepted.revision, accepted.library_revision), (2 + 3 * UPDATES, 1 + UPDATES)); let theme = Some(ThemeId::parse(THEMES[last]).unwrap()); assert_eq!(accepted.suite, SuiteChoice { theme_light: theme.clone(), theme_dark: theme, mode: Some(MODES[last]), ..SuiteChoice::default() }); + let saved = store.load_theme(&ThemeId::parse(SAVED).unwrap()).unwrap(); + assert_eq!(&*saved.bytes, saved_file(1 + UPDATES).as_bytes()); } /// Each update changes one field relative to this child's own last write, which is stale for -/// the other child's field: the merge has to keep the disk value there. +/// the other child's field: the merge has to keep the disk value there. Each save goes from the +/// stamp of the child's own last save. fn child(role: &str, dir: &Path) { let mut store = Store::open(&SuiteDir::at(dir), StoreOptions::new(format!("child {role}"))); store.load_selection().unwrap(); + let saved = ThemeId::parse(SAVED).unwrap(); + let mut stamp = store.theme_stamp(&saved).unwrap().unwrap(); while !dir.join("go").exists() { std::thread::yield_now(); } for i in 0..UPDATES as usize { let base = store.accepted().clone(); - let mine = match role { - "theme" => both(THEMES[i % 2]), - _ => SelectionChange::mode(MODES[i % 2]), - }; loop { - match store.update(&base, mine.clone()) { - Ok(_) => break, + let written = match role { + "theme" => store.update(&base, both(THEMES[i % 2])).map(drop), + "mode" => store.update(&base, SelectionChange::mode(MODES[i % 2])).map(drop), + _ => store.save_theme(&saved, saved_file(i as u64 + 2).as_bytes(), stamp).map(|s| stamp = s.stamp), + }; + match written { + Ok(()) => break, Err(StoreError::Busy) => continue, - Err(e) => panic!("{role} update {i}: {e}"), + Err(e) => panic!("{role} write {i}: {e}"), } } } diff --git a/docs/suite-themes.md b/docs/suite-themes.md index 61b45466a..b0cb6bdba 100644 --- a/docs/suite-themes.md +++ b/docs/suite-themes.md @@ -227,6 +227,9 @@ Library operations take the same lock and bump `library_revision`: - **Import** validates the file and writes its original bytes to `library/.json`, never replacing a file (`IdExists`); "import as copy" picks the first free `-2`, `-3` ... +- **Save** replaces a library theme with new bytes when its file still has the stamp the caller + loaded it with; a file another app replaced since is `Changed` and stays as it is. Built-ins + are refused (`BuiltIn`). - **Delete** refuses built-ins and a theme in either suite slot (`InUse`). - **Export** returns a library theme's stored bytes, or a built-in written as a theme file. @@ -242,8 +245,8 @@ use every 500 ms, compares bytes every 10 s, and lists the library only when `li changes or on `Op::Rescan`. Each change publishes a snapshot and calls `wake` once. Each frame the app compares `generation()` (one atomic load) with its cache key and rebuilds its -styles only when it changed. Changes go through `request(Op)`: `Update`, `Import`, `Delete`, -`Export`, `Rescan` and `AppTheme`; the result appears in `snapshot().result(id)`. `SuiteWatch::memory()` +styles only when it changed. Changes go through `request(Op)`: `Update`, `Import`, `Save`, +`Delete`, `Export`, `Rescan` and `AppTheme`; the result appears in `snapshot().result(id)`. `SuiteWatch::memory()` runs without a thread, applying each request before it returns. The lock file and revision protocol follow