From 277fcd5f8cd599d861a69510d4378c9b0cd38fdd Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:28:22 -0600 Subject: [PATCH 01/27] fix(engine): saved data sources keep what a newer RustGIS wrote, and two windows don't overwrite each other's (#1962) A saved source whose details came from a newer RustGIS (a number, a list, more than eight entries) was read, cleaned and written back cleaned on the next save. Details this version can't use are now kept as they were and written back beside the ones it uses, until the source is saved again with other details. A row holding a password, key or token is still cleaned and said, as before. Two desktop windows each wrote their whole list of sources, so the last one to save dropped the other's changes. A save now reads what is stored again under a lock shared by every copy of RustGIS, lays this window's own additions and removals over it, and writes the result; a removed source stays removed, and a source this window changed keeps its own details. With nothing stored, or only what this window last wrote, its whole list is written. Every preference write takes the same lock and never waits for it: while another copy saves, or when the stored sources can't be read or the save fails, the change stays to save and is tried again later, and once more as the app closes. --- apps/rustgis-web/src/web.rs | 3 + apps/rustgis/src/main.rs | 40 ++- crates/data/src/io.rs | 43 +++ crates/engine/src/prefs.rs | 342 +++++++++++++++++++- crates/engine/src/sources.rs | 499 ++++++++++++++++++++++++++---- crates/ui-egui/src/lib.rs | 37 +++ crates/ui-egui/src/sourcespane.rs | 184 ++++++++++- crates/ui-egui/tests/smoke.rs | 181 +++++++++++ 8 files changed, 1263 insertions(+), 66 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e8c00d8565..482de5f83d 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1219,6 +1219,9 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e arcgis_sign_in: Some(Box::new(move |portal, client_id, slot| crate::arcgis::sign_in(portal, client_id, slot, arcgis_ctx.clone()))), load_pref: Some(load_pref), save_pref: Some(save_pref), + // One copy of RustGIS a page keeps its preferences: nothing stored to merge with. + update_pref: None, + retry_prefs: None, // No keychain in the browser: script on the page could read anything stored (#754). secrets: None, // No autosave in the browser yet: localStorage is too small for a project (#873). diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index c911001e79..2c72fdcc07 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -110,6 +110,15 @@ mod prefs { } } + /// Writes again the settings left to save while another copy of RustGIS saved its own, + /// waiting up to `wait` for it (none on the UI thread); what they came to is kept as + /// [`saved`] keeps it. Whether any is still left. + pub fn retry_saves(wait: std::time::Duration) -> bool { + let (results, left) = rustgis_engine::prefs::retry_pending(wait); + results.into_iter().for_each(saved); + left + } + /// The problems since the last call, oldest first. pub fn take_notices() -> Vec { std::mem::take(&mut *notices()) @@ -147,7 +156,30 @@ mod prefs { rustgis_assistant::chatgpt::set_secret_store(Some(secrets.clone())); Services { load_pref: Some(Box::new(|key: &str| read().get(key).and_then(Value::as_str).map(str::to_string))), - save_pref: Some(Box::new(|key: &str, value: &str| saved(rustgis_engine::prefs::write(key, value)))), + // While another copy of RustGIS saves its preferences, a value is kept to save and + // `retry_prefs` writes it on a later frame (and `on_exit` at the end). + save_pref: Some(Box::new(|key: &str, value: &str| match rustgis_engine::prefs::write(key, value) { + Ok(rustgis_engine::prefs::Updated::Saved(set_aside)) => saved(Ok(set_aside)), + Ok(_) => {} + Err(error) => saved(Err(error)), + })), + retry_prefs: Some(Box::new(|| retry_saves(std::time::Duration::ZERO))), + update_pref: Some(Box::new(|key: &str, value: &mut dyn FnMut(Option<&str>) -> Option| { + use rustgis_engine::prefs::Updated; + use rustgis_ui_egui::PrefUpdate; + match rustgis_engine::prefs::update(key, value) { + Ok(Updated::Saved(set_aside)) => { + saved(Ok(set_aside)); + PrefUpdate::Saved + } + Ok(Updated::Unchanged) => PrefUpdate::Unchanged, + Ok(Updated::Busy) => PrefUpdate::Busy, + Err(error) => { + saved(Err(error)); + PrefUpdate::Failed + } + } + })), secrets: Some(secrets), ..Services::default() } @@ -465,6 +497,12 @@ impl eframe::App for App { fn on_exit(&mut self) { self.0.end_exports(); self.0.end_autosave(); + // Settings left to save while another copy of RustGIS saved its own: tried once more, + // waiting a little for it (closing isn't the path that must answer at once). + self.0.save_sources_at_exit(); + if prefs::retry_saves(std::time::Duration::from_millis(1500)) { + log::warn!("some settings couldn't be saved: another copy of RustGIS kept its preferences busy"); + } // Session plugins' programs end with the app, with what they started. rustgis_engine::plugins::session::stop_all(); // The installer starts before the marker goes, so a RustGIS started meanwhile finds this diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index caf0f8b1a2..8a3d72daf6 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -932,6 +932,49 @@ pub fn write_atomic_with>( atomic_write_at(&path, write) } +/// Opens (creating it, empty) an app-managed file used only to lock on: never through a symbolic +/// link (on Unix the open itself refuses one, so none can be swapped in between a check and the +/// open), only a regular file, readable and writable by its owner alone. Elsewhere a link or +/// other non-regular file at `path` is refused before and after the open. +pub fn open_lock_file(path: &Path) -> std::io::Result { + let refused = || std::io::Error::other(format!("{} isn't a regular file", path.display())); + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32); + } + #[cfg(not(all(unix, not(target_arch = "wasm32"))))] + if std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { + return Err(refused()); + } + let file = options.open(path).map_err(|e| if e.raw_os_error() == Some(rustix_eloop()) { refused() } else { e })?; + if !file.metadata()?.is_file() || std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { + return Err(refused()); + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + use std::os::unix::fs::PermissionsExt; + if file.metadata()?.permissions().mode() & 0o777 != 0o600 { + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + } + Ok(file) +} + +/// The error a no-follow open gives for a symbolic link. +fn rustix_eloop() -> i32 { + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + rustix::io::Errno::LOOP.raw_os_error() + } + #[cfg(not(all(unix, not(target_arch = "wasm32"))))] + { + -1 + } +} + /// Atomically replaces an app-managed file, replacing a final symbolic link rather than /// writing through it. Parent directories must be trusted, as for [`write_atomic`]. Existing /// regular files keep their permissions; a replaced link uses a new file's permissions. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 9816eefd77..daa324bd8a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -49,19 +49,182 @@ fn parse_preferences(bytes: &[u8]) -> Result, String> { /// overwritten. The new file is written under a name of its own beside the old one, synced to /// disk, then renamed over it, so a crash or power cut leaves the old file or the new one, never /// a partly written one, and two copies of RustGIS saving at once never share a temporary file. -pub fn write(key: &str, value: &str) -> Result, String> { +/// +/// It reads, changes and writes the file under the lock [`update`] takes, so it never puts back +/// what another copy of RustGIS wrote meanwhile. While another copy holds that lock it writes +/// nothing and returns [`Updated::Busy`]: the value is kept to save, the latest of each key, and +/// [`retry_pending`] writes it later (a later write of the key replaces it). +pub fn write(key: &str, value: &str) -> Result { + let dir = rustgis_data::dirs::config_dir().ok_or("the settings folder isn't available")?; + write_in(&dir.join(FILE), key, value) +} + +/// [`write`] of the file at `path` (a test folder in tests). +fn write_in(path: &Path, key: &str, value: &str) -> Result { + let done = { + let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + update_file(path, key, |_| Some(value.to_string())) + }; + let mut pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let id = (path.to_path_buf(), key.to_string()); + match done { + Ok(Updated::Busy) => { + pending.insert(id, value.to_string()); + } + _ => { + pending.remove(&id); + } + } + done +} + +/// Values [`write`] couldn't save while another copy held the lock, by file and key: the latest +/// of each. +static PENDING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + +/// Writes again what [`write`] left to save. `wait` bounds how long it waits for another copy +/// to let go of the lock: zero on the UI thread (it never waits there), a second or two at exit. +/// Returns what each write tried came to (to report), and whether any is still left. +pub fn retry_pending(wait: std::time::Duration) -> (Vec, String>>, bool) { + retry_pending_in(None, wait) +} + +/// [`retry_pending`], of the file at `only` alone when given (a test folder in tests). +fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec, String>>, bool) { + let todo = || -> Vec<((PathBuf, String), String)> { + let pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + pending.iter().filter(|((path, _), _)| only.is_none_or(|o| o == path)).map(|(k, v)| (k.clone(), v.clone())).collect() + }; + let mut said = Vec::new(); + // The browser keeps no preferences file: nothing is ever left to write there. + #[cfg(not(target_arch = "wasm32"))] + let start = std::time::Instant::now(); + loop { + let mut busy = false; + for ((path, key), value) in todo() { + let done = { + let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + update_file(&path, &key, |_| Some(value.clone())) + }; + if done == Ok(Updated::Busy) { + busy = true; + break; + } + let mut pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + // A newer value written meanwhile stays to save. + if pending.get(&(path.clone(), key.clone())) == Some(&value) { + pending.remove(&(path, key)); + } + said.push(done.map(|d| match d { + Updated::Saved(set_aside) => set_aside, + Updated::Unchanged | Updated::Busy => None, + })); + } + #[cfg(not(target_arch = "wasm32"))] + if busy && start.elapsed() < wait { + std::thread::sleep(std::time::Duration::from_millis(50)); + continue; + } + #[cfg(target_arch = "wasm32")] + let _ = wait; + return (said, busy || !todo().is_empty()); + } +} + +/// What [`update`] came to. +#[derive(Debug, PartialEq)] +pub enum Updated { + /// Saved; where a malformed file was set aside, if one was. + Saved(Option), + /// The value given back none: nothing was written. + Unchanged, + /// Another copy of RustGIS is saving its preferences: nothing was read or written. Try again + /// later; this never waits for it. + Busy, +} + +/// Updates one desktop preference from its stored value: `value` is given what is stored now +/// (none when nothing is, or the file is malformed) and returns what to save, or none to leave +/// it. Another copy of RustGIS saving meanwhile can't read or write the preferences until this +/// one is written, so a value merged with what is stored keeps that copy's changes; while one +/// is saving, this returns [`Updated::Busy`] at once. Otherwise as [`write`]. +pub fn update(key: &str, value: impl FnOnce(Option<&str>) -> Option) -> Result { let dir = rustgis_data::dirs::config_dir().ok_or("the settings folder isn't available")?; let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - write_at(&dir.join(FILE), key, value) + update_file(&dir.join(FILE), key, value) +} + +/// [`update`] of the file at `path` (a test folder in tests), with its lock. +fn update_file(path: &Path, key: &str, value: impl FnOnce(Option<&str>) -> Option) -> Result { + let _held = match lock(path)? { + Locked::Busy => return Ok(Updated::Busy), + Locked::Held(held) => Some(held), + Locked::Unlockable => None, + }; + write_with(path, key, value, std::fs::read(path), sync_directory) } /// [`write`] to the file at `path` (a test folder in tests): returns where a malformed file went. +#[cfg(test)] fn write_at(path: &Path, key: &str, value: &str) -> Result, String> { write_at_with_sync(path, key, value, sync_directory) } +/// A lock on the preferences shared by every copy of RustGIS on this computer: held while one +/// reads, changes and writes them, released when dropped (or when the process ends). It is an +/// empty file beside them, never removed, so two copies always lock the same one. +#[cfg(not(target_arch = "wasm32"))] +struct Lock(std::fs::File); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Lock { + fn drop(&mut self) { + let _ = self.0.unlock(); + } +} + +/// The browser keeps no preferences file (and has one copy of RustGIS a page): nothing to lock. +#[cfg(target_arch = "wasm32")] +struct Lock; + +/// What trying the preferences lock came to. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +enum Locked { + Held(Lock), + /// Another copy of RustGIS holds it. + Busy, + /// This folder can't be locked at all (some network folders): saved without it, as before. + Unlockable, +} + +/// Tries the lock once, never waiting: [`Locked::Busy`] while another copy holds it. +#[cfg(not(target_arch = "wasm32"))] +fn lock(path: &Path) -> Result { + let lock_path = path.with_extension("json.lock"); + let dir = path.parent().ok_or("the settings folder isn't available")?; + // Never through a link (the open itself refuses one on Unix), only a regular file, its + // owner's alone. + let file = std::fs::create_dir_all(dir) + .and_then(|_| rustgis_data::io::open_lock_file(&lock_path)) + .map_err(|error| format!("could not save preferences: couldn't open {}: {error}", lock_path.display()))?; + match file.try_lock() { + Ok(()) => Ok(Locked::Held(Lock(file))), + Err(std::fs::TryLockError::WouldBlock) => Ok(Locked::Busy), + Err(std::fs::TryLockError::Error(error)) => { + log::warn!("preferences saved without a lock: couldn't lock {}: {error}", lock_path.display()); + Ok(Locked::Unlockable) + } + } +} + +#[cfg(target_arch = "wasm32")] +fn lock(_: &Path) -> Result { + Ok(Locked::Held(Lock)) +} + /// Separates replacement from its final directory flush; an unconfirmed flush must not claim /// that the already-visible file was left unchanged. The callback permits a post-rename fault test. +#[cfg(test)] fn write_at_with_sync( path: &Path, key: &str, @@ -73,6 +236,7 @@ fn write_at_with_sync( /// Uses one read result for a save. Only successfully read, malformed bytes permit recovery; /// a transient read failure cannot replace a valid file with a new one containing a single key. +#[cfg(test)] fn write_at_with_bytes( path: &Path, key: &str, @@ -80,15 +244,35 @@ fn write_at_with_bytes( bytes: std::io::Result>, sync: impl FnOnce(&Path) -> std::io::Result<()>, ) -> Result, String> { - let (mut map, set_aside) = match bytes { + match write_with(path, key, |_| Some(value.to_string()), bytes, sync)? { + Updated::Saved(set_aside) => Ok(set_aside), + Updated::Unchanged | Updated::Busy => Ok(None), + } +} + +/// [`write_at_with_bytes`] with the value made from the one stored under `key` in `bytes` (none +/// to leave it as it is). +fn write_with( + path: &Path, + key: &str, + value: impl FnOnce(Option<&str>) -> Option, + bytes: std::io::Result>, + sync: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + let (mut map, malformed) = match bytes { Ok(bytes) => match parse_preferences(&bytes) { Ok(map) => (map, None), - Err(_) => (Map::new(), Some(set_aside(path, &bytes)?)), + Err(_) => (Map::new(), Some(bytes)), }, Err(error) if error.kind() == std::io::ErrorKind::NotFound => (Map::new(), None), Err(error) => return Err(format!("could not read preferences: {error}")), }; - map.insert(key.to_string(), Value::String(value.to_string())); + let Some(value) = value(map.get(key).and_then(Value::as_str)) else { return Ok(Updated::Unchanged) }; + let set_aside = match malformed { + Some(bytes) => Some(set_aside(path, &bytes)?), + None => None, + }; + map.insert(key.to_string(), Value::String(value)); let text = serde_json::to_vec(&map).map_err(|_| "could not serialize preferences")?; let dir = path.parent().ok_or("the settings folder isn't available")?; std::fs::create_dir_all(dir).and_then(|_| rustgis_data::io::replace_atomic(path, &text)).map_err(|error| match &set_aside { @@ -102,7 +286,7 @@ fn write_at_with_bytes( ), None => format!("preferences were replaced, but their durability could not be confirmed: {error}"), })?; - Ok(set_aside) + Ok(Updated::Saved(set_aside)) } /// How many malformed preference files are kept: `prefs.json.bad`, then `prefs.json.bad2` to @@ -250,6 +434,152 @@ pub fn use_saved_secrets(s: &mut crate::Session, prefs: &Map, sto mod tests { use super::*; + /// Two copies of RustGIS read the same saved data sources and save their own changes: each + /// keeps the other's, and a source one forgot stays forgotten. + #[test] + fn two_copies_keep_each_others_data_sources() { + use crate::sources::{Source, Sources}; + let dir = std::env::temp_dir().join(format!("rustgis-preferences-two-copies-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + let file = |address: &str| Source { kind: "file".into(), address: address.into(), ..Source::default() }; + let mut first = Sources::default(); + first.keep("favourites", file("/old.csv")).unwrap(); + first.keep("favourites", file("/gone.csv")).unwrap(); + write_at(&path, "data_sources", &first.to_json()).unwrap(); + // As the desktop saves: read again, this copy's changes laid over what is stored, written. + let save = |s: &mut Sources| { + let mut next = None; + let done = update_file(&path, "data_sources", |stored| { + let mut n = s.clone(); + n.rebase(stored, None).ok()?; + let text = n.to_json(); + next = Some(n); + Some(text) + }) + .unwrap(); + assert!(matches!(done, Updated::Saved(_)), "{done:?}"); + *s = next.unwrap(); + }; + let stored = || Sources::from_json(read_at(&path).unwrap().get("data_sources").and_then(Value::as_str).unwrap()); + let favorites = |s: &Sources| s.favourites.iter().map(|f| f.address.clone()).collect::>(); + let (mut a, mut b) = (stored(), stored()); + a.keep("favourites", file("/a.csv")).unwrap(); + save(&mut a); + b.keep("favourites", file("/b.csv")).unwrap(); + save(&mut b); + assert_eq!(favorites(&stored()), ["/old.csv", "/gone.csv", "/a.csv", "/b.csv"]); + // The copy that saved last lists the other's too. + assert_eq!(favorites(&b), favorites(&stored())); + // One forgets a source and saves after the other did: it stays forgotten. + assert!(a.forget("favourites", "file", "/gone.csv").unwrap()); + b.note(file("/b-recent.csv")); + save(&mut b); + save(&mut a); + assert_eq!(favorites(&stored()), ["/old.csv", "/a.csv", "/b.csv"]); + assert_eq!(stored().recent.iter().map(|r| r.address.as_str()).collect::>(), ["/b-recent.csv"]); + // The other, saving again with what it read before, doesn't bring it back. + b.keep("saved", file("/b-saved.csv")).unwrap(); + save(&mut b); + assert_eq!(favorites(&stored()), ["/old.csv", "/a.csv", "/b.csv"]); + assert_eq!(stored().saved.len(), 1); + // Forgotten and kept again here, a source is listed again. + assert!(a.forget("favourites", "file", "/a.csv").unwrap()); + a.keep("favourites", file("/a.csv")).unwrap(); + save(&mut a); + assert!(favorites(&stored()).contains(&"/a.csv".to_string())); + // With nothing stored (the preferences removed, or reset), a save writes this copy's whole + // list, not just what it changed since. + for gone in [None, Some("")] { + match gone { + None => std::fs::remove_file(&path).unwrap(), + Some(empty) => write_at(&path, "data_sources", empty).map(drop).unwrap(), + } + let all = favorites(&a); + a.keep("favourites", file("/after.csv")).unwrap(); + save(&mut a); + assert_eq!(favorites(&stored()), [all, vec!["/after.csv".to_string()]].concat()); + assert!(a.forget("favourites", "file", "/after.csv").unwrap()); + save(&mut a); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Every preference write goes through the lock: while another copy holds it, a write is + /// kept (the latest of its key), writes nothing, and is written later over what that copy + /// saved meanwhile, never putting its old value back; at exit the retry waits a little. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_write_while_another_copy_saves_is_kept_and_written_later() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-pending-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + write_at(&path, "data_sources", "old").unwrap(); + let held = lock(&path).unwrap(); + assert_eq!(write_in(&path, "theme", "light").unwrap(), Updated::Busy); + assert_eq!(write_in(&path, "theme", "dark").unwrap(), Updated::Busy); + assert!(read_at(&path).unwrap().get("theme").is_none(), "nothing written while it is held"); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(said.is_empty() && left); + // The other copy saves its own while it holds the lock. + write_at(&path, "data_sources", "theirs").unwrap(); + drop(held); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert_eq!((said.len(), left), (1, false), "{said:?}"); + let map = read_at(&path).unwrap(); + assert_eq!(map.get("theme").and_then(Value::as_str), Some("dark"), "the latest value"); + assert_eq!(map.get("data_sources").and_then(Value::as_str), Some("theirs"), "the other copy's save stays"); + // At exit the retry waits (a little) for the other copy to let go. + let held = lock(&path).unwrap(); + assert_eq!(write_in(&path, "theme", "exit").unwrap(), Updated::Busy); + let other = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(200)); // test-wait: another copy holding the lock briefly + drop(held); + }); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::from_millis(1500)); + other.join().unwrap(); + assert_eq!((said.len(), left), (1, false), "{said:?}"); + assert_eq!(read_at(&path).unwrap().get("theme").and_then(Value::as_str), Some("exit")); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// The preferences lock is shared by every copy of RustGIS: while one holds it, another's + /// update returns at once, reading and writing nothing, and saves once it is let go. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_held_preferences_lock_never_waits() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-lock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + let held = lock(&path).unwrap(); + assert!(matches!(held, Locked::Held(_))); + assert!(matches!(lock(&path).unwrap(), Locked::Busy)); + let started = std::time::Instant::now(); + let busy = update_file(&path, "k", |_| panic!("nothing is read while another copy saves")).unwrap(); + assert_eq!(busy, Updated::Busy); + assert!(started.elapsed() < std::time::Duration::from_millis(500)); + assert!(!path.exists()); + drop(held); + assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); + assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); + // A value given back as none leaves the preference as it was. + assert_eq!(update_file(&path, "k", |_| None).unwrap(), Updated::Unchanged); + assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); + // A link in the lock's place is refused, never followed. + #[cfg(unix)] + { + let lock_path = path.with_extension("json.lock"); + std::fs::remove_file(&lock_path).unwrap(); + std::os::unix::fs::symlink(dir.join("elsewhere"), &lock_path).unwrap(); + assert!(lock(&path).is_err()); + assert!(!dir.join("elsewhere").exists()); + } + std::fs::remove_dir_all(dir).unwrap(); + } + /// Recovery preserves the malformed snapshot, even if the path now contains another save. #[test] fn recovery_keeps_the_bytes_that_failed_parsing() { diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index ab8688e623..338558615b 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -48,6 +48,13 @@ pub struct Sources { /// What of the preference this version couldn't use, written back as it was. #[serde(skip)] kept: Kept, + /// What this session changed since the sources were last stored, by list, kind and address: + /// the sources it kept or noted, and the ones it forgot. [`Sources::rebase`] lays these over + /// the stored sources, so another window's changes stay. + #[serde(skip)] + touched: BTreeSet<(&'static str, String, String)>, + #[serde(skip)] + removed: BTreeSet<(&'static str, String, String)>, } /// The three lists, as the preference names them. @@ -68,14 +75,19 @@ struct Kept { over: usize, /// Fields of read sources this version doesn't know, by list, kind and address. fields: BTreeMap<(&'static str, String, String), Map>, + /// Details (`extra`) of read sources that [`clean`] leaves out but a newer RustGIS may have + /// written (a number, a list, more than eight entries…), by list, kind and address: the + /// entries left out, or the whole value when it isn't an object. Only for rows without a + /// password, key or token; written back beside the details this version uses. + extra: BTreeMap<(&'static str, String, String), Value>, /// Keys beside the three lists this version doesn't know. top: Map, /// Rows and fields that couldn't be read and held a password, key or token: not kept, since /// this version can't strip it from what it doesn't understand. secrets: usize, /// Readable sources whose name, address or details [`clean`] changed (a name too long or with - /// control characters, an address with a password, key or token, details that aren't short - /// text, more than eight, or secret-looking): saved that way. + /// control characters, an address with a password, key or token, or details of a row holding + /// one): saved that way. The details of other rows are kept in `extra` instead. cut: usize, /// Readable rows that repeat the identity of an earlier row of their list: dropped (the first /// one wins, with its unknown fields). @@ -136,6 +148,21 @@ fn cut(before: &Source, after: &Source) -> bool { (!name.is_empty() && after.name != name) || after.address != before.address.trim() || extra } +/// What [`clean`] left out of a source's details `before` (now `after`): the entries it dropped, or +/// the whole value when it isn't an object (none when nothing was left out). +fn left_out(before: &Value, after: &Value) -> Option { + match before { + Value::Null => None, + Value::Object(o) => { + let used = after.as_object(); + let out: Map = + o.iter().filter(|(k, _)| !used.is_some_and(|u| u.contains_key(*k))).map(|(k, v)| (k.clone(), v.clone())).collect(); + (!out.is_empty()).then_some(Value::Object(out)) + } + other => Some(other.clone()), + } +} + /// A saved row: the source, and the fields this version doesn't know. #[derive(Deserialize)] struct Row { @@ -186,21 +213,33 @@ impl Sources { // Entry by entry: one that doesn't read is kept as it was, not the whole list. let read = serde_json::from_value::(row.clone()).ok().and_then(|r| { let mut cleaned = clean(r.source.clone()).ok()?; - let was_cut = cut(&r.source, &cleaned); + // Details this version doesn't use, from a row without a secret, are kept as + // they were: a newer RustGIS may have written them. A row holding a secret + // can't be kept as it was, so its details are saved cleaned (and said). + let newer = if holds_secret(&row) { None } else { left_out(&r.source.extra, &cleaned.extra) }; + let before = match newer { + Some(_) => Source { extra: cleaned.extra.clone(), ..r.source.clone() }, + None => r.source.clone(), + }; + let was_cut = cut(&before, &cleaned); // A login binding is the app's own output, never authority from an earlier // process's login: it isn't kept, and clearing it is no loss. crate::s3_connections::clear_bindings(std::iter::once(&mut cleaned.address)); - Some((was_cut, cleaned, r.other)) + Some((was_cut, cleaned, r.other, newer)) }); match read { // The first row of an identity wins; a repeat is dropped, and said. - Some((_, source, _)) if seen.contains(&identity(&source.kind, &source.address)) => s.kept.repeated += 1, - Some((was_cut, source, other)) if into.len() < cap => { + Some((_, source, _, _)) if seen.contains(&identity(&source.kind, &source.address)) => s.kept.repeated += 1, + Some((was_cut, source, other, newer)) if into.len() < cap => { seen.insert(identity(&source.kind, &source.address)); s.kept.cut += usize::from(was_cut); let other = s.kept.without_secrets(other, &source.address, &source.extra); + let key = (list, source.kind.clone(), source.address.clone()); if !other.is_empty() { - s.kept.fields.insert((list, source.kind.clone(), source.address.clone()), other); + s.kept.fields.insert(key.clone(), other); + } + if let Some(newer) = newer { + s.kept.extra.insert(key, newer); } into.push(source); } @@ -221,52 +260,67 @@ impl Sources { /// What of the preference read by [`Sources::from_json`] isn't used here, one line per kind /// (none when all of it is). pub fn unread(&self) -> Vec { + self.unread_by_kind().into_iter().map(|(_, _, said)| said).collect() + } + + /// [`Sources::unread`], each line with its kind (`"whole"`, `"repeated"`, `"over"`, `"rows"`, + /// `"newer"`, `"cut"` or `"secrets"`) and how many it is about, so a caller says each kind once, + /// and again only when it is about more. + pub fn unread_by_kind(&self) -> Vec<(&'static str, usize, String)> { let k = &self.kept; if let Some((_, why)) = &k.whole { - return vec![format!( - "The saved data sources couldn't be read ({why}): none is listed, and the favourites, recent and saved sources of this session aren't kept over them; fix or remove \"data_sources\" in the preferences file to keep them" + return vec![( + "whole", + 1, + format!( + "The saved data sources couldn't be read ({why}): none is listed, and the favourites, recent and saved sources of this session aren't kept over them; fix or remove \"data_sources\" in the preferences file to keep them" + ), )]; } let mut said = Vec::new(); let rows = k.rows.values().map(Vec::len).sum::().saturating_sub(k.over); if k.repeated > 0 { let n = k.repeated; - said.push(format!( - "{n} repeated saved data source{} removed (the first of each is kept, with its settings)", - if n == 1 { " was" } else { "s were" } + said.push(( + "repeated", + n, + format!( + "{n} repeated saved data source{} removed (the first of each is kept, with its settings)", + if n == 1 { " was" } else { "s were" } + ), )); } if k.over > 0 { let n = k.over; - said.push(format!( + said.push(("over", n, format!( "{n} saved data source{} past the lists' limits ({MAX_KEPT} favourites or saved, {MAX_RECENT} recent): not listed, and kept as {} when the sources are saved", if n == 1 { " is" } else { "s are" }, if n == 1 { "it was" } else { "they were" } - )); + ))); } if rows > 0 { - said.push(format!( + said.push(("rows", rows, format!( "{rows} saved data source{} couldn't be read (from a newer RustGIS, or damaged): not listed, and kept as {} when the sources are saved", if rows == 1 { "" } else { "s" }, if rows == 1 { "it was" } else { "they were" } - )); + ))); } - if !k.fields.is_empty() { - let n = k.fields.len(); - said.push(format!( + if !k.fields.is_empty() || !k.extra.is_empty() { + let n = k.fields.keys().chain(k.extra.keys()).collect::>().len(); + said.push(("newer", n, format!( "{n} saved data source{} settings this version doesn't know (from a newer RustGIS): ignored here, and kept when the sources are saved", if n == 1 { " has" } else { "s have" } - )); + ))); } if k.cut > 0 { let n = k.cut; - said.push(format!( - "{n} saved data source{} a name, address or details this version changes (a name too long or with control characters, an address with a password, key or token, details that aren't short text, more than eight, or secret-looking): saved changed", + said.push(("cut", n, format!( + "{n} saved data source{} a name, address or details this version changes (a name too long or with control characters, an address with a password, key or token, or details of a source holding one): saved changed", if n == 1 { " has" } else { "s have" } - )); + ))); } if k.secrets > 0 { - said.push(secrets_notice(k.secrets)); + said.push(("secrets", k.secrets, secrets_notice(k.secrets))); } said } @@ -297,7 +351,9 @@ impl Sources { now.push(source); } else { over.push((list, stored.row(list, &source))); - stored.kept.fields.remove(&(list, source.kind.clone(), source.address.clone())); + let key = key_of(list, &source); + stored.kept.fields.remove(&key); + stored.kept.extra.remove(&key); } } } @@ -309,14 +365,7 @@ impl Sources { // A readable row kept past a limit for a source that is listed gives it its fields. for list in LISTS { if self.kept.rows.contains_key(list) { - let ids: Vec<_> = match list { - "favourites" => &self.favourites, - "saved" => &self.saved, - _ => &self.recent, - } - .iter() - .map(|s| identity(&s.kind, &s.address)) - .collect(); + let ids: Vec<_> = self.list(list).iter().map(|s| identity(&s.kind, &s.address)).collect(); for id in ids { self.adopt(list, &id); } @@ -326,6 +375,105 @@ impl Sources { self.generation += 1; } + /// Lays this session's changes over the sources kept with the preferences as they are now, + /// which another window may have changed since they were read: the sources this session kept + /// or noted since then are taken as it has them, the ones it forgot stay forgotten, and every + /// other source is as stored (another window's additions stay, its removals too). A recent + /// source this session noted comes first. + /// + /// `stored` is the preference as it is now, `last_written` what this session last wrote of + /// it. When nothing is stored (the preferences removed or reset), or what is stored is what + /// this session wrote, there is nothing to lay the changes over: this session's sources are + /// kept whole. Stored sources that can't be read at all are never written over (as + /// [`Sources::merge`] does): an error says why, `self` is unchanged and its changes wait. + pub fn rebase(&mut self, stored: Option<&str>, last_written: Option<&str>) -> Result<(), String> { + let stored = stored.filter(|s| !s.trim_start_matches('\u{feff}').trim().is_empty()); + let Some(stored) = stored.filter(|s| Some(*s) != last_written) else { + // This session's lists are what is stored now; what it read but can't use is kept. + self.kept.whole = None; + self.touched.clear(); + self.removed.clear(); + self.generation += 1; + return Ok(()); + }; + let mut next = Sources::from_json(stored); + if next.kept.whole.is_some() { + return Err(next.unread().into_iter().next().unwrap_or_default()); + } + for (list, kind, address) in &self.removed { + let _ = next.forget(list, kind, address); + } + // A source this session changed is written with what this session keeps for it, exactly: + // its fields and details from a newer RustGIS, or none (replaced with other details, its + // old ones went), never the stored row's again. + let exact = |next: &mut Sources, key: &(&'static str, String, String)| { + match self.kept.fields.get(key) { + Some(fields) => next.kept.fields.insert(key.clone(), fields.clone()), + None => next.kept.fields.remove(key), + }; + match self.kept.extra.get(key) { + Some(newer) => next.kept.extra.insert(key.clone(), newer.clone()), + None => next.kept.extra.remove(key), + }; + }; + for list in LISTS { + let cap = if list == "recent" { MAX_RECENT } else { MAX_KEPT }; + let ours: Vec = self.list(list).iter().filter(|s| self.touched.contains(&key_of(list, s))).cloned().collect(); + for source in &ours { + exact(&mut next, &key_of(list, source)); + } + if list == "recent" { + next.recent.retain(|r| !ours.iter().any(|o| same(o, r))); + let older = std::mem::replace(&mut next.recent, ours.clone()); + next.recent.extend(older); + next.recent.truncate(MAX_RECENT); + let recent = &next.recent; + next.kept.fields.retain(|(l, k, a), _| still_listed(recent, l, k, a)); + next.kept.extra.retain(|(l, k, a), _| still_listed(recent, l, k, a)); + } else { + let mut over = Vec::new(); + let Ok(now) = next.list_mut(list) else { continue }; + for source in ours.iter().cloned() { + if let Some(slot) = now.iter_mut().find(|r| same(r, &source)) { + *slot = source; + } else if now.len() < cap { + now.push(source); + } else { + over.push(source); + } + } + // Past the limit (another window filled the list): kept as rows, and said. + for source in over { + let row = next.row(list, &source); + let key = key_of(list, &source); + next.kept.fields.remove(&key); + next.kept.extra.remove(&key); + next.kept.rows.entry(list).or_default().push(row); + next.kept.over += 1; + } + } + let ids: Vec<_> = next.list(list).iter().map(|s| identity(&s.kind, &s.address)).collect(); + for id in ids { + next.adopt(list, &id); + } + // Adopting a stored row past the limit mustn't bring its details back either. + for source in &ours { + let key = key_of(list, source); + if next.list(list).iter().any(|s| same(s, source)) { + exact(&mut next, &key); + } + } + } + next.kept.fields.retain(|_, f| !f.is_empty()); + next.recheck_fields(); + // Stored as they are now: nothing is this session's own change any more. + next.touched.clear(); + next.removed.clear(); + next.generation = self.generation + 1; + *self = next; + Ok(()) + } + /// Classifies the fields kept for each listed source again, against the source as it is now /// (a changed `extra` or address can make a field that passed at load a secret), and drops /// what is one, counted with the rest. Every change to a list that keeps fields ends here, so @@ -334,13 +482,8 @@ impl Sources { let keys: Vec<_> = self.kept.fields.keys().cloned().collect(); for key in keys { let (list, kind, address) = &key; - let listed = match *list { - "favourites" => &self.favourites, - "saved" => &self.saved, - _ => &self.recent, - }; let id = (kind.clone(), address.clone()); - let Some(source) = listed.iter().find(|s| identity(&s.kind, &s.address) == id).cloned() else { continue }; + let Some(source) = self.list(list).iter().find(|s| identity(&s.kind, &s.address) == id).cloned() else { continue }; if let Some(fields) = self.kept.fields.remove(&key) { let fields = self.kept.without_secrets(fields, &source.address, &source.extra); if !fields.is_empty() { @@ -348,6 +491,19 @@ impl Sources { } } } + // Kept details passed with the row as it was read; beside details changed since (a web + // address next to a bare `key`), the row they make may hold a secret: then they go. + let keys: Vec<_> = self.kept.extra.keys().cloned().collect(); + for key in keys { + let (list, kind, address) = &key; + let id = (kind.clone(), address.clone()); + let Some(source) = self.list(list).iter().find(|s| identity(&s.kind, &s.address) == id) else { continue }; + if holds_secret(&self.row(list, source)) + && let Some(gone) = self.kept.extra.remove(&key) + { + self.kept.secrets += gone.as_object().map_or(1, Map::len); + } + } } /// Listing a source takes along the fields of a readable row of it kept past the list's limit @@ -358,16 +514,25 @@ impl Sources { rows.retain(|r| { let ours = row_identity(r).as_ref() == Some(id); if ours && let Ok(row) = serde_json::from_value::(r.clone()) { - taken.push(row.other); + // Its details this version doesn't use go along too, unless the row holds a secret. + let newer = match clean(row.source.clone()) { + Ok(cleaned) if !holds_secret(r) => left_out(&row.source.extra, &cleaned.extra), + _ => None, + }; + taken.push((row.other, newer)); } !ours }); self.kept.over = self.kept.over.saturating_sub(taken.len()); - for other in taken { - let fields = self.kept.fields.entry((list, id.0.clone(), id.1.clone())).or_default(); + let key = (list, id.0.clone(), id.1.clone()); + for (other, newer) in taken { + let fields = self.kept.fields.entry(key.clone()).or_default(); for (k, v) in other { fields.entry(k).or_insert(v); } + if let Some(newer) = newer { + self.kept.extra.entry(key.clone()).or_insert(newer); + } } self.kept.fields.retain(|_, f| !f.is_empty()); } @@ -387,13 +552,30 @@ impl Sources { Value::Object(o).to_string() } - /// A source as a preference row: with the fields kept for it that this version doesn't know. + /// A source as a preference row: with the fields and details kept for it that this version + /// doesn't know (what this version sets wins). fn row(&self, list: &'static str, source: &Source) -> Value { let mut row = serde_json::to_value(source).unwrap_or(Value::Null); let (kind, address) = identity(&source.kind, &source.address); - if let (Value::Object(row), Some(other)) = (&mut row, self.kept.fields.get(&(list, kind, address))) { - for (k, v) in other { - row.entry(k.clone()).or_insert_with(|| v.clone()); + let key = (list, kind, address); + if let Value::Object(row) = &mut row { + if let Some(other) = self.kept.fields.get(&key) { + for (k, v) in other { + row.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + match self.kept.extra.get(&key) { + Some(Value::Object(newer)) => { + if let Value::Object(extra) = row.entry("extra").or_insert_with(|| Value::Object(Map::new())) { + for (k, v) in newer { + extra.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + } + Some(whole) => { + row.entry("extra").or_insert_with(|| whole.clone()); + } + None => {} } } row @@ -402,16 +584,23 @@ impl Sources { /// Notes a source just added (the most recent first, each once). pub fn note(&mut self, s: Source) { let Ok(s) = clean(s) else { return }; + let changed = self.recent.iter().any(|r| same(r, &s) && *r != s); self.recent.retain(|r| !same(r, &s)); self.recent.insert(0, s); self.recent.truncate(MAX_RECENT); let id = identity(&self.recent[0].kind, &self.recent[0].address); + // Noted with other details, as in [`Sources::keep`]. + if changed { + self.kept.extra.remove(&("recent", id.0.clone(), id.1.clone())); + } self.adopt("recent", &id); // A source no longer recent takes the fields kept for it along. let recent = &self.recent; - self.kept.fields.retain(|(list, kind, address), _| { - *list != "recent" || recent.iter().any(|r| identity(&r.kind, &r.address) == identity(kind, address)) - }); + self.kept.fields.retain(|(list, kind, address), _| still_listed(recent, list, kind, address)); + self.kept.extra.retain(|(list, kind, address), _| still_listed(recent, list, kind, address)); + self.touched.retain(|(list, kind, address)| still_listed(recent, list, kind, address)); + self.removed.remove(&("recent", id.0.clone(), id.1.clone())); + self.touched.insert(("recent", id.0, id.1)); self.recheck_fields(); self.generation += 1; } @@ -423,7 +612,9 @@ impl Sources { let list = LISTS.into_iter().find(|l| *l == list).ok_or_else(|| format!("unknown list '{list}' (favourites, saved or recent)"))?; let l = self.list_mut(list)?; // The same source keeps its place. + let mut changed = false; if let Some(slot) = l.iter_mut().find(|r| same(r, &s)) { + changed = *slot != s; *slot = s.clone(); } else { if l.len() >= MAX_KEPT { @@ -431,7 +622,15 @@ impl Sources { } l.push(s.clone()); } - self.adopt(list, &identity(&s.kind, &s.address)); + let id = identity(&s.kind, &s.address); + // Replaced with other details, a source's kept details from a newer RustGIS were about + // the old ones (a WMS layer kept beside a WMTS source's): they go with them. + if changed { + self.kept.extra.remove(&(list, id.0.clone(), id.1.clone())); + } + self.adopt(list, &id); + self.removed.remove(&(list, id.0.clone(), id.1.clone())); + self.touched.insert((list, id.0, id.1)); self.recheck_fields(); self.generation += 1; // What was stored (cleaned): the caller reports it, wherever it sits in the list. @@ -448,6 +647,7 @@ impl Sources { let mut kept_gone = false; if let Some(list) = LISTS.into_iter().find(|l| *l == list) { self.kept.fields.retain(|(l, k, a), _| *l != list || identity(k, a) != id); + self.kept.extra.retain(|(l, k, a), _| *l != list || identity(k, a) != id); // A readable row kept past the list's limit with the same identity would be listed // again by the next start; a row this version can't read is not this source's. if let Some(rows) = self.kept.rows.get_mut(list) { @@ -456,6 +656,11 @@ impl Sources { self.kept.over = self.kept.over.saturating_sub(before - rows.len()); kept_gone = rows.len() != before; } + if gone || kept_gone { + let key = (list, id.0.clone(), id.1.clone()); + self.touched.remove(&key); + self.removed.insert(key); + } } if gone || kept_gone { self.generation += 1; @@ -463,6 +668,23 @@ impl Sources { Ok(gone || kept_gone) } + /// The list named `list` (the recent one for a name that isn't another's). + fn list(&self, list: &str) -> &Vec { + match list { + "favourites" => &self.favourites, + "saved" => &self.saved, + _ => &self.recent, + } + } + + /// Marks these sources as what is stored: what this session changed is written. For a + /// caller that wrote [`Sources::to_json`] over what it last wrote itself, with nothing to lay + /// its changes over ([`Sources::rebase`] does this itself). + pub fn stored(&mut self) { + self.touched.clear(); + self.removed.clear(); + } + fn list_mut(&mut self, list: &str) -> Result<&mut Vec, String> { match list { "favourites" => Ok(&mut self.favourites), @@ -481,6 +703,18 @@ fn identity(kind: &str, address: &str) -> (String, String) { (kind.to_string(), address) } +/// The key what is kept for a source in `list` goes under: the list and its identity. +fn key_of(list: &'static str, source: &Source) -> (&'static str, String, String) { + let (kind, address) = identity(&source.kind, &source.address); + (list, kind, address) +} + +/// Whether what is kept under `list`, `kind` and `address` still has its source: always, but in +/// the recent list (`recent`), which drops its oldest. +fn still_listed(recent: &[Source], list: &str, kind: &str, address: &str) -> bool { + list != "recent" || recent.iter().any(|r| identity(&r.kind, &r.address) == identity(kind, address)) +} + /// The identity of a saved row [`Sources::from_json`] reads (none for one it can't). fn row_identity(row: &Value) -> Option<(String, String)> { let source = clean(serde_json::from_value::(row.clone()).ok()?.source).ok()?; @@ -1396,14 +1630,24 @@ MIIE let signed = json!({"saved": [{"kind": "url", "name": "U", "address": "https://a/x.fgb?sig=hidden"}]}); let s = Sources::from_json(&signed.to_string()); assert!(matches!(s.unread().as_slice(), [one] if one.starts_with("1 saved data source has")), "{:?}", s.unread()); - // Details and a name this version cuts down when it reads them are said. + // A name this version cuts down when it reads it is said, and saved cut. Details it doesn't + // use are no longer cut: they may be a newer RustGIS's, which an older one never saves + // again without (AGENTS.md, "Never silent"), so they are kept as they were and said as + // kept, not as changed. let long = "n".repeat(300); let cut = json!({"saved": [ {"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "future": {"mode": 1}}}, {"kind": "file", "name": long, "address": "/a.csv"} ]}); let s = Sources::from_json(&cut.to_string()); - assert!(matches!(s.unread().as_slice(), [one] if one.starts_with("2 saved data sources have")), "{:?}", s.unread()); + assert!( + matches!(s.unread().as_slice(), [kept, cut] if kept.starts_with("1 saved data source has settings") + && cut.starts_with("1 saved data source has a name")), + "{:?}", + s.unread() + ); + assert_eq!(s.saved[0].extra, json!({"type": "wms"})); + assert!(s.to_json().contains(r#""extra":{"future":{"mode":1},"type":"wms"}"#), "{}", s.to_json()); for clean in [ "", r#"{"favourites": [], "recent": [], "saved": []}"#, @@ -1414,6 +1658,157 @@ MIIE } } + /// Details a newer RustGIS wrote that this version doesn't use (a number, a list, more than + /// eight entries, a value that isn't an object) survive reading, noting a source and saving: + /// this version uses what it can, and writes the rest back as it was. + #[test] + fn newer_details_survive_a_save() { + let nine: Map = (0..9).map(|i| (format!("k{i}"), json!(format!("v{i}")))).collect(); + let rows = json!({"saved": [ + {"kind": "tiles", "name": "T", "address": "https://h/{z}/{x}/{y}.png", "extra": {"type": "xyz", "tileSize": 512}}, + {"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"layers": ["a", "b"], "type": "wms"}}, + {"kind": "file", "name": "N", "address": "/n.csv", "extra": nine}, + {"kind": "file", "name": "W", "address": "/w.csv", "extra": [1, 2]} + ]}); + let mut s = Sources::from_json(&rows.to_string()); + // This version uses only what it can. + assert_eq!(s.saved[0].extra, json!({"type": "xyz"})); + assert_eq!(s.saved[1].extra, json!({"type": "wms"})); + assert_eq!(s.saved[2].extra.as_object().map(Map::len), Some(8)); + assert_eq!(s.saved[3].extra, Value::Null); + // Nothing is lost, so nothing is said to be changed: only that settings are kept. + assert!( + matches!(s.unread().as_slice(), [one] if one.starts_with("4 saved data sources have settings") && one.contains("kept")), + "{:?}", + s.unread() + ); + s.note(Source { kind: "file".into(), address: "/new.csv".into(), ..Source::default() }); + let saved: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(saved["saved"], rows["saved"], "{saved}"); + // Read again by this version: the same, and saved the same again. + let again = Sources::from_json(&s.to_json()); + assert_eq!(serde_json::from_str::(&again.to_json()).unwrap()["saved"], rows["saved"]); + // Kept again unchanged, a source keeps the details kept for it. + let same = s.saved[1].clone(); + s.keep("saved", same).unwrap(); + assert!(s.to_json().contains(r#""layers":["a","b"]"#), "{}", s.to_json()); + // Replaced with other details, its kept ones were about the old: they go (a WMTS source + // saved over a WMS one doesn't keep the WMS layers). + s.keep( + "saved", + Source { kind: "service".into(), name: "S".into(), address: "https://h/wms".into(), extra: json!({"type": "wmts"}) }, + ) + .unwrap(); + let saved: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(saved["saved"][1]["extra"], json!({"type": "wmts"})); + s.keep("saved", Source { kind: "file".into(), name: "N".into(), address: "/n.csv".into(), extra: json!({"k8": "mine"}) }).unwrap(); + let saved: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(saved["saved"][2]["extra"], json!({"k8": "mine"})); + // Noted again with other details, a recent source drops them too. + let mut r = Sources::from_json( + &json!({"recent": [{"kind": "tiles", "name": "T", "address": "https://h/t", "extra": {"type": "xyz", "tileSize": 512}}]}) + .to_string(), + ); + r.note(Source { kind: "tiles".into(), name: "T".into(), address: "https://h/t".into(), extra: json!({"type": "xyz"}) }); + assert!(r.to_json().contains("tileSize"), "unchanged details keep it: {}", r.to_json()); + r.note(Source { kind: "tiles".into(), name: "T".into(), address: "https://h/t".into(), extra: json!({"type": "tms"}) }); + assert!(!r.to_json().contains("tileSize"), "{}", r.to_json()); + // Forgotten, a source's kept details go with it. + assert!(s.forget("saved", "tiles", "https://h/{z}/{x}/{y}.png").unwrap()); + assert!(!s.to_json().contains("tileSize")); + + // A normal row is written back unchanged, with no notice. + let plain = + json!({"saved": [{"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "layer": "roads"}}]}); + let mut s = Sources::from_json(&plain.to_string()); + assert!(s.unread().is_empty(), "{:?}", s.unread()); + s.note(Source { kind: "file".into(), address: "/new.csv".into(), ..Source::default() }); + assert_eq!(serde_json::from_str::(&s.to_json()).unwrap()["saved"], plain["saved"]); + + // A row holding a secret is still cleaned and saved without it, and said. + for secret in [ + json!({"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "token": "hidden", "tileSize": 512}}), + json!({"kind": "url", "name": "U", "address": "https://h/x.fgb?sig=hidden", "extra": {"tileSize": 512}}), + ] { + let mut s = Sources::from_json(&json!({"saved": [secret]}).to_string()); + assert!(s.unread().iter().any(|t| t.contains("saved changed")), "{:?}", s.unread()); + s.note(Source { kind: "file".into(), address: "/new.csv".into(), ..Source::default() }); + let saved = s.to_json(); + assert!(!saved.contains("hidden") && !saved.contains("tileSize"), "{saved}"); + } + // Kept details that would sit beside a secret once this version changes the source go. + let mut s = Sources::from_json( + &json!({"saved": [{"kind": "file", "name": "F", "address": "/f.csv", "extra": {"key": "feature_id"}}]}).to_string(), + ); + assert!(s.to_json().contains("feature_id")); + s.keep( + "saved", + Source { kind: "file".into(), name: "F".into(), address: "/f.csv".into(), extra: json!({"endpoint": "https://api.example"}) }, + ) + .unwrap(); + assert!(!s.to_json().contains("feature_id"), "{}", s.to_json()); + } + + /// Laying this session's changes over what is stored: nothing stored (removed, reset, or set + /// aside as malformed) or only what this session last wrote keeps its whole list; a stored + /// preference that can't be read is never written over, and the changes wait. + #[test] + fn rebase_keeps_the_whole_list_when_nothing_else_is_stored() { + let file = |address: &str| Source { kind: "file".into(), address: address.into(), ..Source::default() }; + let stored = + json!({"favourites": (0..50).map(|i| json!({"kind": "file", "name": "", "address": format!("/{i}.csv")})).collect::>()}) + .to_string(); + let mut s = Sources::from_json(&stored); + s.keep("favourites", file("/new.csv")).unwrap(); + for nothing in [None, Some(""), Some("\u{feff} \n")] { + let mut next = s.clone(); + next.rebase(nothing, None).unwrap(); + assert_eq!(next.favourites.len(), 51, "{nothing:?}"); + assert_eq!(Sources::from_json(&next.to_json()).favourites.len(), 51); + } + // What this session last wrote is its own: its list is kept whole, no rebase needed. + let mut next = s.clone(); + next.rebase(Some(&stored), Some(&stored)).unwrap(); + assert_eq!(next.favourites.len(), 51); + // Another window's list is merged with. + let theirs = json!({"favourites": [{"kind": "file", "name": "", "address": "/theirs.csv"}]}).to_string(); + let mut next = s.clone(); + next.rebase(Some(&theirs), Some(&stored)).unwrap(); + let listed: Vec<_> = next.favourites.iter().map(|f| f.address.as_str()).collect(); + assert_eq!(listed, ["/theirs.csv", "/new.csv"]); + // Unreadable: an error that says so, and nothing of this session changed or written. + let mut next = s.clone(); + let error = next.rebase(Some("[\"not\", \"an object\"]"), None).unwrap_err(); + assert!(error.contains("couldn't be read"), "{error}"); + assert_eq!(next, s); + } + + /// Through the desktop's save (laid over what is stored): a source this session saved again + /// with other details is written with what this session keeps for it, never the stored row's + /// old details glued back; a source it didn't change keeps the stored row's. + #[test] + fn rebase_writes_this_sessions_details_for_what_it_changed() { + let stored = json!({"saved": [ + {"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "layers": ["a"]}, "future": 1}, + {"kind": "tiles", "name": "T", "address": "https://h/t", "extra": {"type": "xyz", "tileSize": 512}} + ]}) + .to_string(); + let mut s = Sources::from_json(&stored); + let wmts = Source { kind: "service".into(), name: "S".into(), address: "https://h/wms".into(), extra: json!({"type": "wmts"}) }; + s.keep("saved", wmts).unwrap(); + // As another window stored it since, then this one saves. + s.rebase(Some(&stored), None).unwrap(); + let written: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(written["saved"][0]["extra"], json!({"type": "wmts"}), "{written}"); + assert_eq!(written["saved"][0]["future"], json!(1), "unknown fields stay"); + assert_eq!(written["saved"][1]["extra"], json!({"type": "xyz", "tileSize": 512})); + // Saved again later, the old details don't come back from what was stored either. + let again = s.to_json(); + s.keep("saved", Source { kind: "file".into(), address: "/x.csv".into(), ..Source::default() }).unwrap(); + s.rebase(Some(&again), None).unwrap(); + assert!(!s.to_json().contains("layers"), "{}", s.to_json()); + } + #[test] fn identity_is_kind_and_address() { let mut s = Sources::default(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dc887b7919..16d72898b0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -378,6 +378,18 @@ pub fn parse_extent(text: &str) -> Option<[f64; 4]> { Some([e.min_x, e.min_y, e.max_x, e.max_y]) } +/// What a [`Services::update_pref`] came to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PrefUpdate { + Saved, + /// The function gave back none: nothing was written. + Unchanged, + /// Another copy of the app is saving its preferences: try again later. + Busy, + /// Saving failed (the hook said why). + Failed, +} + /// Platform hooks. The desktop app leaves them empty and uses native file dialogs; the web app /// supplies an asynchronous file picker (results arrive in `inbox`) and browser downloads. #[derive(Default)] @@ -399,6 +411,16 @@ pub struct Services { pub load_pref: Option Option>>, /// Saves a preference. pub save_pref: Option>, + /// Saves a preference made from the value stored now, which another copy of the app may have + /// changed since it was read (the desktop's, locked against the others meanwhile): the + /// function is given that value and returns the one to save, or none to leave it. It never + /// waits for another copy: [`PrefUpdate::Busy`] instead. `None` where one copy of the app + /// keeps its preferences (the browser): `save_pref` is used. + pub update_pref: Option) -> Option) -> PrefUpdate>>, + /// Saves again what `save_pref` left to save while another copy of the app saved its own + /// preferences (the desktop's), never waiting; whether any is still left. Tried each frame + /// while one is. `None` where nothing is ever left (the browser). + pub retry_prefs: Option bool>>, /// The system's secret store (see `docs/architecture.md` › Secrets): the desktop's keychain. /// `None` in the browser and on the command line, where secrets last for the session only. pub secrets: Option>, @@ -2668,6 +2690,13 @@ impl RustGisApp { } } + /// As the app closes (the desktop app's `on_exit`): data sources left to save are tried once + /// more, waiting up to a second and a half for another copy of the app to let go of the + /// preferences; what still can't be saved is said and logged. + pub fn save_sources_at_exit(&mut self) { + sourcespane::save_at_exit(self, std::time::Duration::from_millis(1500)); + } + /// A clean exit (the desktop app's `on_exit`): the recovery copy of this run's unsaved work /// is removed, as recovery is for a run that didn't close. Call it once, as the app closes. pub fn end_autosave(&mut self) { @@ -6402,6 +6431,14 @@ impl RustGisApp { // Sources the AI Assistant or a background add brought in (not through `run`) are kept // too: a generation compared each frame. So is a default raster style it set. sourcespane::save(self); + if let Some(retry) = sourcespane::retry_in(self) { + ctx.request_repaint_after(retry); + } + if let Some(retry) = &self.services.retry_prefs + && retry() + { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } sourcespane::save_connections(self); self.save_raster_defaults(); self.save_layout_favourite(); diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 96c7984abc..21d6469ae4 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -20,6 +20,32 @@ pub struct State { /// The sources as last shown, and their generation. shown: Option<(u64, std::sync::Arc)>, connections: Option<(u64, std::sync::Arc>)>, + /// The kinds of notice said of the stored sources, with the count each was said at: reading + /// them again at a save says a kind again only when more is affected than was said. + said: Vec<(&'static str, usize)>, + /// Whether a save refused to write over unreadable stored sources has been said since the + /// last save that happened. + refusal_said: bool, + /// What this session last wrote: a save that finds it stored has nothing to lay its changes + /// over. + last_written: Option, + /// When a save that didn't happen (the preferences busy, unreadable or failing) is tried + /// again, and how many have failed in a row. + retry_at: Option, + failures: u32, + /// Since when another copy of the app has kept the preferences busy. + busy_since: Option, +} + +/// How soon a save is tried again while another copy of the app saves its preferences. +const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(250); +/// How long another copy may keep them busy before that is said. +const BUSY_SAY: std::time::Duration = std::time::Duration::from_secs(10); + +/// How long after `failures` failed saves in a row the next is tried: one second, doubling up +/// to a minute. +fn backoff(failures: u32) -> std::time::Duration { + std::time::Duration::from_secs(1u64 << failures.saturating_sub(1).min(6)).min(std::time::Duration::from_secs(60)) } /// The sources to show this frame: the last snapshot unless they changed since. @@ -62,16 +88,38 @@ pub fn load(app: &mut RustGisApp) { let stored = rustgis_engine::sources::Sources::from_json(&text); app.session.sources.merge(stored); // After the merge: sources it moved past a list's limit are said too. - for said in app.session.sources.unread() { - app.session.warn(said); - } + say_unread(app); } if !changed { app.ui.sources_saved = app.session.sources.generation; } } -/// Keeps the sources with the preferences when they changed. +/// Says what of the stored sources isn't used here: each kind once, and again when more of it +/// is affected than was said (another window's newer sources, more rows unreadable). +fn say_unread(app: &mut RustGisApp) { + for (kind, count, said) in app.session.sources.unread_by_kind() { + say_more(app, kind, count, said); + } +} + +/// Says `said` unless its kind was said at `count` or more already. +fn say_more(app: &mut RustGisApp, kind: &'static str, count: usize, said: String) { + let known = &mut app.ui.sources.said; + match known.iter_mut().find(|(k, _)| *k == kind) { + Some((_, at)) if *at >= count => return, + Some((_, at)) => *at = count, + None => known.push((kind, count)), + } + app.session.warn(said); +} + +/// Keeps the sources with the preferences when they changed. Where another copy of the app +/// keeps them too (the desktop), what is stored is read again and this session's changes laid +/// over it ([`Sources::rebase`](rustgis_engine::sources::Sources::rebase)), so neither copy +/// writes over the other's. A save that doesn't happen (another copy saving, the stored +/// sources unreadable, the file failing) leaves the changes to save, tried again later +/// ([`retry_in`]); it never waits. pub fn save(app: &mut RustGisApp) { if !app.ui.sources.loaded { load(app); @@ -79,10 +127,132 @@ pub fn save(app: &mut RustGisApp) { if app.session.sources.generation == app.ui.sources_saved { return; } - app.ui.sources_saved = app.session.sources.generation; - if let Some(save) = &app.services.save_pref { - save(PREF, &app.session.sources.to_json()); + if app.services.update_pref.is_none() { + app.ui.sources_saved = app.session.sources.generation; + if let Some(save) = &app.services.save_pref { + save(PREF, &app.session.sources.to_json()); + } + return; + } + if app.ui.sources.retry_at.is_some_and(|at| web_time::Instant::now() < at) { + return; + } + attempt(app); +} + +/// One try at saving the data sources through `update_pref`: what it came to. +fn attempt(app: &mut RustGisApp) -> Option { + use rustgis_engine::sources::Sources; + enum Next { + /// What is stored is what this session last wrote: its lists are written as they are. + Own(String), + Rebased(Box, String), + } + let update = app.services.update_pref.as_ref()?; + let now = web_time::Instant::now(); + let (mut next, mut unreadable) = (None, None); + let (sources, last) = (&app.session.sources, app.ui.sources.last_written.as_deref()); + let outcome = update(PREF, &mut |stored| { + if stored.is_some() && stored == last { + let text = sources.to_json(); + next = Some(Next::Own(text.clone())); + return Some(text); + } + let mut rebased = sources.clone(); + match rebased.rebase(stored, last) { + Ok(()) => { + let text = rebased.to_json(); + next = Some(Next::Rebased(Box::new(rebased), text.clone())); + Some(text) + } + // Never written over: the changes wait until it can be read (or is removed). + Err(why) => { + unreadable = Some(why); + None + } + } + }); + let state = &mut app.ui.sources; + match (outcome, next) { + (crate::PrefUpdate::Saved, Some(next)) => { + (state.retry_at, state.failures, state.busy_since, state.refusal_said) = (None, 0, None, false); + state.said.retain(|(kind, _)| *kind != "busy"); + let text = match next { + Next::Own(text) => { + app.session.sources.stored(); + text + } + Next::Rebased(sources, text) => { + app.session.sources = *sources; + text + } + }; + app.ui.sources.last_written = Some(text); + app.ui.sources_saved = app.session.sources.generation; + say_unread(app); + } + (crate::PrefUpdate::Busy, _) => { + let since = *state.busy_since.get_or_insert(now); + state.retry_at = Some(now + BUSY_RETRY); + if now.duration_since(since) >= BUSY_SAY { + let said = + crate::tl!("The data sources aren't saved yet: another copy of RustGIS keeps its preferences busy. Trying again."); + say_more(app, "busy", 1, said.to_string()); + } + } + _ => { + state.busy_since = None; + state.failures = state.failures.saturating_add(1); + state.retry_at = Some(now + backoff(state.failures)); + // Said when a save refuses, though the same was said when the sources were read. + if let Some(why) = unreadable + && !state.refusal_said + { + state.refusal_said = true; + app.session.warn(why); + } + } + } + Some(outcome) +} + +/// As the app closes: data sources left to save are tried once more whatever the retry delay, +/// trying again for up to `wait` while another copy of the app keeps the preferences busy +/// (closing isn't the path that must answer at once). What still can't be saved is said and +/// logged. +pub fn save_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { + if !app.ui.sources.loaded || app.session.sources.generation == app.ui.sources_saved || app.services.update_pref.is_none() { + return; + } + let start = web_time::Instant::now(); + loop { + let outcome = attempt(app); + if app.session.sources.generation == app.ui.sources_saved { + return; + } + let busy = outcome == Some(crate::PrefUpdate::Busy); + if !busy || start.elapsed() >= wait { + let why = if busy { "another copy of RustGIS kept its preferences busy" } else { "they couldn't be written" }; + log::warn!("the data sources changed in this session weren't saved: {why}"); + app.session.warn(crate::i18n::fmt( + "The data sources changed in this session weren't saved as RustGIS closed: {why}.", + &[("why", why)], + )); + return; + } + #[cfg(not(target_arch = "wasm32"))] + std::thread::sleep(std::time::Duration::from_millis(50)); + } +} + +/// How soon a data sources save left to do is tried again, if one is: the frame that tries it +/// is asked for. +pub fn retry_in(app: &RustGisApp) -> Option { + if app.session.sources.generation == app.ui.sources_saved { + return None; } + let at = app.ui.sources.retry_at?; + Some(at.saturating_duration_since(web_time::Instant::now())) } /// Loads connections before commands can run, importing legacy saved endpoints only once. diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index ac5bcfab93..50f8c93ccb 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -1506,6 +1506,187 @@ fn saved_sources_from_a_newer_version_survive_recording_a_recent_one() { } } +/// Two windows of the desktop app keep the same data sources: each one's save reads what is +/// stored again and lays its own changes over it, so neither writes over the other's favorites, +/// and a source one removes stays removed. +type PrefStore = std::sync::Arc>>; +type PrefOutcomes = std::sync::Arc>>; + +/// A desktop window over a shared preferences store, its saves going through `update_pref` +/// as the desktop's do. `outcomes` scripts saves that don't happen (busy, failed), in turn. +fn window_over(store: &PrefStore, outcomes: &PrefOutcomes) -> RustGisApp { + use rustgis_ui_egui::PrefUpdate; + let (load, update, outcomes) = (store.clone(), store.clone(), outcomes.clone()); + let services = rustgis_ui_egui::Services { + load_pref: Some(Box::new(move |k| load.lock().unwrap().get(k).cloned())), + save_pref: Some(Box::new(|k, _| assert_ne!(k, "data_sources", "the desktop saves data sources through update_pref"))), + update_pref: Some(Box::new(move |k, value| { + if let Some(outcome) = outcomes.lock().unwrap().pop_front() { + return outcome; + } + let mut store = update.lock().unwrap(); + match value(store.get(k).map(String::as_str)) { + Some(next) => { + store.insert(k.to_string(), next); + PrefUpdate::Saved + } + None => PrefUpdate::Unchanged, + } + })), + ..Default::default() + }; + RustGisApp::with_sample().with_services(services) +} + +fn stored_favorites(store: &PrefStore) -> Vec { + let text = store.lock().unwrap()["data_sources"].clone(); + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + v["favourites"].as_array().unwrap().iter().map(|f| f["address"].as_str().unwrap().to_string()).collect() +} + +#[test] +fn two_windows_keep_each_others_data_sources() { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([( + "data_sources".to_string(), + json!({"favourites": [{"kind": "file", "name": "Old", "address": "/old.csv"}]}).to_string(), + )]))); + let outcomes = PrefOutcomes::default(); + let window = || window_over(&store, &outcomes); + let favorite = |address: &str| json!({"kind": "file", "address": address}); + let (mut a, mut b) = (window(), window()); + a.run("sources.favourite", favorite("/a.csv")).unwrap(); + b.run("sources.favourite", favorite("/b.csv")).unwrap(); + let stored = || stored_favorites(&store); + assert_eq!(stored(), ["/old.csv", "/a.csv", "/b.csv"]); + a.run("sources.remove", json!({"list": "favourites", "kind": "file", "address": "/old.csv"})).unwrap(); + b.run("sources.favourite", favorite("/b2.csv")).unwrap(); + assert_eq!(stored(), ["/a.csv", "/b.csv", "/b2.csv"]); + // The window that saved last lists the other's favorites too. + let listed: Vec<_> = b.session.sources.favourites.iter().map(|f| f.address.as_str()).collect(); + assert_eq!(listed, ["/a.csv", "/b.csv", "/b2.csv"]); + + // The stored sources removed or reset: the next save writes the window's whole list, not + // only the source it just added. + for reset in [None, Some(String::new())] { + match reset { + None => drop(store.lock().unwrap().remove("data_sources")), + Some(empty) => drop(store.lock().unwrap().insert("data_sources".into(), empty)), + } + let before: Vec<_> = b.session.sources.favourites.iter().map(|f| f.address.clone()).collect(); + b.run("sources.favourite", favorite("/after.csv")).unwrap(); + assert_eq!(stored(), [before, vec!["/after.csv".to_string()]].concat()); + b.run("sources.favourite", json!({"kind": "file", "address": "/after.csv", "on": false})).unwrap(); + } +} + +/// A save of the data sources that doesn't happen (another copy busy, the file failing, the +/// stored sources unreadable) loses nothing: the changes stay to save and are tried again +/// later, without waiting, and the window's other sources stay with them. +#[test] +fn a_data_sources_save_that_does_not_happen_is_tried_again() { + use rustgis_ui_egui::PrefUpdate; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let stored = json!({"favourites": [{"kind": "file", "name": "", "address": "/kept.csv"}]}).to_string(); + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), stored)]))); + let outcomes = PrefOutcomes::default(); + let mut app = window_over(&store, &outcomes); + let favorite = |address: &str| json!({"kind": "file", "address": address}); + for outcome in [PrefUpdate::Busy, PrefUpdate::Failed] { + outcomes.lock().unwrap().push_back(outcome); + let address = format!("/{outcome:?}.csv"); + let started = std::time::Instant::now(); + app.run("sources.favourite", favorite(&address)).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(1), "a save never waits"); + assert!(!stored_favorites(&store).contains(&address), "{outcome:?}: not saved yet"); + // Tried again once its wait is over (a quarter second busy, a second after a failure). + std::thread::sleep(std::time::Duration::from_millis(1100)); // test-wait: the retry delay the save sets + app.run("sources.list", json!({})).unwrap(); + let listed = stored_favorites(&store); + assert!(listed.contains(&address) && listed.contains(&"/kept.csv".to_string()), "{outcome:?}: {listed:?}"); + } + // Unreadable stored sources are never written over: the change waits, and is saved once + // they can be read again. + store.lock().unwrap().insert("data_sources".into(), "[\"not\", \"an object\"]".into()); + app.run("sources.favourite", favorite("/waits.csv")).unwrap(); + assert_eq!(store.lock().unwrap()["data_sources"], "[\"not\", \"an object\"]"); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.iter().filter(|t| t.contains("couldn't be read")).count(), 1, "{said:?}"); + store.lock().unwrap().remove("data_sources"); + std::thread::sleep(std::time::Duration::from_millis(1100)); // test-wait: the retry delay the save sets + app.run("sources.list", json!({})).unwrap(); + assert!(stored_favorites(&store).contains(&"/waits.csv".to_string())); +} + +/// What can't be used of the stored data sources is said once a kind while as much is affected, +/// and again when more is (another window stored more of it); a save that refuses to write over +/// unreadable stored sources says so, though the same was said when they were read. +#[test] +fn data_sources_notices_are_said_again_only_for_more() { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let newer = |n: usize| { + let rows: Vec<_> = (0..n).map(|i| json!({"kind": "file", "name": "", "address": format!("/{i}.csv"), "opened": i})).collect(); + json!({"favourites": rows}).to_string() + }; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), newer(1))]))); + let mut app = window_over(&store, &PrefOutcomes::default()); + let favorite = |address: &str| json!({"kind": "file", "address": address}); + let unknown = |app: &RustGisApp| -> Vec { + let said = app.session.notices_since(0); + said.iter().map(|n| n.text.clone()).filter(|t| t.contains("settings this version doesn't know")).collect() + }; + // Read, then saved over the same: said once. + app.run("sources.favourite", favorite("/a.csv")).unwrap(); + store.lock().unwrap().insert("data_sources".into(), newer(1)); + app.run("sources.favourite", favorite("/a2.csv")).unwrap(); + assert_eq!(unknown(&app).len(), 1, "{:?}", unknown(&app)); + // Another window stored more of it: said again, with the new count. + store.lock().unwrap().insert("data_sources".into(), newer(3)); + app.run("sources.favourite", favorite("/b.csv")).unwrap(); + let said = unknown(&app); + assert!(said.len() == 2 && said[1].starts_with("3 saved data sources"), "{said:?}"); + // The other window's list wins for what this one didn't change (it dropped /a.csv, /a2.csv). + assert_eq!(stored_favorites(&store), ["/0.csv", "/1.csv", "/2.csv", "/b.csv"]); + + // Unreadable when read and still when saved over: said both times. + let bad = "[\"not\", \"an object\"]".to_string(); + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), bad.clone())]))); + let mut app = window_over(&store, &PrefOutcomes::default()); + app.run("sources.favourite", favorite("/c.csv")).unwrap(); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.iter().filter(|t| t.contains("couldn't be read")).count(), 2, "{said:?}"); + assert_eq!(store.lock().unwrap()["data_sources"], bad); +} + +/// As the app closes, data sources left to save are tried again whatever the retry delay, +/// waiting a little while another copy keeps the preferences busy; what still can't be saved +/// is said. +#[test] +fn data_sources_left_to_save_are_saved_at_exit() { + use rustgis_ui_egui::PrefUpdate; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), json!({"favourites": []}).to_string())]))); + let outcomes = PrefOutcomes::default(); + let mut app = window_over(&store, &outcomes); + outcomes.lock().unwrap().extend([PrefUpdate::Busy, PrefUpdate::Busy]); + app.run("sources.favourite", json!({"kind": "file", "address": "/exit.csv"})).unwrap(); + assert!(stored_favorites(&store).is_empty()); + // The retry delay hasn't passed; at exit it is tried anyway, through one more busy answer. + app.save_sources_at_exit(); + assert_eq!(stored_favorites(&store), ["/exit.csv"]); + // Still busy at the end of the wait: said, not lost silently. + outcomes.lock().unwrap().extend(std::iter::repeat_n(PrefUpdate::Busy, 1000)); + app.run("sources.favourite", json!({"kind": "file", "address": "/late.csv"})).unwrap(); + app.save_sources_at_exit(); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("weren't saved as RustGIS closed")), "{said:?}"); + assert!(!stored_favorites(&store).contains(&"/late.csv".to_string())); +} + /// Saved connections from a newer RustGIS (#1405): a preference of a newer version is said, isn't /// used and stays byte for byte through other changes to the preferences, recording a recent /// source among them; rows and fields this version can't read survive a connection made here. From d228b14cb4a15160af120de6e97276536cfd6461 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:20:27 -0600 Subject: [PATCH 02/27] fix(engine): a data sources save keeps what another window stored since, and a queued setting never overwrites a newer one (#1962) Laying this window's changes over the stored data sources replaced each changed source's kept fields and details with this window's, so what a newer RustGIS stored for it since was written away. The stored row's are now kept unless this window changed that source's details itself, and a new name or place alone no longer drops the details kept for a source. A setting left to save while another copy held the lock could be written over a newer value of it: what is left to save now changes under the same lock as the write, and a setting a newer RustGIS stored as something other than text is never written over (the change waits and is said). A setting left to save is what reading it gives, the retry of the other settings backs off instead of trying each frame, and the lock files share one no-follow open. --- apps/rustgis/src/main.rs | 11 ++- crates/data/src/io.rs | 45 ++++++---- crates/data/src/publish.rs | 34 ++------ crates/data/src/source/shp/cache.rs | 12 +-- crates/engine/src/prefs.rs | 126 ++++++++++++++++++++++------ crates/engine/src/sources.rs | 124 ++++++++++++++++++++------- crates/ui-egui/src/lib.rs | 6 +- crates/ui-egui/src/sourcespane.rs | 117 ++++++++++++++++---------- 8 files changed, 310 insertions(+), 165 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 2c72fdcc07..cf51eae6c3 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -155,11 +155,15 @@ mod prefs { // The ChatGPT sign-in's tokens go to the same keychain (its accounts stay in the file). rustgis_assistant::chatgpt::set_secret_store(Some(secrets.clone())); Services { - load_pref: Some(Box::new(|key: &str| read().get(key).and_then(Value::as_str).map(str::to_string))), + // A value left to save is newer than the file's: it is what the setting is. + load_pref: Some(Box::new(|key: &str| { + rustgis_engine::prefs::pending(key).or_else(|| read().get(key).and_then(Value::as_str).map(str::to_string)) + })), // While another copy of RustGIS saves its preferences, a value is kept to save and // `retry_prefs` writes it on a later frame (and `on_exit` at the end). save_pref: Some(Box::new(|key: &str, value: &str| match rustgis_engine::prefs::write(key, value) { Ok(rustgis_engine::prefs::Updated::Saved(set_aside)) => saved(Ok(set_aside)), + Ok(rustgis_engine::prefs::Updated::Newer) => saved(Err(rustgis_engine::prefs::newer_notice(key))), Ok(_) => {} Err(error) => saved(Err(error)), })), @@ -174,6 +178,11 @@ mod prefs { } Ok(Updated::Unchanged) => PrefUpdate::Unchanged, Ok(Updated::Busy) => PrefUpdate::Busy, + // Never written over; said (once, while it stays the last failure). + Ok(Updated::Newer) => { + saved(Err(rustgis_engine::prefs::newer_notice(key))); + PrefUpdate::Failed + } Err(error) => { saved(Err(error)); PrefUpdate::Failed diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 8a3d72daf6..373081cd95 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -932,34 +932,45 @@ pub fn write_atomic_with>( atomic_write_at(&path, write) } -/// Opens (creating it, empty) an app-managed file used only to lock on: never through a symbolic -/// link (on Unix the open itself refuses one, so none can be swapped in between a check and the -/// open), only a regular file, readable and writable by its owner alone. Elsewhere a link or -/// other non-regular file at `path` is refused before and after the open. -pub fn open_lock_file(path: &Path) -> std::io::Result { +/// Opens an app-managed file used only to lock on, read and write, creating it empty when +/// `create` is set: never through a symbolic link (on Unix the open itself refuses one, so none +/// can be swapped in between a check and the open) and only a regular file; elsewhere a link or +/// other non-regular file is refused before and after the open. A file this call creates gets +/// `mode` on Unix, set through the open handle so the umask doesn't narrow it (`0o600` for one +/// user's own, `0o666` for a lock accounts share); an existing one keeps its own. +pub fn open_lock_file(path: &Path, create: bool, mode: u32) -> std::io::Result { let refused = || std::io::Error::other(format!("{} isn't a regular file", path.display())); - let mut options = std::fs::OpenOptions::new(); - options.read(true).write(true).create(true).truncate(false); - #[cfg(all(unix, not(target_arch = "wasm32")))] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600).custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32); - } + #[cfg(not(all(unix, not(target_arch = "wasm32"))))] + let _ = mode; + let open = |create_new: bool| { + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true).create_new(create_new); + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32); + } + options.open(path).map_err(|e| if e.raw_os_error() == Some(rustix_eloop()) { refused() } else { e }) + }; #[cfg(not(all(unix, not(target_arch = "wasm32"))))] if std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { return Err(refused()); } - let file = options.open(path).map_err(|e| if e.raw_os_error() == Some(rustix_eloop()) { refused() } else { e })?; + let (file, created) = match create.then(|| open(true)) { + Some(Ok(file)) => (file, true), + Some(Err(e)) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e), + _ => (open(false)?, false), + }; if !file.metadata()?.is_file() || std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { return Err(refused()); } #[cfg(all(unix, not(target_arch = "wasm32")))] - { + if created { use std::os::unix::fs::PermissionsExt; - if file.metadata()?.permissions().mode() & 0o777 != 0o600 { - file.set_permissions(std::fs::Permissions::from_mode(0o600))?; - } + file.set_permissions(std::fs::Permissions::from_mode(mode))?; } + #[cfg(not(all(unix, not(target_arch = "wasm32"))))] + let _ = created; Ok(file) } diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 48e72c1073..be8571ac48 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -98,35 +98,11 @@ fn source_lock(path: &Path) -> Result { if std::fs::symlink_metadata(&lock_path).is_ok_and(|m| !m.file_type().is_file()) { return Err(refused(path, format!("{} isn't a regular lock file", lock_path.display()))); } - let mut options = std::fs::OpenOptions::new(); - options.read(true).write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600).custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32); - } - let opened = match options.open(&lock_path) { - Ok(file) => { - // The empty sidecar contains no source data. Accounts sharing the directory need - // read/write access regardless of source groups, ACLs or a private umask: NFS - // exclusive locks require a writable handle. Set modes through the open handle. - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - file.set_permissions(std::fs::Permissions::from_mode(0o666))?; - } - Ok(file) - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { - options.create_new(false); - options.open(&lock_path) - } - Err(e) => Err(e), - }; - let file = opened.map_err(|e| refused(path, format!("couldn't open {}: {e}", lock_path.display())))?; - if !file.metadata()?.is_file() { - return Err(refused(path, "its lock isn't a regular file")); - } + // The empty sidecar contains no source data. Accounts sharing the directory need read/write + // access regardless of source groups, ACLs or a private umask: NFS exclusive locks require a + // writable handle, so a new one is made 0o666. + let file = crate::io::open_lock_file(&lock_path, true, 0o666) + .map_err(|e| refused(path, format!("couldn't open {}: {e}", lock_path.display())))?; file.try_lock().map_err(|e| match e { std::fs::TryLockError::WouldBlock => refused(path, "another RustGIS publisher holds this source; try again after it finishes"), std::fs::TryLockError::Error(e) => refused(path, format!("couldn't lock {}: {e}", lock_path.display())), diff --git a/crates/data/src/source/shp/cache.rs b/crates/data/src/source/shp/cache.rs index 857824b8bd..206655cac6 100644 --- a/crates/data/src/source/shp/cache.rs +++ b/crates/data/src/source/shp/cache.rs @@ -119,18 +119,8 @@ fn lease_file(path: &Path, create: bool) -> io::Result { if std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { return Err(io::Error::other("cache lease is not a regular file")); } - let mut options = OpenOptions::new(); - options.read(true).write(true).create(create).truncate(false); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600).custom_flags((rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32); - } - let file = options.open(path)?; + let file = crate::io::open_lock_file(path, create, 0o600)?; let metadata = file.metadata()?; - if !metadata.is_file() { - return Err(io::Error::other("cache lease is not a regular file")); - } #[cfg(unix)] { use std::os::unix::fs::MetadataExt; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index daa324bd8a..a1da83861e 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -59,16 +59,18 @@ pub fn write(key: &str, value: &str) -> Result { write_in(&dir.join(FILE), key, value) } -/// [`write`] of the file at `path` (a test folder in tests). +/// [`write`] of the file at `path` (a test folder in tests). The write and what is left to save +/// change together under [`WRITE_LOCK`], so a value left to save is never older than one written +/// since. fn write_in(path: &Path, key: &str, value: &str) -> Result { - let done = { - let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - update_file(path, key, |_| Some(value.to_string())) - }; + let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let done = update_file(path, key, |_| Some(value.to_string())); let mut pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let id = (path.to_path_buf(), key.to_string()); match done { - Ok(Updated::Busy) => { + // Left to save: the lock was busy, or what is stored is a newer RustGIS's (refused, and + // tried again in case it changes). + Ok(Updated::Busy | Updated::Newer) => { pending.insert(id, value.to_string()); } _ => { @@ -78,10 +80,20 @@ fn write_in(path: &Path, key: &str, value: &str) -> Result { done } -/// Values [`write`] couldn't save while another copy held the lock, by file and key: the latest -/// of each. +/// Values [`write`] couldn't save yet, by file and key: the latest of each. static PENDING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); +/// The value of `key` left to save, if [`write`] left one: newer than what the file holds, so a +/// read of the setting gives it. +pub fn pending(key: &str) -> Option { + let dir = rustgis_data::dirs::config_dir()?; + pending_in(&dir.join(FILE), key) +} + +fn pending_in(path: &Path, key: &str) -> Option { + PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&(path.to_path_buf(), key.to_string())).cloned() +} + /// Writes again what [`write`] left to save. `wait` bounds how long it waits for another copy /// to let go of the lock: zero on the UI thread (it never waits there), a second or two at exit. /// Returns what each write tried came to (to report), and whether any is still left. @@ -101,24 +113,27 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec { + busy = true; + break; + } + Ok(Updated::Newer) => said.push(Err(newer_notice(&key))), + done => { + PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&(path, key)); + said.push(done.map(|d| match d { + Updated::Saved(set_aside) => set_aside, + _ => None, + })); + } + } } - said.push(done.map(|d| match d { - Updated::Saved(set_aside) => set_aside, - Updated::Unchanged | Updated::Busy => None, - })); } #[cfg(not(target_arch = "wasm32"))] if busy && start.elapsed() < wait { @@ -141,6 +156,18 @@ pub enum Updated { /// Another copy of RustGIS is saving its preferences: nothing was read or written. Try again /// later; this never waits for it. Busy, + /// What is stored under the key isn't text: a newer RustGIS's setting this version can't + /// read. Never written over (as AGENTS.md's rule for newer settings asks); [`newer_notice`] + /// says so. + Newer, +} + +/// Says that `key` was saved by a newer RustGIS in a form this version can't read, so a change +/// to it here isn't saved. +pub fn newer_notice(key: &str) -> String { + format!( + "the setting \"{key}\" was saved by a newer RustGIS in a form this version can't read: it is kept as it is, and this change isn't saved" + ) } /// Updates one desktop preference from its stored value: `value` is given what is stored now @@ -205,7 +232,7 @@ fn lock(path: &Path) -> Result { // Never through a link (the open itself refuses one on Unix), only a regular file, its // owner's alone. let file = std::fs::create_dir_all(dir) - .and_then(|_| rustgis_data::io::open_lock_file(&lock_path)) + .and_then(|_| rustgis_data::io::open_lock_file(&lock_path, true, 0o600)) .map_err(|error| format!("could not save preferences: couldn't open {}: {error}", lock_path.display()))?; match file.try_lock() { Ok(()) => Ok(Locked::Held(Lock(file))), @@ -247,6 +274,7 @@ fn write_at_with_bytes( match write_with(path, key, |_| Some(value.to_string()), bytes, sync)? { Updated::Saved(set_aside) => Ok(set_aside), Updated::Unchanged | Updated::Busy => Ok(None), + Updated::Newer => Err(newer_notice(key)), } } @@ -267,7 +295,13 @@ fn write_with( Err(error) if error.kind() == std::io::ErrorKind::NotFound => (Map::new(), None), Err(error) => return Err(format!("could not read preferences: {error}")), }; - let Some(value) = value(map.get(key).and_then(Value::as_str)) else { return Ok(Updated::Unchanged) }; + // A newer RustGIS's setting this version can't read (not text) is never written over. + let stored = match map.get(key) { + Some(Value::String(text)) => Some(text.as_str()), + Some(_) => return Ok(Updated::Newer), + None => None, + }; + let Some(value) = value(stored) else { return Ok(Updated::Unchanged) }; let set_aside = match malformed { Some(bytes) => Some(set_aside(path, &bytes)?), None => None, @@ -545,6 +579,44 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// A value left to save is what the setting reads as until it is written, never written + /// over a newer one saved since; and a setting a newer RustGIS stored as something other than + /// text is never written over, the change kept to save and said. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn pending_values_stay_newest_and_newer_settings_are_kept() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-pending-order-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + let held = lock(&path).unwrap(); + assert_eq!(write_in(&path, "theme", "old").unwrap(), Updated::Busy); + assert_eq!(pending_in(&path, "theme").as_deref(), Some("old"), "read as the setting until written"); + drop(held); + // A newer value saved meanwhile: the old one is no longer left, so a retry never puts it back. + assert_eq!(write_in(&path, "theme", "new").unwrap(), Updated::Saved(None)); + assert_eq!(pending_in(&path, "theme"), None); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(said.is_empty() && !left, "{said:?}"); + assert_eq!(read_at(&path).unwrap().get("theme").and_then(Value::as_str), Some("new")); + + // A newer RustGIS stored data_sources as an object: never written over. + let newer = r#"{"data_sources":{"version":2,"lists":[]},"theme":"new"}"#; + std::fs::write(&path, newer).unwrap(); + assert_eq!(update_file(&path, "data_sources", |_| Some("{}".into())).unwrap(), Updated::Newer); + assert_eq!(write_in(&path, "data_sources", "{}").unwrap(), Updated::Newer); + assert_eq!(std::fs::read_to_string(&path).unwrap(), newer); + assert_eq!(pending_in(&path, "data_sources").as_deref(), Some("{}"), "kept to save"); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(left && matches!(said.as_slice(), [Err(e)] if e.contains("newer RustGIS")), "{said:?}"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), newer); + // Other settings are still written beside it. + assert_eq!(write_in(&path, "theme", "dark").unwrap(), Updated::Saved(None)); + assert_eq!(read_at(&path).unwrap().get("data_sources"), Some(&serde_json::json!({"version": 2, "lists": []}))); + PENDING.lock().unwrap().retain(|(p, _), _| p != &path); + std::fs::remove_dir_all(dir).unwrap(); + } + /// The preferences lock is shared by every copy of RustGIS: while one holds it, another's /// update returns at once, reading and writing nothing, and saves once it is let go. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index 338558615b..c31574ded1 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -55,6 +55,10 @@ pub struct Sources { touched: BTreeSet<(&'static str, String, String)>, #[serde(skip)] removed: BTreeSet<(&'static str, String, String)>, + /// Of those, the sources whose details (`extra`) this session changed: their kept details + /// from a newer RustGIS went with the old ones. + #[serde(skip)] + details_changed: BTreeSet<(&'static str, String, String)>, } /// The three lists, as the preference names them. @@ -393,6 +397,7 @@ impl Sources { self.kept.whole = None; self.touched.clear(); self.removed.clear(); + self.details_changed.clear(); self.generation += 1; return Ok(()); }; @@ -403,24 +408,43 @@ impl Sources { for (list, kind, address) in &self.removed { let _ = next.forget(list, kind, address); } - // A source this session changed is written with what this session keeps for it, exactly: - // its fields and details from a newer RustGIS, or none (replaced with other details, its - // old ones went), never the stored row's again. - let exact = |next: &mut Sources, key: &(&'static str, String, String)| { - match self.kept.fields.get(key) { - Some(fields) => next.kept.fields.insert(key.clone(), fields.clone()), - None => next.kept.fields.remove(key), - }; - match self.kept.extra.get(key) { - Some(newer) => next.kept.extra.insert(key.clone(), newer.clone()), - None => next.kept.extra.remove(key), - }; + // Row by row, this session's changes are laid over the stored row, never the other way: + // what a newer RustGIS stored for a source since (unknown fields, details this version + // doesn't use) stays, unless this session changed that part itself. A source this + // session gave other details is written with what it keeps for them (none, when those + // went with the old details), never the stored row's again; one the stored lists lack + // is written with what this session keeps for it. + let carry = |next: &mut Sources, key: &(&'static str, String, String), stored_had: bool| { + let own_details = self.details_changed.contains(key); + if !stored_had { + match self.kept.fields.get(key) { + Some(fields) => next.kept.fields.insert(key.clone(), fields.clone()), + None => next.kept.fields.remove(key), + }; + } + if !stored_had || own_details { + match self.kept.extra.get(key) { + Some(newer) => next.kept.extra.insert(key.clone(), newer.clone()), + None => next.kept.extra.remove(key), + }; + } }; for list in LISTS { let cap = if list == "recent" { MAX_RECENT } else { MAX_KEPT }; - let ours: Vec = self.list(list).iter().filter(|s| self.touched.contains(&key_of(list, s))).cloned().collect(); - for source in &ours { - exact(&mut next, &key_of(list, source)); + let mut ours: Vec = self.list(list).iter().filter(|s| self.touched.contains(&key_of(list, s))).cloned().collect(); + let mut had = Vec::with_capacity(ours.len()); + for source in &mut ours { + let key = key_of(list, source); + let stored = next.list(list).iter().find(|r| same(r, source)); + // Details this session didn't change are the stored row's (another window may + // have changed them since); its other changes (a name, a place) are its own. + if let Some(stored) = stored + && !self.details_changed.contains(&key) + { + source.extra = stored.extra.clone(); + } + had.push(stored.is_some()); + carry(&mut next, &key, had.last().copied().unwrap_or(false)); } if list == "recent" { next.recent.retain(|r| !ours.iter().any(|o| same(o, r))); @@ -456,11 +480,10 @@ impl Sources { for id in ids { next.adopt(list, &id); } - // Adopting a stored row past the limit mustn't bring its details back either. - for source in &ours { - let key = key_of(list, source); + // Adopting a stored row past the limit mustn't bring back details this session replaced. + for (source, stored_had) in ours.iter().zip(had) { if next.list(list).iter().any(|s| same(s, source)) { - exact(&mut next, &key); + carry(&mut next, &key_of(list, source), stored_had); } } } @@ -469,6 +492,7 @@ impl Sources { // Stored as they are now: nothing is this session's own change any more. next.touched.clear(); next.removed.clear(); + next.details_changed.clear(); next.generation = self.generation + 1; *self = next; Ok(()) @@ -584,7 +608,10 @@ impl Sources { /// Notes a source just added (the most recent first, each once). pub fn note(&mut self, s: Source) { let Ok(s) = clean(s) else { return }; - let changed = self.recent.iter().any(|r| same(r, &s) && *r != s); + // Only other details drop the kept ones (a new name or place keeps them); a source new to + // the list has the details this session gave it. + let changed = !self.recent.iter().any(|r| same(r, &s) && r.extra == s.extra); + self.recent.retain(|r| !same(r, &s)); self.recent.insert(0, s); self.recent.truncate(MAX_RECENT); @@ -592,6 +619,7 @@ impl Sources { // Noted with other details, as in [`Sources::keep`]. if changed { self.kept.extra.remove(&("recent", id.0.clone(), id.1.clone())); + self.details_changed.insert(("recent", id.0.clone(), id.1.clone())); } self.adopt("recent", &id); // A source no longer recent takes the fields kept for it along. @@ -599,6 +627,7 @@ impl Sources { self.kept.fields.retain(|(list, kind, address), _| still_listed(recent, list, kind, address)); self.kept.extra.retain(|(list, kind, address), _| still_listed(recent, list, kind, address)); self.touched.retain(|(list, kind, address)| still_listed(recent, list, kind, address)); + self.details_changed.retain(|(list, kind, address)| still_listed(recent, list, kind, address)); self.removed.remove(&("recent", id.0.clone(), id.1.clone())); self.touched.insert(("recent", id.0, id.1)); self.recheck_fields(); @@ -612,21 +641,25 @@ impl Sources { let list = LISTS.into_iter().find(|l| *l == list).ok_or_else(|| format!("unknown list '{list}' (favourites, saved or recent)"))?; let l = self.list_mut(list)?; // The same source keeps its place. - let mut changed = false; - if let Some(slot) = l.iter_mut().find(|r| same(r, &s)) { - changed = *slot != s; + let changed = if let Some(slot) = l.iter_mut().find(|r| same(r, &s)) { + // Only other details drop the kept ones (a new name keeps them). + let changed = slot.extra != s.extra; *slot = s.clone(); + changed } else { if l.len() >= MAX_KEPT { return Err(format!("up to {MAX_KEPT} sources in {list}")); } + // New to the list: its details are the ones this session gave it. l.push(s.clone()); - } + true + }; let id = identity(&s.kind, &s.address); // Replaced with other details, a source's kept details from a newer RustGIS were about // the old ones (a WMS layer kept beside a WMTS source's): they go with them. if changed { self.kept.extra.remove(&(list, id.0.clone(), id.1.clone())); + self.details_changed.insert((list, id.0.clone(), id.1.clone())); } self.adopt(list, &id); self.removed.remove(&(list, id.0.clone(), id.1.clone())); @@ -659,6 +692,7 @@ impl Sources { if gone || kept_gone { let key = (list, id.0.clone(), id.1.clone()); self.touched.remove(&key); + self.details_changed.remove(&key); self.removed.insert(key); } } @@ -677,14 +711,6 @@ impl Sources { } } - /// Marks these sources as what is stored: what this session changed is written. For a - /// caller that wrote [`Sources::to_json`] over what it last wrote itself, with nothing to lay - /// its changes over ([`Sources::rebase`] does this itself). - pub fn stored(&mut self) { - self.touched.clear(); - self.removed.clear(); - } - fn list_mut(&mut self, list: &str) -> Result<&mut Vec, String> { match list { "favourites" => Ok(&mut self.favourites), @@ -1783,6 +1809,40 @@ MIIE assert_eq!(next, s); } + /// What a newer RustGIS stored for a source after this session read it (an unknown field, + /// details this version doesn't use) stays when this session saves a change to that source + /// that doesn't touch its details: noting it again, renaming it. + #[test] + fn rebase_keeps_what_a_newer_window_stored_since() { + let read = json!({ + "recent": [{"kind": "file", "name": "X", "address": "/x.csv"}], + "saved": [{"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "layers": ["a"]}}] + }) + .to_string(); + let mut s = Sources::from_json(&read); + // A newer window stores more for both since. + let newer = json!({ + "recent": [{"kind": "file", "name": "X", "address": "/x.csv", "future": 1, "extra": {"tileSize": 512}}], + "saved": [{"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "layers": ["a", "b"]}, "opened": 2}] + }) + .to_string(); + s.note(Source { kind: "file".into(), name: "X".into(), address: "/x.csv".into(), extra: Value::Null }); + // Renamed here: a new name keeps the details kept for it. + s.keep( + "saved", + Source { kind: "service".into(), name: "WMS".into(), address: "https://h/wms".into(), extra: json!({"type": "wms"}) }, + ) + .unwrap(); + assert!(s.to_json().contains(r#""layers":["a"]"#), "a rename keeps them: {}", s.to_json()); + s.rebase(Some(&newer), Some(&read)).unwrap(); + let written: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(written["recent"][0]["future"], json!(1), "{written}"); + assert_eq!(written["recent"][0]["extra"], json!({"tileSize": 512}), "{written}"); + assert_eq!(written["saved"][0]["name"], json!("WMS"), "this session's rename"); + assert_eq!(written["saved"][0]["extra"], json!({"type": "wms", "layers": ["a", "b"]}), "{written}"); + assert_eq!(written["saved"][0]["opened"], json!(2), "{written}"); + } + /// Through the desktop's save (laid over what is stored): a source this session saved again /// with other details is written with what this session keeps for it, never the stored row's /// old details glued back; a source it didn't change keeps the stored row's. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16d72898b0..f597adaaef 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6434,10 +6434,8 @@ impl RustGisApp { if let Some(retry) = sourcespane::retry_in(self) { ctx.request_repaint_after(retry); } - if let Some(retry) = &self.services.retry_prefs - && retry() - { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); + if let Some(retry) = sourcespane::retry_prefs(self) { + ctx.request_repaint_after(retry); } sourcespane::save_connections(self); self.save_raster_defaults(); diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 21d6469ae4..cd401cc982 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -29,24 +29,52 @@ pub struct State { /// What this session last wrote: a save that finds it stored has nothing to lay its changes /// over. last_written: Option, - /// When a save that didn't happen (the preferences busy, unreadable or failing) is tried - /// again, and how many have failed in a row. - retry_at: Option, - failures: u32, + /// When a data sources save that didn't happen (the preferences busy, unreadable or + /// failing) is tried again. + retry: Retry, /// Since when another copy of the app has kept the preferences busy. busy_since: Option, + /// When the other preferences left to save (`retry_prefs`) are tried again. + prefs_retry: Retry, +} + +/// When a save that didn't happen is tried again, so a frame doesn't retry it each time: +/// shared by the data sources and the app's other preferences. +#[derive(Default)] +struct Retry { + at: Option, + /// Failed tries in a row. + failures: u32, +} + +impl Retry { + fn due(&self, now: web_time::Instant) -> bool { + self.at.is_none_or(|at| now >= at) + } + /// Tried again after `delay`, whatever failed before (another copy busy). + fn after(&mut self, now: web_time::Instant, delay: std::time::Duration) { + self.at = Some(now + delay); + } + /// One more failure in a row: tried again after `first`, doubling each time up to `most`. + fn failed(&mut self, now: web_time::Instant, first: std::time::Duration, most: std::time::Duration) { + self.failures = self.failures.saturating_add(1); + self.at = Some(now + first.saturating_mul(1 << self.failures.saturating_sub(1).min(16)).min(most)); + } + fn done(&mut self) { + *self = Retry::default(); + } + /// How long until it is due, if it waits. + fn wait(&self, now: web_time::Instant) -> Option { + self.at.map(|at| at.saturating_duration_since(now)) + } } /// How soon a save is tried again while another copy of the app saves its preferences. const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(250); /// How long another copy may keep them busy before that is said. const BUSY_SAY: std::time::Duration = std::time::Duration::from_secs(10); - -/// How long after `failures` failed saves in a row the next is tried: one second, doubling up -/// to a minute. -fn backoff(failures: u32) -> std::time::Duration { - std::time::Duration::from_secs(1u64 << failures.saturating_sub(1).min(6)).min(std::time::Duration::from_secs(60)) -} +/// A failed data sources save is tried again after a second, doubling up to a minute. +const FAILED_RETRY: (std::time::Duration, std::time::Duration) = (std::time::Duration::from_secs(1), std::time::Duration::from_secs(60)); /// The sources to show this frame: the last snapshot unless they changed since. fn snapshot(app: &mut RustGisApp) -> std::sync::Arc { @@ -134,7 +162,7 @@ pub fn save(app: &mut RustGisApp) { } return; } - if app.ui.sources.retry_at.is_some_and(|at| web_time::Instant::now() < at) { + if !app.ui.sources.retry.due(web_time::Instant::now()) { return; } attempt(app); @@ -142,27 +170,16 @@ pub fn save(app: &mut RustGisApp) { /// One try at saving the data sources through `update_pref`: what it came to. fn attempt(app: &mut RustGisApp) -> Option { - use rustgis_engine::sources::Sources; - enum Next { - /// What is stored is what this session last wrote: its lists are written as they are. - Own(String), - Rebased(Box, String), - } let update = app.services.update_pref.as_ref()?; let now = web_time::Instant::now(); let (mut next, mut unreadable) = (None, None); let (sources, last) = (&app.session.sources, app.ui.sources.last_written.as_deref()); let outcome = update(PREF, &mut |stored| { - if stored.is_some() && stored == last { - let text = sources.to_json(); - next = Some(Next::Own(text.clone())); - return Some(text); - } let mut rebased = sources.clone(); match rebased.rebase(stored, last) { Ok(()) => { let text = rebased.to_json(); - next = Some(Next::Rebased(Box::new(rebased), text.clone())); + next = Some((rebased, text.clone())); Some(text) } // Never written over: the changes wait until it can be read (or is removed). @@ -174,26 +191,17 @@ fn attempt(app: &mut RustGisApp) -> Option { }); let state = &mut app.ui.sources; match (outcome, next) { - (crate::PrefUpdate::Saved, Some(next)) => { - (state.retry_at, state.failures, state.busy_since, state.refusal_said) = (None, 0, None, false); + (crate::PrefUpdate::Saved, Some((sources, text))) => { + state.retry.done(); + (state.busy_since, state.refusal_said, state.last_written) = (None, false, Some(text)); state.said.retain(|(kind, _)| *kind != "busy"); - let text = match next { - Next::Own(text) => { - app.session.sources.stored(); - text - } - Next::Rebased(sources, text) => { - app.session.sources = *sources; - text - } - }; - app.ui.sources.last_written = Some(text); + app.session.sources = sources; app.ui.sources_saved = app.session.sources.generation; say_unread(app); } (crate::PrefUpdate::Busy, _) => { let since = *state.busy_since.get_or_insert(now); - state.retry_at = Some(now + BUSY_RETRY); + state.retry.after(now, BUSY_RETRY); if now.duration_since(since) >= BUSY_SAY { let said = crate::tl!("The data sources aren't saved yet: another copy of RustGIS keeps its preferences busy. Trying again."); @@ -202,8 +210,7 @@ fn attempt(app: &mut RustGisApp) -> Option { } _ => { state.busy_since = None; - state.failures = state.failures.saturating_add(1); - state.retry_at = Some(now + backoff(state.failures)); + state.retry.failed(now, FAILED_RETRY.0, FAILED_RETRY.1); // Said when a save refuses, though the same was said when the sources were read. if let Some(why) = unreadable && !state.refusal_said @@ -218,8 +225,9 @@ fn attempt(app: &mut RustGisApp) -> Option { /// As the app closes: data sources left to save are tried once more whatever the retry delay, /// trying again for up to `wait` while another copy of the app keeps the preferences busy -/// (closing isn't the path that must answer at once). What still can't be saved is said and -/// logged. +/// (closing isn't the path that must answer at once). What still can't be saved is logged and +/// said in this session's messages; with the window closing, only the log keeps it for later +/// (the next start doesn't say it). pub fn save_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { if !app.ui.sources.loaded || app.session.sources.generation == app.ui.sources_saved || app.services.update_pref.is_none() { return; @@ -234,9 +242,11 @@ pub fn save_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { if !busy || start.elapsed() >= wait { let why = if busy { "another copy of RustGIS kept its preferences busy" } else { "they couldn't be written" }; log::warn!("the data sources changed in this session weren't saved: {why}"); + let said = + if busy { crate::tl!("another copy of RustGIS kept its preferences busy") } else { crate::tl!("they couldn't be written") }; app.session.warn(crate::i18n::fmt( "The data sources changed in this session weren't saved as RustGIS closed: {why}.", - &[("why", why)], + &[("why", said)], )); return; } @@ -251,8 +261,27 @@ pub fn retry_in(app: &RustGisApp) -> Option { if app.session.sources.generation == app.ui.sources_saved { return None; } - let at = app.ui.sources.retry_at?; - Some(at.saturating_duration_since(web_time::Instant::now())) + app.ui.sources.retry.wait(web_time::Instant::now()) +} + +/// Saves again the app's other preferences left to save while another copy saved its own +/// (`Services::retry_prefs`), when due: tried at once, then after a quarter second, doubling up +/// to five seconds while they stay left, so a long-held lock doesn't cost every frame. How soon +/// it is tried again, if anything is left. +pub fn retry_prefs(app: &mut RustGisApp) -> Option { + let retry = app.services.retry_prefs.as_ref()?; + let now = web_time::Instant::now(); + let state = &mut app.ui.sources.prefs_retry; + if !state.due(now) { + return state.wait(now); + } + if retry() { + state.failed(now, std::time::Duration::from_millis(250), std::time::Duration::from_secs(5)); + state.wait(now) + } else { + state.done(); + None + } } /// Loads connections before commands can run, importing legacy saved endpoints only once. From 77e25417969a95f32cdb89c9e1eb5c1ed1b2ae3f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:41:48 -0600 Subject: [PATCH 03/27] fix(engine): settings a newer RustGIS stored stay refused without retries, and a data sources save keeps another window's details and this one's order (#1962) A setting refused because a newer RustGIS stored it in a form this version can't read was retried every few seconds for the rest of the session. It is now kept for the session, said once per key, and not retried or counted as left at exit; a refused data sources save waits for the next change here instead of a timer. A source new to this window no longer counts as details it changed, so details another window stored for it since are kept. This window's additions keep their place in the list, a source saved past a list's limit replaces its earlier row there, and rechecked kept details lose only the entries that read as a secret. At exit, the data sources and the other settings share one deadline, and what isn't saved is said with why. Frames look for settings left to save once a second, and only take the lock when there are some. --- apps/rustgis/src/main.rs | 23 +++--- crates/engine/src/prefs.rs | 128 ++++++++++++++++++++++++------ crates/engine/src/sources.rs | 126 +++++++++++++++++++++++++---- crates/ui-egui/src/lib.rs | 21 +++-- crates/ui-egui/src/sourcespane.rs | 78 +++++++++++++----- crates/ui-egui/tests/smoke.rs | 64 +++++++++++++-- 6 files changed, 358 insertions(+), 82 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index cf51eae6c3..e1c84218b1 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -163,11 +163,16 @@ mod prefs { // `retry_prefs` writes it on a later frame (and `on_exit` at the end). save_pref: Some(Box::new(|key: &str, value: &str| match rustgis_engine::prefs::write(key, value) { Ok(rustgis_engine::prefs::Updated::Saved(set_aside)) => saved(Ok(set_aside)), - Ok(rustgis_engine::prefs::Updated::Newer) => saved(Err(rustgis_engine::prefs::newer_notice(key))), + // Never written over, nor tried again this session; said once for the key. + Ok(rustgis_engine::prefs::Updated::Newer) => { + if let Some(notice) = rustgis_engine::prefs::newer_notice_once(key) { + saved(Err(notice)); + } + } Ok(_) => {} Err(error) => saved(Err(error)), })), - retry_prefs: Some(Box::new(|| retry_saves(std::time::Duration::ZERO))), + retry_prefs: Some(Box::new(retry_saves)), update_pref: Some(Box::new(|key: &str, value: &mut dyn FnMut(Option<&str>) -> Option| { use rustgis_engine::prefs::Updated; use rustgis_ui_egui::PrefUpdate; @@ -178,10 +183,10 @@ mod prefs { } Ok(Updated::Unchanged) => PrefUpdate::Unchanged, Ok(Updated::Busy) => PrefUpdate::Busy, - // Never written over; said (once, while it stays the last failure). + // Never written over; the window says it (once) and stops trying. Ok(Updated::Newer) => { - saved(Err(rustgis_engine::prefs::newer_notice(key))); - PrefUpdate::Failed + log::warn!("{}", rustgis_engine::prefs::newer_notice(key)); + PrefUpdate::Refused } Err(error) => { saved(Err(error)); @@ -507,11 +512,9 @@ impl eframe::App for App { self.0.end_exports(); self.0.end_autosave(); // Settings left to save while another copy of RustGIS saved its own: tried once more, - // waiting a little for it (closing isn't the path that must answer at once). - self.0.save_sources_at_exit(); - if prefs::retry_saves(std::time::Duration::from_millis(1500)) { - log::warn!("some settings couldn't be saved: another copy of RustGIS kept its preferences busy"); - } + // waiting a little for it within one deadline (closing isn't the path that must answer at + // once); what still isn't saved is logged with why and said in the session. + self.0.save_prefs_at_exit(std::time::Duration::from_millis(1500)); // Session plugins' programs end with the app, with what they started. rustgis_engine::plugins::session::stop_all(); // The installer starts before the marker goes, so a RustGIS started meanwhile finds this diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index a1da83861e..fc1fb274a8 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -65,33 +65,62 @@ pub fn write(key: &str, value: &str) -> Result { fn write_in(path: &Path, key: &str, value: &str) -> Result { let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let done = update_file(path, key, |_| Some(value.to_string())); - let mut pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let id = (path.to_path_buf(), key.to_string()); + let mut pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut refused = REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + pending.remove(&id); + refused.remove(&id); match done { - // Left to save: the lock was busy, or what is stored is a newer RustGIS's (refused, and - // tried again in case it changes). - Ok(Updated::Busy | Updated::Newer) => { + // Left to save: tried again once the other copy lets go of the lock. + Ok(Updated::Busy) => { pending.insert(id, value.to_string()); } - _ => { - pending.remove(&id); + // What is stored is a newer RustGIS's: never written over, and not tried again this + // session (a later write of the key tries once more). + Ok(Updated::Newer) => { + refused.insert(id, value.to_string()); } + _ => {} } done } -/// Values [`write`] couldn't save yet, by file and key: the latest of each. -static PENDING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); +type Values = Mutex>; + +/// Values [`write`] couldn't save yet while another copy held the lock, by file and key: the +/// latest of each, tried again by [`retry_pending`]. +static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); + +/// Values refused because a newer RustGIS stored the key in a form this version can't read: +/// kept for this session (a read of the setting gives them), never tried again. +static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); + +/// Keys whose refusal ([`newer_notice`]) has been said, so each is said once a session. +static SAID_NEWER: Mutex> = Mutex::new(std::collections::BTreeSet::new()); -/// The value of `key` left to save, if [`write`] left one: newer than what the file holds, so a -/// read of the setting gives it. +/// The value of `key` left to save, if [`write`] left one (waiting for the lock, or refused for +/// a newer RustGIS's setting): newer than what the file holds for this session, so a read of +/// the setting gives it. pub fn pending(key: &str) -> Option { let dir = rustgis_data::dirs::config_dir()?; pending_in(&dir.join(FILE), key) } fn pending_in(path: &Path, key: &str) -> Option { - PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&(path.to_path_buf(), key.to_string())).cloned() + let id = (path.to_path_buf(), key.to_string()); + let pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&id).cloned(); + pending.or_else(|| REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&id).cloned()) +} + +/// [`newer_notice`] for `key` the first time it is refused this session; none after. +pub fn newer_notice_once(key: &str) -> Option { + let dir = rustgis_data::dirs::config_dir()?; + newer_notice_once_in(&dir.join(FILE), key) +} + +fn newer_notice_once_in(path: &Path, key: &str) -> Option { + let first = SAID_NEWER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert((path.to_path_buf(), key.to_string())); + first.then(|| newer_notice(key)) } /// Writes again what [`write`] left to save. `wait` bounds how long it waits for another copy @@ -108,6 +137,10 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec, wait: std::time::Duration) -> (Vec { - busy = true; - break; - } - Ok(Updated::Newer) => said.push(Err(newer_notice(&key))), - done => { - PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&(path, key)); - said.push(done.map(|d| match d { - Updated::Saved(set_aside) => set_aside, - _ => None, - })); + // Refused once, it isn't tried again (not on the next pass at exit either), + // and is said once. + Ok(Updated::Newer) => { + REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(id, value); + if let Some(notice) = newer_notice_once_in(&path, &key) { + said.push(Err(notice)); + } } + done => said.push(done.map(|d| match d { + Updated::Saved(set_aside) => set_aside, + _ => None, + })), } } } @@ -606,14 +645,53 @@ mod tests { assert_eq!(update_file(&path, "data_sources", |_| Some("{}".into())).unwrap(), Updated::Newer); assert_eq!(write_in(&path, "data_sources", "{}").unwrap(), Updated::Newer); assert_eq!(std::fs::read_to_string(&path).unwrap(), newer); - assert_eq!(pending_in(&path, "data_sources").as_deref(), Some("{}"), "kept to save"); + assert_eq!(pending_in(&path, "data_sources").as_deref(), Some("{}"), "read as the setting this session"); + // Refused for good this session: not retried (no file read, nothing left), said once. let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); - assert!(left && matches!(said.as_slice(), [Err(e)] if e.contains("newer RustGIS")), "{said:?}"); + assert!(said.is_empty() && !left, "{said:?}"); + assert!(newer_notice_once_in(&path, "data_sources").is_some_and(|n| n.contains("newer RustGIS"))); + assert_eq!(newer_notice_once_in(&path, "data_sources"), None, "said once a session"); assert_eq!(std::fs::read_to_string(&path).unwrap(), newer); // Other settings are still written beside it. assert_eq!(write_in(&path, "theme", "dark").unwrap(), Updated::Saved(None)); assert_eq!(read_at(&path).unwrap().get("data_sources"), Some(&serde_json::json!({"version": 2, "lists": []}))); - PENDING.lock().unwrap().retain(|(p, _), _| p != &path); + forget_values(&path); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Drops what this test folder left in the session-wide sets. + fn forget_values(path: &Path) { + PENDING.lock().unwrap().retain(|(p, _), _| p != path); + REFUSED.lock().unwrap().retain(|(p, _), _| p != path); + SAID_NEWER.lock().unwrap().retain(|(p, _)| p != path); + } + + /// At exit, a value left to save that turns out refused (a newer RustGIS stored the key + /// meanwhile) is tried once, said once, and not counted as left, however long the wait. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_value_refused_at_exit_is_tried_once() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-exit-refused-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + let held = lock(&path).unwrap(); + assert_eq!(write_in(&path, "data_sources", "{}").unwrap(), Updated::Busy); + // The other copy, a newer RustGIS, stores the key as an object, then lets go. + let newer = r#"{"data_sources":{"version":2}}"#; + std::fs::write(&path, newer).unwrap(); + let other = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(100)); // test-wait: another copy holding the lock briefly + drop(held); + }); + let started = std::time::Instant::now(); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::from_millis(1500)); + other.join().unwrap(); + assert!(!left, "a refused value isn't left"); + assert_eq!(said.iter().filter(|r| r.as_ref().is_err_and(|e| e.contains("newer RustGIS"))).count(), 1, "{said:?}"); + assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no more passes once refused"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), newer); + forget_values(&path); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index c31574ded1..de7b3d2836 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -456,23 +456,31 @@ impl Sources { next.kept.extra.retain(|(l, k, a), _| still_listed(recent, l, k, a)); } else { let mut over = Vec::new(); + let mine = self.list(list); let Ok(now) = next.list_mut(list) else { continue }; for source in ours.iter().cloned() { if let Some(slot) = now.iter_mut().find(|r| same(r, &source)) { *slot = source; } else if now.len() < cap { - now.push(source); + let at = place(mine, now, &source); + now.insert(at, source); } else { over.push(source); } } - // Past the limit (another window filled the list): kept as rows, and said. + // Past the limit (another window filled the list): kept as rows, and said. A row + // of the same source kept past the limit already is replaced, not repeated. for source in over { let row = next.row(list, &source); let key = key_of(list, &source); next.kept.fields.remove(&key); next.kept.extra.remove(&key); - next.kept.rows.entry(list).or_default().push(row); + let id = (key.1, key.2); + let rows = next.kept.rows.entry(list).or_default(); + let before = rows.len(); + rows.retain(|r| row_identity(r).as_ref() != Some(&id)); + next.kept.over = next.kept.over.saturating_sub(before - rows.len()); + rows.push(row); next.kept.over += 1; } } @@ -516,16 +524,29 @@ impl Sources { } } // Kept details passed with the row as it was read; beside details changed since (a web - // address next to a bare `key`), the row they make may hold a secret: then they go. + // address next to a bare `key`), one may read as a secret: those entries go, counted, + // and the rest stay. let keys: Vec<_> = self.kept.extra.keys().cloned().collect(); for key in keys { let (list, kind, address) = &key; let id = (kind.clone(), address.clone()); - let Some(source) = self.list(list).iter().find(|s| identity(&s.kind, &s.address) == id) else { continue }; - if holds_secret(&self.row(list, source)) - && let Some(gone) = self.kept.extra.remove(&key) - { - self.kept.secrets += gone.as_object().map_or(1, Map::len); + let Some(source) = self.list(list).iter().find(|s| identity(&s.kind, &s.address) == id).cloned() else { continue }; + match self.kept.extra.remove(&key) { + Some(Value::Object(entries)) => { + let entries = self.kept.without_secrets(entries, &source.address, &source.extra); + if !entries.is_empty() { + self.kept.extra.insert(key, Value::Object(entries)); + } + } + // Details that aren't an object stand for this source's details whole. + Some(whole) => { + if holds_secret(&json!({ "address": source.address, "extra": whole })) { + self.kept.secrets += 1; + } else { + self.kept.extra.insert(key, whole); + } + } + None => {} } } } @@ -608,9 +629,9 @@ impl Sources { /// Notes a source just added (the most recent first, each once). pub fn note(&mut self, s: Source) { let Ok(s) = clean(s) else { return }; - // Only other details drop the kept ones (a new name or place keeps them); a source new to - // the list has the details this session gave it. - let changed = !self.recent.iter().any(|r| same(r, &s) && r.extra == s.extra); + // Only details this session changed from what it had drop the kept ones (a new name or + // place keeps them); a source new here takes the stored row's when one exists by then. + let changed = self.recent.iter().any(|r| same(r, &s) && r.extra != s.extra); self.recent.retain(|r| !same(r, &s)); self.recent.insert(0, s); @@ -650,9 +671,9 @@ impl Sources { if l.len() >= MAX_KEPT { return Err(format!("up to {MAX_KEPT} sources in {list}")); } - // New to the list: its details are the ones this session gave it. + // New here: no details of its own changed (a stored row's, if one exists by the save, win). l.push(s.clone()); - true + false }; let id = identity(&s.kind, &s.address); // Replaced with other details, a source's kept details from a newer RustGIS were about @@ -729,6 +750,16 @@ fn identity(kind: &str, address: &str) -> (String, String) { (kind.to_string(), address) } +/// Where `source`, which this session added, goes in a list `now` merged from what is stored, +/// keeping this session's order (`mine`): right after the nearest source before it in `mine` +/// that `now` lists, past what other windows added there; first when none is (as +/// [`Sources::merge`] puts this session's own sources first). +fn place(mine: &[Source], now: &[Source], source: &Source) -> usize { + let before = mine.iter().take_while(|m| !same(m, source)).filter_map(|m| now.iter().position(|n| same(n, m))).last(); + let Some(at) = before.map(|p| p + 1) else { return 0 }; + at + now.iter().skip(at).take_while(|n| !mine.iter().any(|m| same(m, n))).count() +} + /// The key what is kept for a source in `list` goes under: the list and its identity. fn key_of(list: &'static str, source: &Source) -> (&'static str, String, String) { let (kind, address) = identity(&source.kind, &source.address); @@ -1801,7 +1832,8 @@ MIIE let mut next = s.clone(); next.rebase(Some(&theirs), Some(&stored)).unwrap(); let listed: Vec<_> = next.favourites.iter().map(|f| f.address.as_str()).collect(); - assert_eq!(listed, ["/theirs.csv", "/new.csv"]); + // This session's addition goes where it had it, first when nothing before it is listed. + assert_eq!(listed, ["/new.csv", "/theirs.csv"]); // Unreadable: an error that says so, and nothing of this session changed or written. let mut next = s.clone(); let error = next.rebase(Some("[\"not\", \"an object\"]"), None).unwrap_err(); @@ -1812,6 +1844,70 @@ MIIE /// What a newer RustGIS stored for a source after this session read it (an unknown field, /// details this version doesn't use) stays when this session saves a change to that source /// that doesn't touch its details: noting it again, renaming it. + #[test] + fn rebase_lays_only_what_this_session_did_over_what_is_stored() { + let file = |address: &str| Source { kind: "file".into(), address: address.into(), ..Source::default() }; + let favorites = |s: &Sources| s.favourites.iter().map(|f| f.address.clone()).collect::>(); + + // A source new to this session that another window stored since, with details a newer + // RustGIS wrote: the stored row's details win; this session didn't change them. + let mut s = Sources::from_json(&json!({"favourites": []}).to_string()); + s.keep( + "favourites", + Source { kind: "service".into(), name: "S".into(), address: "https://h/wms".into(), extra: json!({"type": "wms"}) }, + ) + .unwrap(); + let theirs = json!({"favourites": [{"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wmts", "tileSize": 512}}]}) + .to_string(); + s.rebase(Some(&theirs), None).unwrap(); + let written: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(written["favourites"][0]["extra"], json!({"type": "wmts", "tileSize": 512}), "{written}"); + + // This session's additions keep their place: before what it had, first; after, right + // after it (past what another window added there). + let stored = json!({"favourites": [file("/a.csv"), file("/b.csv")]}).to_string(); + let mut s = Sources::from_json(&stored); + s.keep("favourites", file("/y.csv")).unwrap(); + let mut early = Sources::default(); + early.keep("favourites", file("/x.csv")).unwrap(); + early.merge(Sources::from_json(&stored)); + assert_eq!(favorites(&early), ["/x.csv", "/a.csv", "/b.csv"]); + let theirs = json!({"favourites": [file("/a.csv"), file("/b.csv"), file("/c.csv")]}).to_string(); + early.rebase(Some(&theirs), None).unwrap(); + assert_eq!(favorites(&early), ["/x.csv", "/a.csv", "/b.csv", "/c.csv"]); + s.rebase(Some(&theirs), None).unwrap(); + assert_eq!(favorites(&s), ["/a.csv", "/b.csv", "/c.csv", "/y.csv"]); + + // Past the limit (another window filled the list), a source this session added is kept as + // one row, replacing a row of it already kept there, not counted twice. + let full: Vec = (0..=MAX_KEPT).map(|i| json!({"kind": "file", "name": "", "address": format!("/{i}.csv")})).collect(); + let mut full = full; + full.push(json!({"kind": "file", "name": "", "address": "/z.csv"})); + let stored = json!({ "favourites": full }).to_string(); + let mut s = Sources::from_json(&json!({"favourites": []}).to_string()); + s.keep("favourites", file("/z.csv")).unwrap(); + s.rebase(Some(&stored), None).unwrap(); + let rows = s.kept.rows.get("favourites").map_or(0, |r| r.iter().filter(|r| r["address"] == json!("/z.csv")).count()); + assert_eq!(rows, 1, "{:?}", s.kept.rows); + assert_eq!(s.kept.over, 2, "/{MAX_KEPT}.csv and /z.csv"); + assert_eq!(s.to_json().matches("/z.csv").count(), 1); + } + + /// Kept details from a newer RustGIS rechecked beside details changed since: only the entries + /// that now read as a secret go (and are counted), the others stay. + #[test] + fn rechecked_kept_details_lose_only_their_secrets() { + let mut s = Sources::from_json( + &json!({"saved": [{"kind": "file", "name": "F", "address": "/f.csv", "extra": {"key": "feature_id", "n": 5}}]}).to_string(), + ); + assert!(s.to_json().contains("feature_id")); + s.saved[0].extra = json!({"endpoint": "https://api.example"}); + let before = s.secrets_left_out(); + s.recheck_fields(); + assert_eq!(s.kept.extra.values().next(), Some(&json!({"n": 5})), "{:?}", s.kept.extra); + assert_eq!(s.secrets_left_out() - before, 1); + } + #[test] fn rebase_keeps_what_a_newer_window_stored_since() { let read = json!({ diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f597adaaef..148d784263 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -388,6 +388,9 @@ pub enum PrefUpdate { Busy, /// Saving failed (the hook said why). Failed, + /// What is stored is a newer version's, in a form this one can't read: never written over, + /// and not tried again until something else changes. + Refused, } /// Platform hooks. The desktop app leaves them empty and uses native file dialogs; the web app @@ -418,9 +421,10 @@ pub struct Services { /// keeps its preferences (the browser): `save_pref` is used. pub update_pref: Option) -> Option) -> PrefUpdate>>, /// Saves again what `save_pref` left to save while another copy of the app saved its own - /// preferences (the desktop's), never waiting; whether any is still left. Tried each frame - /// while one is. `None` where nothing is ever left (the browser). - pub retry_prefs: Option bool>>, + /// preferences (the desktop's), waiting up to the given time for it (none during the run, + /// a little as the app closes); whether any is still left. `None` where nothing is ever + /// left (the browser). + pub retry_prefs: Option bool>>, /// The system's secret store (see `docs/architecture.md` › Secrets): the desktop's keychain. /// `None` in the browser and on the command line, where secrets last for the session only. pub secrets: Option>, @@ -2690,11 +2694,12 @@ impl RustGisApp { } } - /// As the app closes (the desktop app's `on_exit`): data sources left to save are tried once - /// more, waiting up to a second and a half for another copy of the app to let go of the - /// preferences; what still can't be saved is said and logged. - pub fn save_sources_at_exit(&mut self) { - sourcespane::save_at_exit(self, std::time::Duration::from_millis(1500)); + /// As the app closes (the desktop app's `on_exit`): the data sources and other settings left + /// to save are tried once more, all within `wait` (a second and a half on the desktop) while + /// another copy of the app keeps the preferences busy. What still isn't saved is logged with + /// why and said in this session's messages; with the window closing, only the log keeps it. + pub fn save_prefs_at_exit(&mut self, wait: std::time::Duration) { + sourcespane::save_prefs_at_exit(self, wait); } /// A clean exit (the desktop app's `on_exit`): the recovery copy of this run's unsaved work diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index cd401cc982..2c7078b697 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -36,6 +36,9 @@ pub struct State { busy_since: Option, /// When the other preferences left to save (`retry_prefs`) are tried again. prefs_retry: Retry, + /// The generation of the sources when a save was refused because a newer RustGIS stored + /// them in a form this one can't read: not tried again until they change once more. + refused_at: Option, } /// When a save that didn't happen is tried again, so a frame doesn't retry it each time: @@ -162,7 +165,8 @@ pub fn save(app: &mut RustGisApp) { } return; } - if !app.ui.sources.retry.due(web_time::Instant::now()) { + // Refused for a newer RustGIS's stored sources: tried again only after another change here. + if !app.ui.sources.retry.due(web_time::Instant::now()) || app.ui.sources.refused_at == Some(app.session.sources.generation) { return; } attempt(app); @@ -193,7 +197,7 @@ fn attempt(app: &mut RustGisApp) -> Option { match (outcome, next) { (crate::PrefUpdate::Saved, Some((sources, text))) => { state.retry.done(); - (state.busy_since, state.refusal_said, state.last_written) = (None, false, Some(text)); + (state.busy_since, state.refusal_said, state.last_written, state.refused_at) = (None, false, Some(text), None); state.said.retain(|(kind, _)| *kind != "busy"); app.session.sources = sources; app.ui.sources_saved = app.session.sources.generation; @@ -208,6 +212,17 @@ fn attempt(app: &mut RustGisApp) -> Option { say_more(app, "busy", 1, said.to_string()); } } + // A newer RustGIS stored them in a form this one can't read: never written over, not + // tried again on a timer (only after another change here), and said once. + (crate::PrefUpdate::Refused, _) => { + state.busy_since = None; + state.retry.done(); + state.refused_at = Some(app.session.sources.generation); + let said = crate::tl!( + "The data sources aren't saved: a newer RustGIS saved them in a form this version can't read, so they are kept as they are." + ); + say_more(app, "newer-format", 1, said.to_string()); + } _ => { state.busy_since = None; state.retry.failed(now, FAILED_RETRY.0, FAILED_RETRY.1); @@ -223,27 +238,47 @@ fn attempt(app: &mut RustGisApp) -> Option { Some(outcome) } -/// As the app closes: data sources left to save are tried once more whatever the retry delay, -/// trying again for up to `wait` while another copy of the app keeps the preferences busy -/// (closing isn't the path that must answer at once). What still can't be saved is logged and -/// said in this session's messages; with the window closing, only the log keeps it for later -/// (the next start doesn't say it). -pub fn save_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { +/// As the app closes: the data sources and the other settings left to save are tried once more +/// whatever their retry delay, all within one `wait` while another copy of the app keeps the +/// preferences busy (closing isn't the path that must answer at once). What still isn't saved +/// is logged with why and said in this session's messages; with the window closing, only the +/// log keeps it for later (the next start doesn't say it). +pub fn save_prefs_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { + let deadline = web_time::Instant::now() + wait; + save_sources_at_exit(app, deadline); + if let Some(retry) = &app.services.retry_prefs + && retry(deadline.saturating_duration_since(web_time::Instant::now())) + { + log::warn!("some settings changed in this session weren't saved: another copy of RustGIS kept its preferences busy"); + app.session.warn(crate::tl!( + "Some settings changed in this session weren't saved as RustGIS closed: another copy of RustGIS kept its preferences busy." + )); + } +} + +/// The data sources' part of [`save_prefs_at_exit`], until `deadline`. +fn save_sources_at_exit(app: &mut RustGisApp, deadline: web_time::Instant) { if !app.ui.sources.loaded || app.session.sources.generation == app.ui.sources_saved || app.services.update_pref.is_none() { return; } - let start = web_time::Instant::now(); loop { let outcome = attempt(app); if app.session.sources.generation == app.ui.sources_saved { return; } let busy = outcome == Some(crate::PrefUpdate::Busy); - if !busy || start.elapsed() >= wait { - let why = if busy { "another copy of RustGIS kept its preferences busy" } else { "they couldn't be written" }; + if !busy || web_time::Instant::now() >= deadline { + let (why, said) = match outcome { + Some(crate::PrefUpdate::Busy) => { + ("another copy of RustGIS kept its preferences busy", crate::tl!("another copy of RustGIS kept its preferences busy")) + } + Some(crate::PrefUpdate::Refused) => ( + "a newer RustGIS saved them in a form this version can't read", + crate::tl!("a newer RustGIS saved them in a form this version can't read"), + ), + _ => ("they couldn't be written", crate::tl!("they couldn't be written")), + }; log::warn!("the data sources changed in this session weren't saved: {why}"); - let said = - if busy { crate::tl!("another copy of RustGIS kept its preferences busy") } else { crate::tl!("they couldn't be written") }; app.session.warn(crate::i18n::fmt( "The data sources changed in this session weren't saved as RustGIS closed: {why}.", &[("why", said)], @@ -258,28 +293,33 @@ pub fn save_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { /// How soon a data sources save left to do is tried again, if one is: the frame that tries it /// is asked for. pub fn retry_in(app: &RustGisApp) -> Option { - if app.session.sources.generation == app.ui.sources_saved { + if app.session.sources.generation == app.ui.sources_saved || app.ui.sources.refused_at == Some(app.session.sources.generation) { return None; } app.ui.sources.retry.wait(web_time::Instant::now()) } +/// How often frames look for other settings left to save while none is known to be. +const PREFS_IDLE_CHECK: std::time::Duration = std::time::Duration::from_secs(1); + /// Saves again the app's other preferences left to save while another copy saved its own -/// (`Services::retry_prefs`), when due: tried at once, then after a quarter second, doubling up -/// to five seconds while they stay left, so a long-held lock doesn't cost every frame. How soon -/// it is tried again, if anything is left. +/// (`Services::retry_prefs`), when due: with nothing left, looked for once a second, not every +/// frame; with something left, tried after a quarter second, doubling up to five seconds, so a +/// long-held lock doesn't cost every frame either. How soon it is tried again, if anything is +/// left (none: no frame is asked for). pub fn retry_prefs(app: &mut RustGisApp) -> Option { let retry = app.services.retry_prefs.as_ref()?; let now = web_time::Instant::now(); let state = &mut app.ui.sources.prefs_retry; if !state.due(now) { - return state.wait(now); + return (state.failures > 0).then(|| state.wait(now)).flatten(); } - if retry() { + if retry(std::time::Duration::ZERO) { state.failed(now, std::time::Duration::from_millis(250), std::time::Duration::from_secs(5)); state.wait(now) } else { state.done(); + state.after(now, PREFS_IDLE_CHECK); None } } diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 50f8c93ccb..e297e0156e 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -1559,13 +1559,14 @@ fn two_windows_keep_each_others_data_sources() { a.run("sources.favourite", favorite("/a.csv")).unwrap(); b.run("sources.favourite", favorite("/b.csv")).unwrap(); let stored = || stored_favorites(&store); - assert_eq!(stored(), ["/old.csv", "/a.csv", "/b.csv"]); + // Each window's own additions come first, as reading the stored ones put them. + assert_eq!(stored(), ["/b.csv", "/a.csv", "/old.csv"]); a.run("sources.remove", json!({"list": "favourites", "kind": "file", "address": "/old.csv"})).unwrap(); b.run("sources.favourite", favorite("/b2.csv")).unwrap(); - assert_eq!(stored(), ["/a.csv", "/b.csv", "/b2.csv"]); + assert_eq!(stored(), ["/b.csv", "/a.csv", "/b2.csv"]); // The window that saved last lists the other's favorites too. let listed: Vec<_> = b.session.sources.favourites.iter().map(|f| f.address.as_str()).collect(); - assert_eq!(listed, ["/a.csv", "/b.csv", "/b2.csv"]); + assert_eq!(listed, ["/b.csv", "/a.csv", "/b2.csv"]); // The stored sources removed or reset: the next save writes the window's whole list, not // only the source it just added. @@ -1676,17 +1677,70 @@ fn data_sources_left_to_save_are_saved_at_exit() { app.run("sources.favourite", json!({"kind": "file", "address": "/exit.csv"})).unwrap(); assert!(stored_favorites(&store).is_empty()); // The retry delay hasn't passed; at exit it is tried anyway, through one more busy answer. - app.save_sources_at_exit(); + app.save_prefs_at_exit(std::time::Duration::from_millis(1500)); assert_eq!(stored_favorites(&store), ["/exit.csv"]); // Still busy at the end of the wait: said, not lost silently. outcomes.lock().unwrap().extend(std::iter::repeat_n(PrefUpdate::Busy, 1000)); app.run("sources.favourite", json!({"kind": "file", "address": "/late.csv"})).unwrap(); - app.save_sources_at_exit(); + app.save_prefs_at_exit(std::time::Duration::from_millis(1500)); let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("weren't saved as RustGIS closed")), "{said:?}"); assert!(!stored_favorites(&store).contains(&"/late.csv".to_string())); } +/// The data sources and the other settings share one deadline at exit: however long the data +/// sources wait for another copy, the other settings get only what is left of it, and what +/// isn't saved of either is said. +#[test] +fn settings_left_to_save_share_one_deadline_at_exit() { + use rustgis_ui_egui::PrefUpdate; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), json!({"favourites": []}).to_string())]))); + let outcomes = PrefOutcomes::default(); + let mut app = window_over(&store, &outcomes); + let given = Arc::new(Mutex::new(Vec::new())); + let log = given.clone(); + app.services.retry_prefs = Some(Box::new(move |wait| { + log.lock().unwrap().push(wait); + true + })); + outcomes.lock().unwrap().extend(std::iter::repeat_n(PrefUpdate::Busy, 1000)); + app.run("sources.favourite", json!({"kind": "file", "address": "/x.csv"})).unwrap(); + let wait = std::time::Duration::from_millis(400); + let started = std::time::Instant::now(); + app.save_prefs_at_exit(wait); + assert!(started.elapsed() < wait + std::time::Duration::from_millis(300), "{:?}", started.elapsed()); + let given = given.lock().unwrap().last().copied(); + assert!(given.is_some_and(|g| g < std::time::Duration::from_millis(100)), "the rest of the one deadline: {given:?}"); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("data sources changed in this session weren't saved")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("Some settings changed in this session weren't saved")), "{said:?}"); +} + +/// A data sources save refused because a newer RustGIS stored them in a form this version can't +/// read is said once and not tried again on a timer, only after another change here. +#[test] +fn a_refused_data_sources_save_is_not_retried() { + use rustgis_ui_egui::PrefUpdate; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), json!({"favourites": []}).to_string())]))); + let outcomes = PrefOutcomes::default(); + let mut app = window_over(&store, &outcomes); + outcomes.lock().unwrap().push_back(PrefUpdate::Refused); + app.run("sources.favourite", json!({"kind": "file", "address": "/a.csv"})).unwrap(); + // Well past any retry delay, nothing is tried: a try now would find the store free and save. + std::thread::sleep(std::time::Duration::from_millis(1100)); // test-wait: past the longest first retry delay + app.run("sources.list", json!({})).unwrap(); + assert!(stored_favorites(&store).is_empty()); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.iter().filter(|t| t.contains("a newer RustGIS saved them")).count(), 1, "{said:?}"); + // Another change here tries again. + app.run("sources.favourite", json!({"kind": "file", "address": "/b.csv"})).unwrap(); + assert_eq!(stored_favorites(&store), ["/a.csv", "/b.csv"]); +} + /// Saved connections from a newer RustGIS (#1405): a preference of a newer version is said, isn't /// used and stays byte for byte through other changes to the preferences, recording a recent /// source among them; rows and fields this version can't read survive a connection made here. From 2640ac98e56ff821de0c4b0f8eda1830ec5fd1c6 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:32:02 -0600 Subject: [PATCH 04/27] fix(engine): a data sources save keeps this window's login bindings, and a source new here keeps its own details (#1962) --- crates/engine/src/sources.rs | 72 +++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index de7b3d2836..b81b56b004 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -496,6 +496,18 @@ impl Sources { } } next.kept.fields.retain(|_, f| !f.is_empty()); + // A source this session lists keeps its address as this session has it: reading what is + // stored drops login bindings (another process's are never authority), but this session's + // own stay with its sources whether or not it changed them since. + for list in LISTS { + let mine = self.list(list); + let Ok(now) = next.list_mut(list) else { continue }; + for source in now.iter_mut() { + if let Some(own) = mine.iter().find(|m| same(m, source)) { + source.address.clone_from(&own.address); + } + } + } next.recheck_fields(); // Stored as they are now: nothing is this session's own change any more. next.touched.clear(); @@ -630,7 +642,9 @@ impl Sources { pub fn note(&mut self, s: Source) { let Ok(s) = clean(s) else { return }; // Only details this session changed from what it had drop the kept ones (a new name or - // place keeps them); a source new here takes the stored row's when one exists by then. + // place keeps them). A source new here brings details of its own, which win over a + // stored row's when one exists by then. + let new = !self.recent.iter().any(|r| same(r, &s)); let changed = self.recent.iter().any(|r| same(r, &s) && r.extra != s.extra); self.recent.retain(|r| !same(r, &s)); @@ -640,6 +654,8 @@ impl Sources { // Noted with other details, as in [`Sources::keep`]. if changed { self.kept.extra.remove(&("recent", id.0.clone(), id.1.clone())); + } + if changed || new { self.details_changed.insert(("recent", id.0.clone(), id.1.clone())); } self.adopt("recent", &id); @@ -671,9 +687,9 @@ impl Sources { if l.len() >= MAX_KEPT { return Err(format!("up to {MAX_KEPT} sources in {list}")); } - // New here: no details of its own changed (a stored row's, if one exists by the save, win). + // New here: its details are its own, and win over a stored row's at the save. l.push(s.clone()); - false + true }; let id = identity(&s.kind, &s.address); // Replaced with other details, a source's kept details from a newer RustGIS were about @@ -1849,8 +1865,8 @@ MIIE let file = |address: &str| Source { kind: "file".into(), address: address.into(), ..Source::default() }; let favorites = |s: &Sources| s.favourites.iter().map(|f| f.address.clone()).collect::>(); - // A source new to this session that another window stored since, with details a newer - // RustGIS wrote: the stored row's details win; this session didn't change them. + // A source new to this session that another window stored since, with other details: this + // session's details win, as it added them itself. let mut s = Sources::from_json(&json!({"favourites": []}).to_string()); s.keep( "favourites", @@ -1861,7 +1877,25 @@ MIIE .to_string(); s.rebase(Some(&theirs), None).unwrap(); let written: Value = serde_json::from_str(&s.to_json()).unwrap(); - assert_eq!(written["favourites"][0]["extra"], json!({"type": "wmts", "tileSize": 512}), "{written}"); + assert_eq!(written["favourites"][0]["extra"], json!({"type": "wms"}), "{written}"); + // Window B stored layer roads; window A newly adds the same address with rivers: rivers. + // A source A already had and didn't change takes B's details. + let wms = |layer: &str| Source { + kind: "service".into(), + name: "S".into(), + address: "https://h/wms".into(), + extra: json!({"type": "wms", "layer": layer}), + }; + let theirs = json!({"favourites": [wms("roads")], "recent": [wms("roads")]}).to_string(); + let mut a = Sources::from_json(&json!({}).to_string()); + a.keep("favourites", wms("rivers")).unwrap(); + a.note(wms("rivers")); + a.rebase(Some(&theirs), None).unwrap(); + assert_eq!((a.favourites[0].extra["layer"].clone(), a.recent[0].extra["layer"].clone()), (json!("rivers"), json!("rivers"))); + let mut a = Sources::from_json(&json!({"favourites": [wms("lakes")]}).to_string()); + a.keep("favourites", file("/other.csv")).unwrap(); + a.rebase(Some(&theirs), None).unwrap(); + assert_eq!(a.favourites.iter().find(|f| f.kind == "service").map(|f| f.extra["layer"].clone()), Some(json!("roads"))); // This session's additions keep their place: before what it had, first; after, right // after it (past what another window added there). @@ -1893,6 +1927,32 @@ MIIE assert_eq!(s.to_json().matches("/z.csv").count(), 1); } + /// A source this session lists keeps its login binding through a save that lays its changes + /// over what another window stored, though it didn't change that source; without one, what is + /// stored is read as it was (#1962). + #[test] + fn a_saved_rebase_keeps_this_sessions_login_bindings() { + let bound = rustgis_data::s3_address::bind("0123456789abcdef", "https://s3.example.org", "s3://data/a.fgb").unwrap(); + let mut s = Sources::from_json("{}"); + s.note(Source { kind: "url".into(), name: "B".into(), address: bound.clone(), ..Source::default() }); + assert_eq!(s.recent[0].address, bound); + s.rebase(None, None).unwrap(); + let written = s.to_json(); + // An unrelated change here, and another window's change stored since. + s.keep("favourites", Source { kind: "file".into(), address: "/a.csv".into(), ..Source::default() }).unwrap(); + let mut theirs: Value = serde_json::from_str(&written).unwrap(); + theirs["saved"] = json!([{"kind": "file", "name": "", "address": "/theirs.csv"}]); + s.rebase(Some(&theirs.to_string()), Some(&written)).unwrap(); + assert_eq!(s.recent[0].address, bound); + assert_eq!(s.saved.len(), 1); + // A source this session doesn't list is read as stored, without a binding. + let stored = json!({"recent": [{"kind": "url", "name": "B", "address": bound}]}).to_string(); + let mut other = Sources::from_json("{}"); + other.keep("favourites", Source { kind: "file".into(), address: "/b.csv".into(), ..Source::default() }).unwrap(); + other.rebase(Some(&stored), None).unwrap(); + assert!(rustgis_data::s3_address::parse(&other.recent[0].address).unwrap().unwrap().binding.is_empty()); + } + /// Kept details from a newer RustGIS rechecked beside details changed since: only the entries /// that now read as a secret go (and are counted), the others stay. #[test] From a725fa07d40d88adb4c7a7dd400713d82a9b6758 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:35:24 -0600 Subject: [PATCH 05/27] fix(engine): a setting that fails to save stays to save, only objects and lists count as newer, and refusals can be said again (#1962) --- crates/engine/src/prefs.rs | 103 +++++++++++++++++++++++++++++++++---- 1 file changed, 94 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index fc1fb274a8..6f1d9e99e2 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -75,6 +75,10 @@ fn write_in(path: &Path, key: &str, value: &str) -> Result { Ok(Updated::Busy) => { pending.insert(id, value.to_string()); } + // Saved: a refusal of the key said before is over, and is said again if one comes back. + Ok(Updated::Saved(_)) => { + SAID_NEWER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + } // What is stored is a newer RustGIS's: never written over, and not tried again this // session (a later write of the key tries once more). Ok(Updated::Newer) => { @@ -95,6 +99,9 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); +/// Values left to save whose last retry failed, said once until one is saved. +static FAILED: Mutex> = Mutex::new(std::collections::BTreeSet::new()); + /// Keys whose refusal ([`newer_notice`]) has been said, so each is said once a session. static SAID_NEWER: Mutex> = Mutex::new(std::collections::BTreeSet::new()); @@ -106,6 +113,11 @@ pub fn pending(key: &str) -> Option { pending_in(&dir.join(FILE), key) } +/// Whether any value is left to save ([`write`] found another copy saving). +pub fn has_pending() -> bool { + !PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).is_empty() +} + fn pending_in(path: &Path, key: &str) -> Option { let id = (path.to_path_buf(), key.to_string()); let pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&id).cloned(); @@ -157,7 +169,10 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec, wait: std::time::Duration) -> (Vec said.push(done.map(|d| match d { - Updated::Saved(set_aside) => set_aside, - _ => None, - })), + // A failure is said once while the value stays left, not at each retry. + Err(error) => { + if FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(id) { + said.push(Err(error)); + } + } + Ok(done) => { + FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + if matches!(done, Updated::Saved(_)) { + SAID_NEWER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + } + said.push(Ok(match done { + Updated::Saved(set_aside) => set_aside, + _ => None, + })); + } } } } @@ -277,7 +304,11 @@ fn lock(path: &Path) -> Result { Ok(()) => Ok(Locked::Held(Lock(file))), Err(std::fs::TryLockError::WouldBlock) => Ok(Locked::Busy), Err(std::fs::TryLockError::Error(error)) => { - log::warn!("preferences saved without a lock: couldn't lock {}: {error}", lock_path.display()); + // Said once a session: every save would say it again. + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + log::warn!("preferences saved without a lock: couldn't lock {}: {error}", lock_path.display()); + } Ok(Locked::Unlockable) } } @@ -334,11 +365,12 @@ fn write_with( Err(error) if error.kind() == std::io::ErrorKind::NotFound => (Map::new(), None), Err(error) => return Err(format!("could not read preferences: {error}")), }; - // A newer RustGIS's setting this version can't read (not text) is never written over. + // A newer RustGIS's setting this version can't read (an object or a list) is never written + // over. A null, true or false, or a number was never a newer form: written over, as before. let stored = match map.get(key) { Some(Value::String(text)) => Some(text.as_str()), - Some(_) => return Ok(Updated::Newer), - None => None, + Some(Value::Object(_) | Value::Array(_)) => return Ok(Updated::Newer), + _ => None, }; let Some(value) = value(stored) else { return Ok(Updated::Unchanged) }; let set_aside = match malformed { @@ -659,11 +691,64 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// Only an object or a list stored under a key is a newer RustGIS's setting: a null, a flag + /// or a number is written over. A key saved again may be said again when refused later. A + /// value left to save that fails to write stays left, to try again (#1962). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn newer_settings_are_objects_or_lists_and_failed_retries_stay_left() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-newer-kinds-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + std::fs::write(&path, r#"{"flag":true,"n":5,"z":null,"o":{"v":2},"a":[1]}"#).unwrap(); + for key in ["flag", "n", "z"] { + assert_eq!(write_in(&path, key, "text").unwrap(), Updated::Saved(None), "{key}"); + } + for key in ["o", "a"] { + assert_eq!(write_in(&path, key, "text").unwrap(), Updated::Newer, "{key}"); + } + // Refused and said; saved once the stored value is text again; refused later, said again. + assert!(newer_notice_once_in(&path, "o").is_some()); + assert_eq!(newer_notice_once_in(&path, "o"), None); + let mut map = read_at(&path).unwrap(); + map.insert("o".into(), Value::String("old".into())); + std::fs::write(&path, serde_json::to_vec(&map).unwrap()).unwrap(); + assert_eq!(write_in(&path, "o", "text").unwrap(), Updated::Saved(None)); + map.insert("o".into(), serde_json::json!({"v": 3})); + std::fs::write(&path, serde_json::to_vec(&map).unwrap()).unwrap(); + assert_eq!(write_in(&path, "o", "again").unwrap(), Updated::Newer); + assert!(newer_notice_once_in(&path, "o").is_some(), "said again after a save of the key"); + + // Left to save while another copy saves; then the file can't be read (a folder in its + // place): the retry fails, and the value stays left; once it can be, it is written. + let held = lock(&path).unwrap(); + assert_eq!(write_in(&path, "theme", "dark").unwrap(), Updated::Busy); + drop(held); + let kept = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(said.iter().any(Result::is_err) && left, "{said:?}"); + assert_eq!(pending_in(&path, "theme").as_deref(), Some("dark")); + // Failing again: still left, and not said again. + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(said.is_empty() && left, "{said:?}"); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, kept).unwrap(); + let (said, left) = retry_pending_in(Some(&path), std::time::Duration::ZERO); + assert!(said.iter().all(Result::is_ok) && !left, "{said:?}"); + assert_eq!(read_at(&path).unwrap().get("theme").and_then(Value::as_str), Some("dark")); + forget_values(&path); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Drops what this test folder left in the session-wide sets. fn forget_values(path: &Path) { PENDING.lock().unwrap().retain(|(p, _), _| p != path); REFUSED.lock().unwrap().retain(|(p, _), _| p != path); SAID_NEWER.lock().unwrap().retain(|(p, _)| p != path); + FAILED.lock().unwrap().retain(|(p, _)| p != path); } /// At exit, a value left to save that turns out refused (a newer RustGIS stored the key From 4996e56f39fe9cc017f989ab7ac6acdeff252404 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:35:25 -0600 Subject: [PATCH 06/27] fix(desktop): a setting left to save while another copy saves is retried without waiting for a repaint (#1962) --- apps/rustgis/src/main.rs | 5 +++++ crates/ui-egui/src/lib.rs | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index e1c84218b1..3044b5e94b 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -130,6 +130,11 @@ mod prefs { if !notices().is_empty() { ctx.request_repaint(); } + // A setting left to save while another copy saves its own is tried again on a frame a + // quarter second on, which an idle window wouldn't otherwise draw. + if rustgis_engine::prefs::has_pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } } /// A notice's text in the current language. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 58e8ea3e87..0c5cfd1a95 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6524,12 +6524,13 @@ impl RustGisApp { if let Some(retry) = sourcespane::retry_in(self) { ctx.request_repaint_after(retry); } - if let Some(retry) = sourcespane::retry_prefs(self) { - ctx.request_repaint_after(retry); - } sourcespane::save_connections(self); self.save_raster_defaults(); self.save_layout_favourite(); + // After the frame's other saves, so one that found another copy saving is tried again. + if let Some(retry) = sourcespane::retry_prefs(self) { + ctx.request_repaint_after(retry); + } cswui::poll(self); stacui::poll(self, ctx); s3ui::poll(self, ctx); From 2d5f1f29a591c3bcf51b6e35fb974cd5439b8e7c Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:39:04 -0600 Subject: [PATCH 07/27] fix(engine): reading stored data sources drops kept details of a source listed here with other details (#1962) --- crates/engine/src/sources.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index b81b56b004..3fc1dc70fb 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -348,7 +348,12 @@ impl Sources { let Ok(incoming) = stored.list_mut(list).map(std::mem::take) else { continue }; let Ok(now) = self.list_mut(list) else { continue }; for source in incoming { - if now.iter().any(|n| same(n, &source)) { + if let Some(mine) = now.iter().find(|n| same(n, &source)) { + // This session's own details win; kept details from a newer RustGIS were about + // the stored ones, so they go when this session's differ (as keep and note do). + if mine.extra != source.extra { + stored.kept.extra.remove(&key_of(list, &source)); + } continue; } if now.len() < cap { @@ -1927,6 +1932,27 @@ MIIE assert_eq!(s.to_json().matches("/z.csv").count(), 1); } + /// Reading what is stored over a session that already lists a source with other details: the + /// details a newer RustGIS kept beside the stored ones go, as they were about those (no WMS + /// layers on a WMTS source); with the same details they stay (#1962). + #[test] + fn a_merge_drops_kept_details_of_a_source_listed_with_other_details() { + let stored = json!({"favourites": [{"kind": "service", "name": "S", "address": "https://h/wms", "extra": {"type": "wms", "layers": ["a", "b"]}}]}) + .to_string(); + let source = + |kind: &str| Source { kind: "service".into(), name: "S".into(), address: "https://h/wms".into(), extra: json!({"type": kind}) }; + let mut s = Sources::default(); + s.keep("favourites", source("wmts")).unwrap(); + s.merge(Sources::from_json(&stored)); + let written: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(written["favourites"][0]["extra"], json!({"type": "wmts"}), "{written}"); + let mut s = Sources::default(); + s.keep("favourites", source("wms")).unwrap(); + s.merge(Sources::from_json(&stored)); + let written: Value = serde_json::from_str(&s.to_json()).unwrap(); + assert_eq!(written["favourites"][0]["extra"], json!({"type": "wms", "layers": ["a", "b"]}), "{written}"); + } + /// A source this session lists keeps its login binding through a save that lays its changes /// over what another window stored, though it didn't change that source; without one, what is /// stored is read as it was (#1962). From 752bce69d5aa005883cc7108888ff7d365cbd64f Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:39:05 -0600 Subject: [PATCH 08/27] fix(engine): a lock file that can't be opened no longer stops saving, a direct write clears a failed retry, and retries say why values are left (#1962) --- crates/engine/src/prefs.rs | 98 ++++++++++++++++++++++++++++++++------ 1 file changed, 83 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 6f1d9e99e2..756cb68f91 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -70,6 +70,10 @@ fn write_in(path: &Path, key: &str, value: &str) -> Result { let mut refused = REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); pending.remove(&id); refused.remove(&id); + // Written, refused or failing here, it is no longer a retry that failed. + if done != Ok(Updated::Busy) { + FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + } match done { // Left to save: tried again once the other copy lets go of the lock. Ok(Updated::Busy) => { @@ -138,8 +142,25 @@ fn newer_notice_once_in(path: &Path, key: &str) -> Option { /// Writes again what [`write`] left to save. `wait` bounds how long it waits for another copy /// to let go of the lock: zero on the UI thread (it never waits there), a second or two at exit. /// Returns what each write tried came to (to report), and whether any is still left. -pub fn retry_pending(wait: std::time::Duration) -> (Vec, String>>, bool) { - retry_pending_in(None, wait) +pub fn retry_pending(wait: std::time::Duration) -> (Vec, String>>, Option) { + let (said, left) = retry_pending_in(None, wait); + (said, left.then(left_why)) +} + +/// Why values are still left to save after [`retry_pending`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Left { + /// Another copy of RustGIS kept its preferences busy (for one of them at least). + Busy, + /// Writing them failed. + Failed, +} + +/// Why what is left to save is left: busy unless every value left failed its last retry. +fn left_why() -> Left { + let pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let failed = FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if !pending.is_empty() && pending.keys().all(|id| failed.contains(id)) { Left::Failed } else { Left::Busy } } /// [`retry_pending`], of the file at `only` alone when given (a test folder in tests). @@ -297,20 +318,25 @@ fn lock(path: &Path) -> Result { let dir = path.parent().ok_or("the settings folder isn't available")?; // Never through a link (the open itself refuses one on Unix), only a regular file, its // owner's alone. - let file = std::fs::create_dir_all(dir) - .and_then(|_| rustgis_data::io::open_lock_file(&lock_path, true, 0o600)) - .map_err(|error| format!("could not save preferences: couldn't open {}: {error}", lock_path.display()))?; + // Saved without the lock where it can't be had (some network folders, a lock file that isn't + // a regular file of this user's or can't be opened), as before the lock: logged once a + // session, as every save would log it again. + let unlockable = |why: String| { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + log::warn!("preferences saved without a lock: {why}"); + } + Ok(Locked::Unlockable) + }; + std::fs::create_dir_all(dir).map_err(|error| format!("could not save preferences: couldn't create {}: {error}", dir.display()))?; + let file = match rustgis_data::io::open_lock_file(&lock_path, true, 0o600) { + Ok(file) => file, + Err(error) => return unlockable(format!("couldn't open {}: {error}", lock_path.display())), + }; match file.try_lock() { Ok(()) => Ok(Locked::Held(Lock(file))), Err(std::fs::TryLockError::WouldBlock) => Ok(Locked::Busy), - Err(std::fs::TryLockError::Error(error)) => { - // Said once a session: every save would say it again. - static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { - log::warn!("preferences saved without a lock: couldn't lock {}: {error}", lock_path.display()); - } - Ok(Locked::Unlockable) - } + Err(std::fs::TryLockError::Error(error)) => unlockable(format!("couldn't lock {}: {error}", lock_path.display())), } } @@ -743,6 +769,47 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// A value whose retry failed, then written directly, is no longer counted as failed: failing + /// again later is said again. A lock file that can't be opened (a folder in its place) doesn't + /// stop saving: written without the lock, as where locking isn't possible (#1962). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_direct_write_clears_a_failed_retry_and_an_unopenable_lock_still_saves() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-failed-then-written-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + std::fs::write(&path, "{}").unwrap(); + let fail_once = |path: &Path| { + let held = lock(path).unwrap(); + assert_eq!(write_in(path, "theme", "dark").unwrap(), Updated::Busy); + drop(held); + let kept = std::fs::read(path).unwrap(); + std::fs::remove_file(path).unwrap(); + std::fs::create_dir(path).unwrap(); + let (said, left) = retry_pending_in(Some(path), std::time::Duration::ZERO); + std::fs::remove_dir(path).unwrap(); + std::fs::write(path, kept).unwrap(); + (said, left) + }; + let (said, left) = fail_once(&path); + assert!(said.iter().any(Result::is_err) && left, "{said:?}"); + assert_eq!(write_in(&path, "theme", "light").unwrap(), Updated::Saved(None)); + assert!(!FAILED.lock().unwrap().contains(&(path.clone(), "theme".to_string()))); + let (said, _) = fail_once(&path); + assert!(said.iter().any(Result::is_err), "said again after a direct write: {said:?}"); + forget_values(&path); + + // The lock file's place taken by a folder: the save goes on without the lock. + let lock_path = path.with_extension("json.lock"); + let _ = std::fs::remove_file(&lock_path); + std::fs::create_dir(&lock_path).unwrap(); + assert_eq!(write_in(&path, "theme", "blue").unwrap(), Updated::Saved(None)); + assert_eq!(read_at(&path).unwrap().get("theme").and_then(Value::as_str), Some("blue")); + forget_values(&path); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Drops what this test folder left in the session-wide sets. fn forget_values(path: &Path) { PENDING.lock().unwrap().retain(|(p, _), _| p != path); @@ -803,13 +870,14 @@ mod tests { // A value given back as none leaves the preference as it was. assert_eq!(update_file(&path, "k", |_| None).unwrap(), Updated::Unchanged); assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); - // A link in the lock's place is refused, never followed. + // A link in the lock's place is never followed: the preferences are saved without the lock, + // as where locking isn't possible. #[cfg(unix)] { let lock_path = path.with_extension("json.lock"); std::fs::remove_file(&lock_path).unwrap(); std::os::unix::fs::symlink(dir.join("elsewhere"), &lock_path).unwrap(); - assert!(lock(&path).is_err()); + assert!(matches!(lock(&path), Ok(Locked::Unlockable))); assert!(!dir.join("elsewhere").exists()); } std::fs::remove_dir_all(dir).unwrap(); From 39b628190c11123e0a577c0d272bc85bae9ebc86 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:39:07 -0600 Subject: [PATCH 09/27] fix(desktop): settings retried with their own backoff, and what isn't saved at exit says why (#1962) --- apps/rustgis/src/main.rs | 12 ++++------ crates/ui-egui/src/lib.rs | 11 ++++++++- crates/ui-egui/src/sourcespane.rs | 39 ++++++++++++++++++------------- crates/ui-egui/tests/smoke.rs | 38 +++++++++++++++++++++++++++++- 4 files changed, 75 insertions(+), 25 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 3044b5e94b..f8c5b9b19e 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -113,10 +113,13 @@ mod prefs { /// Writes again the settings left to save while another copy of RustGIS saved its own, /// waiting up to `wait` for it (none on the UI thread); what they came to is kept as /// [`saved`] keeps it. Whether any is still left. - pub fn retry_saves(wait: std::time::Duration) -> bool { + pub fn retry_saves(wait: std::time::Duration) -> Option { let (results, left) = rustgis_engine::prefs::retry_pending(wait); results.into_iter().for_each(saved); - left + left.map(|why| match why { + rustgis_engine::prefs::Left::Busy => rustgis_ui_egui::PrefsLeft::Busy, + rustgis_engine::prefs::Left::Failed => rustgis_ui_egui::PrefsLeft::Failed, + }) } /// The problems since the last call, oldest first. @@ -130,11 +133,6 @@ mod prefs { if !notices().is_empty() { ctx.request_repaint(); } - // A setting left to save while another copy saves its own is tried again on a frame a - // quarter second on, which an idle window wouldn't otherwise draw. - if rustgis_engine::prefs::has_pending() { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); - } } /// A notice's text in the current language. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0c5cfd1a95..aab008bea7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -380,6 +380,15 @@ pub fn parse_extent(text: &str) -> Option<[f64; 4]> { Some([e.min_x, e.min_y, e.max_x, e.max_y]) } +/// Why settings are still left to save after [`Services::retry_prefs`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PrefsLeft { + /// Another copy of the app kept its preferences busy. + Busy, + /// Writing them failed (the hook said why). + Failed, +} + /// What a [`Services::update_pref`] came to. #[derive(Clone, Copy, Debug, PartialEq)] pub enum PrefUpdate { @@ -429,7 +438,7 @@ pub struct Services { /// preferences (the desktop's), waiting up to the given time for it (none during the run, /// a little as the app closes); whether any is still left. `None` where nothing is ever /// left (the browser). - pub retry_prefs: Option bool>>, + pub retry_prefs: Option Option>>, /// The system's secret store (see `docs/architecture.md` › Secrets): the desktop's keychain. /// `None` in the browser and on the command line, where secrets last for the session only. pub secrets: Option>, diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 2c7078b697..c356122cf0 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -198,7 +198,8 @@ fn attempt(app: &mut RustGisApp) -> Option { (crate::PrefUpdate::Saved, Some((sources, text))) => { state.retry.done(); (state.busy_since, state.refusal_said, state.last_written, state.refused_at) = (None, false, Some(text), None); - state.said.retain(|(kind, _)| *kind != "busy"); + // Saved: a later busy spell or refusal is said again. + state.said.retain(|(kind, _)| *kind != "busy" && *kind != "newer-format"); app.session.sources = sources; app.ui.sources_saved = app.session.sources.generation; say_unread(app); @@ -247,12 +248,17 @@ pub fn save_prefs_at_exit(app: &mut RustGisApp, wait: std::time::Duration) { let deadline = web_time::Instant::now() + wait; save_sources_at_exit(app, deadline); if let Some(retry) = &app.services.retry_prefs - && retry(deadline.saturating_duration_since(web_time::Instant::now())) + && let Some(left) = retry(deadline.saturating_duration_since(web_time::Instant::now())) { - log::warn!("some settings changed in this session weren't saved: another copy of RustGIS kept its preferences busy"); - app.session.warn(crate::tl!( - "Some settings changed in this session weren't saved as RustGIS closed: another copy of RustGIS kept its preferences busy." - )); + let (why, said) = match left { + crate::PrefsLeft::Busy => { + ("another copy of RustGIS kept its preferences busy", crate::tl!("another copy of RustGIS kept its preferences busy")) + } + crate::PrefsLeft::Failed => ("they couldn't be written", crate::tl!("they couldn't be written")), + }; + log::warn!("some settings changed in this session weren't saved: {why}"); + app.session + .warn(crate::i18n::fmt("Some settings changed in this session weren't saved as RustGIS closed: {why}.", &[("why", said)])); } } @@ -276,6 +282,10 @@ fn save_sources_at_exit(app: &mut RustGisApp, deadline: web_time::Instant) { "a newer RustGIS saved them in a form this version can't read", crate::tl!("a newer RustGIS saved them in a form this version can't read"), ), + // Never written over what is stored while it can't be read. + Some(crate::PrefUpdate::Unchanged) => { + ("the stored sources couldn't be read", crate::tl!("the stored sources couldn't be read")) + } _ => ("they couldn't be written", crate::tl!("they couldn't be written")), }; log::warn!("the data sources changed in this session weren't saved: {why}"); @@ -299,27 +309,24 @@ pub fn retry_in(app: &RustGisApp) -> Option { app.ui.sources.retry.wait(web_time::Instant::now()) } -/// How often frames look for other settings left to save while none is known to be. -const PREFS_IDLE_CHECK: std::time::Duration = std::time::Duration::from_secs(1); - /// Saves again the app's other preferences left to save while another copy saved its own -/// (`Services::retry_prefs`), when due: with nothing left, looked for once a second, not every -/// frame; with something left, tried after a quarter second, doubling up to five seconds, so a -/// long-held lock doesn't cost every frame either. How soon it is tried again, if anything is -/// left (none: no frame is asked for). +/// (`Services::retry_prefs`): with nothing left, looked for each frame (which reads no file and +/// takes no lock), so one a save this frame left is tried at once; with something left, tried +/// after a quarter second, doubling up to five seconds, so a long-held lock or a failing write +/// doesn't cost every frame, nor wake an idle window more often. How soon it is tried again, if +/// anything is left (none: no frame is asked for). pub fn retry_prefs(app: &mut RustGisApp) -> Option { let retry = app.services.retry_prefs.as_ref()?; let now = web_time::Instant::now(); let state = &mut app.ui.sources.prefs_retry; if !state.due(now) { - return (state.failures > 0).then(|| state.wait(now)).flatten(); + return state.wait(now); } - if retry(std::time::Duration::ZERO) { + if retry(std::time::Duration::ZERO).is_some() { state.failed(now, std::time::Duration::from_millis(250), std::time::Duration::from_secs(5)); state.wait(now) } else { state.done(); - state.after(now, PREFS_IDLE_CHECK); None } } diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index ad418af43f..d067c2849f 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -1692,6 +1692,42 @@ fn data_sources_left_to_save_are_saved_at_exit() { assert!(!stored_favorites(&store).contains(&"/late.csv".to_string())); } +/// A refusal said, then a save that happens, then a refusal again: said again. At exit, data +/// sources that weren't saved because the stored ones can't be read say so, and settings left +/// because writing them failed say that, not that another copy was busy. +#[test] +fn refusals_after_a_save_and_why_at_exit_are_said() { + use rustgis_ui_egui::PrefUpdate; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), json!({"favourites": []}).to_string())]))); + let outcomes = PrefOutcomes::default(); + let mut app = window_over(&store, &outcomes); + let refusals = + |app: &RustGisApp| app.session.notices_since(0).iter().filter(|n| n.text.contains("a newer RustGIS saved them in a form")).count(); + outcomes.lock().unwrap().push_back(PrefUpdate::Refused); + app.run("sources.favourite", json!({"kind": "file", "address": "/one.csv"})).unwrap(); + assert_eq!(refusals(&app), 1); + app.run("sources.favourite", json!({"kind": "file", "address": "/two.csv"})).unwrap(); + assert!(stored_favorites(&store).contains(&"/two.csv".to_string())); + outcomes.lock().unwrap().push_back(PrefUpdate::Refused); + app.run("sources.favourite", json!({"kind": "file", "address": "/three.csv"})).unwrap(); + assert_eq!(refusals(&app), 2, "said again after a save"); + + let bad = "[\"not\", \"an object\"]".to_string(); + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), bad)]))); + let mut app = window_over(&store, &PrefOutcomes::default()); + app.services.retry_prefs = Some(Box::new(|_| Some(rustgis_ui_egui::PrefsLeft::Failed))); + app.run("sources.favourite", json!({"kind": "file", "address": "/x.csv"})).unwrap(); + app.save_prefs_at_exit(std::time::Duration::from_millis(100)); + let said: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("weren't saved as RustGIS closed: the stored sources couldn't be read")), "{said:?}"); + assert!( + said.iter().any(|t| t.contains("Some settings changed in this session weren't saved as RustGIS closed: they couldn't be written")), + "{said:?}" + ); +} + /// The data sources and the other settings share one deadline at exit: however long the data /// sources wait for another copy, the other settings get only what is left of it, and what /// isn't saved of either is said. @@ -1707,7 +1743,7 @@ fn settings_left_to_save_share_one_deadline_at_exit() { let log = given.clone(); app.services.retry_prefs = Some(Box::new(move |wait| { log.lock().unwrap().push(wait); - true + Some(rustgis_ui_egui::PrefsLeft::Busy) })); outcomes.lock().unwrap().extend(std::iter::repeat_n(PrefUpdate::Busy, 1000)); app.run("sources.favourite", json!({"kind": "file", "address": "/x.csv"})).unwrap(); From 1032ea2255cfa2809e745250bc86df0acd29d0b8 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:59:24 -0600 Subject: [PATCH 10/27] fix(ui): a setting left to save during a frame's interface is tried again after it (#1962) --- crates/ui-egui/src/lib.rs | 7 ++++++ crates/ui-egui/tests/smoke.rs | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 348ac7add9..f0a55d5cf1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7934,6 +7934,13 @@ impl RustGisApp { { ctx.request_repaint(); } + // A setting a save during `ui` left to save (another copy saving its preferences) is tried + // again on a later frame, which an idle window wouldn't otherwise draw: `logic` looked + // before this frame's panes saved. The same backoff as there, so a value that keeps failing + // doesn't wake the window more often. + if let Some(retry) = sourcespane::retry_prefs(self) { + ctx.request_repaint_after(retry); + } // egui times clicks by the frame they arrive in: at a slow frame rate the two clicks of a // double-click land too far apart for its default delay (#1321). It reads the delay when // the next frame begins, before that frame's `logic`, so it's set here, from this frame's diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index f3612d5463..ddc17b4ec6 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -2838,6 +2838,51 @@ fn refusals_after_a_save_and_why_at_exit_are_said() { ); } +/// A setting left to save by a save during `ui` (a pane's toggle, while another copy saves) is +/// tried again in that frame's `ui`, not only at the next frame's `logic`, which an idle window +/// might never draw; then not again until its backoff has passed. +#[test] +fn a_setting_left_to_save_during_ui_is_retried_after_it() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + let store: PrefStore = Arc::new(Mutex::new(std::collections::HashMap::new())); + let mut app = window_over(&store, &PrefOutcomes::default()); + let pending = Arc::new(AtomicBool::new(false)); + let tried = Arc::new(AtomicUsize::new(0)); + let (left, count) = (pending.clone(), tried.clone()); + app.services.retry_prefs = Some(Box::new(move |_| { + if !left.load(Ordering::SeqCst) { + return None; + } + count.fetch_add(1, Ordering::SeqCst); + Some(rustgis_ui_egui::PrefsLeft::Busy) + })); + let during_ui = Arc::new(AtomicBool::new(false)); + let during = during_ui.clone(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 860.0)).with_max_steps(64).build_ui_state( + move |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + // A pane's save while the window draws, after `logic`'s look. + if during.load(Ordering::SeqCst) { + pending.store(true, Ordering::SeqCst); + } + app.ui(ui); + }, + app, + ); + // The first frames only install fonts. + for _ in 0..3 { + h.step(); + } + assert_eq!(tried.load(Ordering::SeqCst), 0, "nothing left: nothing tried"); + during_ui.store(true, Ordering::SeqCst); + h.step(); + assert_eq!(tried.load(Ordering::SeqCst), 1, "left during ui: tried after it"); + h.step(); + assert_eq!(tried.load(Ordering::SeqCst), 1, "not again before its backoff"); +} + /// The data sources and the other settings share one deadline at exit: however long the data /// sources wait for another copy, the other settings get only what is left of it, and what /// isn't saved of either is said. From ce6ce972dc5dab8f576cdf1d0948cc66972cfa17 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:59:24 -0600 Subject: [PATCH 11/27] fix(mobile): settings left to save are tried once more as the app closes (#1962) --- apps/rustgis-mobile/src/shell.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index e6c9913e57..2051b3bbbf 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -652,8 +652,11 @@ fn use_picker( impl eframe::App for App

{ /// When the event loop exits, give the recovery writer a short chance to finish the latest /// edit. The next launch offers the last complete copy, if one exists. + /// Settings left to save are tried once more, as on the desktop, within a shorter wait: the + /// phone may end the app soon after. What still isn't saved is logged with why. fn on_exit(&mut self) { self.app.finish_recovery_copy(); + self.app.save_prefs_at_exit(std::time::Duration::from_millis(500)); } fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { From a86f8c0c63c1a4b903a124989a64fea914c9ede4 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:59:24 -0600 Subject: [PATCH 12/27] refactor(engine): time the retry at exit with web_time (#1962) --- crates/engine/src/prefs.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index aa507be3f6..b1d1e2f1f7 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -174,9 +174,7 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec, wait: std::time::Duration) -> (Vec Date: Sat, 28 Nov 2026 16:29:56 -0600 Subject: [PATCH 13/27] fix(ui): a data sources save doesn't count as the add that noted a source (#1962) --- crates/engine/src/sources.rs | 14 ++++++++ crates/ui-egui/src/connectiontree.rs | 50 ++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 8 ++--- crates/ui-egui/src/readjob.rs | 2 +- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index 20da484e83..985f414f52 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -45,6 +45,10 @@ pub struct Sources { /// Bumped on every change, so the app knows when to keep them. #[serde(skip)] pub generation: u64, + /// Of those, the bumps of [`Sources::rebase`]: a save laying this session's changes over + /// what is stored, which [`Sources::changes`] leaves out. + #[serde(skip)] + rebases: u64, /// What of the preference this version couldn't use, written back as it was. #[serde(skip)] kept: Kept, @@ -419,6 +423,7 @@ impl Sources { self.removed.clear(); self.details_changed.clear(); self.generation += 1; + self.rebases += 1; return Ok(()); }; let mut next = Sources::from_json(stored); @@ -534,10 +539,19 @@ impl Sources { next.removed.clear(); next.details_changed.clear(); next.generation = self.generation + 1; + next.rebases = self.rebases + 1; *self = next; Ok(()) } + /// Counts the changes this session made to the lists (a source noted, kept or forgotten), + /// leaving out saves ([`Sources::rebase`]), which also bump [`Sources::generation`]: a + /// caller asking whether a command noted a source compares two of these, so a save that + /// happens meanwhile doesn't count as one. + pub fn changes(&self) -> u64 { + self.generation.wrapping_sub(self.rebases) + } + /// Classifies the fields kept for each listed source again, against the source as it is now /// (a changed `extra` or address can make a field that passed at load a secret), and drops /// what is one, counted with the rest. Every change to a list that keeps fields ends here, so diff --git a/crates/ui-egui/src/connectiontree.rs b/crates/ui-egui/src/connectiontree.rs index fdbbaf3915..a08529e1e2 100644 --- a/crates/ui-egui/src/connectiontree.rs +++ b/crates/ui-egui/src/connectiontree.rs @@ -84,7 +84,7 @@ pub(crate) fn run_named(app: &mut RustGisApp, id: &str, params: Value, origin: O let name = params.get("name").or_else(|| params.get("layer")).and_then(Value::as_str).unwrap_or_default().to_string(); return crate::readjob::run_service(app, params, &name, origin); } - let before = app.session.sources.generation; + let before = app.session.sources.changes(); let r = app.run(id, params); if r.is_ok() { name_recent(app, before, origin); @@ -92,13 +92,13 @@ pub(crate) fn run_named(app: &mut RustGisApp, id: &str, params: Value, origin: O r } -/// Names the source the session noted since `before` (a [`Sources::generation`]) as Recent +/// Names the source the session noted since `before` (a [`Sources::changes`]) as Recent /// shows it, after the connection it came from. The kind, address and `extra` are the ones noted /// (cleaned and redacted), so reopening it targets the same dataset; a name is a snapshot, taken /// when added. Nothing noted (a failed add, one still on its way) leaves Recent as it was. pub(crate) fn name_recent(app: &mut RustGisApp, before: u64, origin: Option<&str>) { let Some(origin) = origin else { return }; - if app.session.sources.generation == before { + if app.session.sources.changes() == before { return; } let Some(mut added) = app.session.sources.recent.first().cloned() else { return }; @@ -754,6 +754,50 @@ mod tests { type Harness = egui_kittest::Harness<'static, RustGisApp>; + /// A data sources save left for later that succeeds while a connection's add runs isn't a + /// source that add noted: the older Recent entry keeps its name. + #[test] + fn a_save_meanwhile_does_not_rename_an_older_recent_source() { + use std::sync::{Arc, Mutex}; + let store: Arc>> = Arc::default(); + let busy = Arc::new(Mutex::new(true)); + let (stored, held) = (store.clone(), busy.clone()); + let services = crate::Services { + update_pref: Some(Box::new(move |_, value| { + if *held.lock().unwrap() { + return crate::PrefUpdate::Busy; + } + let mut stored = stored.lock().unwrap(); + match value(stored.as_deref()) { + Some(next) => { + *stored = Some(next); + crate::PrefUpdate::Saved + } + None => crate::PrefUpdate::Unchanged, + } + })), + ..Default::default() + }; + let mut app = RustGisApp::with_sample().with_services(services); + app.session.note_source(Source { kind: "file".into(), name: "old".into(), address: "/old.csv".into(), extra: Value::Null }); + // Another copy saving: left to save. + crate::sourcespane::save(&mut app); + assert!(store.lock().unwrap().is_none()); + *busy.lock().unwrap() = false; + std::thread::sleep(std::time::Duration::from_millis(300)); // test-wait: past the busy retry delay + let before = app.session.sources.changes(); + // The retry succeeds while the add runs, which notes nothing. + crate::sourcespane::save(&mut app); + assert!(store.lock().unwrap().is_some(), "the retry saved"); + name_recent(&mut app, before, Some("Conn")); + assert_eq!(app.session.sources.recent.first().map(|s| s.name.as_str()), Some("old")); + // An add that notes a source is named after its connection, as before. + let before = app.session.sources.changes(); + app.session.note_source(Source { kind: "file".into(), name: "new".into(), address: "/new.csv".into(), extra: Value::Null }); + name_recent(&mut app, before, Some("Conn")); + assert_eq!(app.session.sources.recent.first().map(|s| s.name.as_str()), Some("Conn")); + } + /// A geodatabase's rows have icons: a feature class its kind of geometry's, a table and a /// feature dataset theirs. Other rows keep none. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f0a55d5cf1..52ba6f3733 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6408,7 +6408,7 @@ impl RustGisApp { // command reads it. let window = cfg!(not(target_arch = "wasm32")) && p.get("bbox").is_some_and(|v| !v.is_null() && v.as_bool() != Some(false)); if !window && url.to_ascii_lowercase().split(['?', '#']).next().is_some_and(|u| u.ends_with(".pmtiles")) { - let before = self.session.sources.generation; + let before = self.session.sources.changes(); let result = if let Some(id) = claim { self.run_with_prepared("layer.addUrl", p.clone(), AppDispatch::InPlace(id)) } else { @@ -6630,7 +6630,7 @@ impl RustGisApp { if !rustgis_engine::data::source::is_remote_name(&url) { p["cog"] = json!(true); } - let before = self.session.sources.generation; + let before = self.session.sources.changes(); let pending = p.clone(); let added = if let Some(id) = claim { self.run_with_prepared("layer.addUrl", p, AppDispatch::InPlace(id)) @@ -7057,7 +7057,7 @@ impl RustGisApp { if zoom && self.ui.link_zoomed { p["zoom"] = json!(false); } - let before = self.session.sources.generation; + let before = self.session.sources.changes(); let pending = p.clone(); match self.run_with_prepared("layer.addDownload", p, AppDispatch::Download(id)) { Ok(r) => { @@ -7225,7 +7225,7 @@ impl RustGisApp { let mut p = resolve.params; p["tiles"] = json!(template); let title = p["name"].as_str().unwrap_or("").to_string(); - let before = self.session.sources.generation; + let before = self.session.sources.changes(); let r = self.run_with_prepared( "service.add", p, diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index bed6c31085..a1f9055804 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -691,7 +691,7 @@ fn complete_here(app: &mut RustGisApp, asked: Asked, p: Value, done: Result Date: Sat, 28 Nov 2026 16:29:57 -0600 Subject: [PATCH 14/27] fix(data): a lock file removed between finding it and opening it is created again (#1962) --- crates/data/src/io.rs | 54 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 82ae9c10c5..7aaded5388 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1502,6 +1502,16 @@ pub fn write_atomic_with>( /// `mode` on Unix, set through the open handle so the umask doesn't narrow it (`0o600` for one /// user's own, `0o666` for a lock accounts share); an existing one keeps its own. pub fn open_lock_file(path: &Path, create: bool, mode: u32) -> std::io::Result { + open_lock_file_with(path, create, mode, &mut || {}) +} + +/// How many times [`open_lock_file`] creates the file again when another process removes it +/// between finding it there and opening it. +const LOCK_FILE_TRIES: usize = 8; + +/// [`open_lock_file`], with `between` run after an existing file is found and before it is +/// opened (a test removes it there, as another process may). +fn open_lock_file_with(path: &Path, create: bool, mode: u32, between: &mut dyn FnMut()) -> std::io::Result { let refused = || std::io::Error::other(format!("{} isn't a regular file", path.display())); #[cfg(not(all(unix, not(target_arch = "wasm32"))))] let _ = mode; @@ -1519,10 +1529,21 @@ pub fn open_lock_file(path: &Path, create: bool, mode: u32) -> std::io::Result (file, true), - Some(Err(e)) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e), - _ => (open(false)?, false), + // Created here, else the one there: one removed in between (another process releasing or + // sweeping it) is created again, a bounded number of times. + let mut tries = 0; + let (file, created) = loop { + match create.then(|| open(true)) { + Some(Ok(file)) => break (file, true), + Some(Err(e)) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e), + _ => {} + } + between(); + match open(false) { + Ok(file) => break (file, false), + Err(e) if create && e.kind() == std::io::ErrorKind::NotFound && tries + 1 < LOCK_FILE_TRIES => tries += 1, + Err(e) => return Err(e), + } }; if !file.metadata()?.is_file() || std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_file()) { return Err(refused()); @@ -6406,6 +6427,31 @@ mod tests { use super::*; use std::io::Write; + /// A lock file another process removes between finding it there and opening it is created + /// again, not an error; without `create`, a missing one stays an error, and one there opens. + #[test] + fn a_lock_file_removed_meanwhile_is_created_again() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("x.lock"); + std::fs::write(&path, b"").unwrap(); + let mut removed = 0; + let file = open_lock_file_with(&path, true, 0o600, &mut || { + if removed == 0 { + std::fs::remove_file(&path).unwrap(); + } + removed += 1; + }); + assert!(file.is_ok_and(|f| f.metadata().is_ok_and(|m| m.is_file())), "created again"); + assert!(path.is_file()); + assert_eq!(removed, 1, "found there once, then made here"); + // Not to create: a missing one is an error, one there opens. + std::fs::remove_file(&path).unwrap(); + assert!(open_lock_file(&path, false, 0o600).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)); + std::fs::write(&path, b"").unwrap(); + assert!(open_lock_file(&path, false, 0o600).is_ok()); + assert!(open_lock_file(&path, true, 0o600).is_ok()); + } + /// A Shapefile's `.dbf` header holds the day it was written, which `dbase` takes from `time`'s /// clock: std's unless `time`'s `wasm-bindgen` feature is on, and std's clock panics on /// wasm32-unknown-unknown, so every Shapefile export stopped the web app with no message From 948b55125dd4503e3795d15b9cc8bdf7293c64c8 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:29:57 -0600 Subject: [PATCH 15/27] refactor(engine): drop the unused prefs::has_pending (#1962) --- crates/engine/src/prefs.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index b1d1e2f1f7..b98e15c010 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -117,11 +117,6 @@ pub fn pending(key: &str) -> Option { pending_in(&dir.join(FILE), key) } -/// Whether any value is left to save ([`write`] found another copy saving). -pub fn has_pending() -> bool { - !PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).is_empty() -} - fn pending_in(path: &Path, key: &str) -> Option { let id = (path.to_path_buf(), key.to_string()); let pending = PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(&id).cloned(); From 413847764047efedae7b0ec82c6c7ebbc074f897 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:07:52 -0600 Subject: [PATCH 16/27] fix(engine): reading the stored data sources in doesn't count as noting a source, and say how the lock file is retried (#1962) --- crates/data/src/io.rs | 8 +++++--- crates/engine/src/sources.rs | 12 +++++++----- crates/ui-egui/src/connectiontree.rs | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 7aaded5388..943046b3f5 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1500,13 +1500,15 @@ pub fn write_atomic_with>( /// can be swapped in between a check and the open) and only a regular file; elsewhere a link or /// other non-regular file is refused before and after the open. A file this call creates gets /// `mode` on Unix, set through the open handle so the umask doesn't narrow it (`0o600` for one -/// user's own, `0o666` for a lock accounts share); an existing one keeps its own. +/// user's own, `0o666` for a lock accounts share); an existing one keeps its own. With `create`, +/// one another process removes between this call finding it and opening it is created again, +/// with `mode`, up to eight tries in all. pub fn open_lock_file(path: &Path, create: bool, mode: u32) -> std::io::Result { open_lock_file_with(path, create, mode, &mut || {}) } -/// How many times [`open_lock_file`] creates the file again when another process removes it -/// between finding it there and opening it. +/// How many times in all [`open_lock_file`] tries to open the file when another process keeps +/// removing it between this call finding it there and opening it. const LOCK_FILE_TRIES: usize = 8; /// [`open_lock_file`], with `between` run after an existing file is found and before it is diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index 985f414f52..a440bd199a 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -45,8 +45,8 @@ pub struct Sources { /// Bumped on every change, so the app knows when to keep them. #[serde(skip)] pub generation: u64, - /// Of those, the bumps of [`Sources::rebase`]: a save laying this session's changes over - /// what is stored, which [`Sources::changes`] leaves out. + /// Of those, the bumps of reading the stored lists in ([`Sources::merge`]) and of saving + /// over them ([`Sources::rebase`]), which [`Sources::changes`] leaves out. #[serde(skip)] rebases: u64, /// What of the preference this version couldn't use, written back as it was. @@ -401,6 +401,7 @@ impl Sources { } self.recheck_fields(); self.generation += 1; + self.rebases += 1; } /// Lays this session's changes over the sources kept with the preferences as they are now, @@ -545,9 +546,10 @@ impl Sources { } /// Counts the changes this session made to the lists (a source noted, kept or forgotten), - /// leaving out saves ([`Sources::rebase`]), which also bump [`Sources::generation`]: a - /// caller asking whether a command noted a source compares two of these, so a save that - /// happens meanwhile doesn't count as one. + /// leaving out reading the stored lists in ([`Sources::merge`]) and saves + /// ([`Sources::rebase`]), which also bump [`Sources::generation`]: a caller asking whether a + /// command noted a source compares two of these, so a first read or a save that happens + /// meanwhile doesn't count as one. pub fn changes(&self) -> u64 { self.generation.wrapping_sub(self.rebases) } diff --git a/crates/ui-egui/src/connectiontree.rs b/crates/ui-egui/src/connectiontree.rs index a08529e1e2..ad0afa6960 100644 --- a/crates/ui-egui/src/connectiontree.rs +++ b/crates/ui-egui/src/connectiontree.rs @@ -754,6 +754,20 @@ mod tests { type Harness = egui_kittest::Harness<'static, RustGisApp>; + /// The first read of the stored data sources, while a connection's add runs, isn't a source + /// that add noted: the stored Recent entry keeps its name. + #[test] + fn a_first_read_meanwhile_does_not_rename_a_stored_recent_source() { + let stored = serde_json::json!({"recent": [{"kind": "file", "name": "Stored", "address": "/stored.csv"}]}).to_string(); + let services = crate::Services { load_pref: Some(Box::new(move |_| Some(stored.clone()))), ..Default::default() }; + let mut app = RustGisApp::with_sample().with_services(services); + let before = app.session.sources.changes(); + crate::sourcespane::load(&mut app); + assert_eq!(app.session.sources.recent.first().map(|s| s.name.as_str()), Some("Stored")); + name_recent(&mut app, before, Some("Conn")); + assert_eq!(app.session.sources.recent.first().map(|s| s.name.as_str()), Some("Stored")); + } + /// A data sources save left for later that succeeds while a connection's add runs isn't a /// source that add noted: the older Recent entry keeps its name. #[test] From 730ef9e4c9d34be3bed4856ffe0caa353f0b8b77 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:06:53 -0600 Subject: [PATCH 17/27] fix(ui): what a save's fresh read leaves out is said again, and a busy data sources save backs off (#1962) --- crates/ui-egui/src/sourcespane.rs | 65 ++++++++++++++++++++++++++----- crates/ui-egui/tests/smoke.rs | 41 +++++++++++++++++++ 2 files changed, 96 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index d391097412..6d0d746063 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -54,10 +54,6 @@ impl Retry { fn due(&self, now: web_time::Instant) -> bool { self.at.is_none_or(|at| now >= at) } - /// Tried again after `delay`, whatever failed before (another copy busy). - fn after(&mut self, now: web_time::Instant, delay: std::time::Duration) { - self.at = Some(now + delay); - } /// One more failure in a row: tried again after `first`, doubling each time up to `most`. fn failed(&mut self, now: web_time::Instant, first: std::time::Duration, most: std::time::Duration) { self.failures = self.failures.saturating_add(1); @@ -72,8 +68,9 @@ impl Retry { } } -/// How soon a save is tried again while another copy of the app saves its preferences. -const BUSY_RETRY: std::time::Duration = std::time::Duration::from_millis(250); +/// How soon a save is tried again while another copy of the app saves its preferences: after a +/// quarter second, doubling up to five seconds while it stays busy, as the other settings are. +const BUSY_RETRY: (std::time::Duration, std::time::Duration) = (std::time::Duration::from_millis(250), std::time::Duration::from_secs(5)); /// How long another copy may keep them busy before that is said. const BUSY_SAY: std::time::Duration = std::time::Duration::from_secs(10); /// A failed data sources save is tried again after a second, doubling up to a minute. @@ -176,9 +173,12 @@ pub fn save(app: &mut RustGisApp) { fn attempt(app: &mut RustGisApp) -> Option { let update = app.services.update_pref.as_ref()?; let now = web_time::Instant::now(); - let (mut next, mut unreadable) = (None, None); + let (mut next, mut unreadable, mut fresh) = (None, None, false); let (sources, last) = (&app.session.sources, app.ui.sources.last_written.as_deref()); let outcome = update(PREF, &mut |stored| { + // What is stored isn't what this session last wrote: read again, so what reading it + // leaves out is counted from it alone. + fresh = stored.filter(|s| !s.trim_start_matches('\u{feff}').trim().is_empty()).is_some_and(|s| Some(s) != last); let mut rebased = sources.clone(); match rebased.rebase(stored, last) { Ok(()) => { @@ -198,15 +198,18 @@ fn attempt(app: &mut RustGisApp) -> Option { (crate::PrefUpdate::Saved, Some((sources, text))) => { state.retry.done(); (state.busy_since, state.refusal_said, state.last_written, state.refused_at) = (None, false, Some(text), None); - // Saved: a later busy spell or refusal is said again. - state.said.retain(|(kind, _)| *kind != "busy" && *kind != "newer-format"); + // Saved: a later busy spell or refusal is said again. What the write left out of what + // it read (secrets, cut names, repeated rows) is gone from the store, so what a fresh + // read finds of them is new, and said whatever was said before. + let consumed = |kind: &str| fresh && matches!(kind, "secrets" | "cut" | "repeated"); + state.said.retain(|(kind, _)| *kind != "busy" && *kind != "newer-format" && !consumed(kind)); app.session.sources = sources; app.ui.sources_saved = app.session.sources.generation; say_unread(app); } (crate::PrefUpdate::Busy, _) => { let since = *state.busy_since.get_or_insert(now); - state.retry.after(now, BUSY_RETRY); + state.retry.failed(now, BUSY_RETRY.0, BUSY_RETRY.1); if now.duration_since(since) >= BUSY_SAY { let said = crate::tl!("The data sources aren't saved yet: another copy of RustGIS keeps its preferences busy. Trying again."); @@ -776,6 +779,48 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { #[cfg(test)] mod tests { use super::*; + + /// A data sources save that finds another copy saving is tried again after a quarter second, + /// doubling while it stays busy, up to five seconds; a save that happens starts again. + #[test] + fn a_busy_data_sources_save_backs_off() { + use std::sync::{Arc, Mutex}; + let busy = Arc::new(Mutex::new(true)); + let held = busy.clone(); + let services = crate::Services { + update_pref: Some(Box::new(move |_, value| { + if *held.lock().unwrap() { + return crate::PrefUpdate::Busy; + } + value(None).map_or(crate::PrefUpdate::Unchanged, |_| crate::PrefUpdate::Saved) + })), + ..Default::default() + }; + let mut app = RustGisApp::with_sample().with_services(services); + let source = |n: &str| rustgis_engine::sources::Source { + kind: "file".into(), + name: n.into(), + address: format!("/{n}.csv"), + extra: serde_json::Value::Null, + }; + app.session.note_source(source("a")); + let mut waits = Vec::new(); + for _ in 0..7 { + // Due now, whatever the delay was. + app.ui.sources.retry.at = None; + save(&mut app); + waits.push(retry_in(&app).unwrap_or_default()); + } + let ms: Vec = waits.iter().map(std::time::Duration::as_millis).collect(); + for (got, most) in ms.iter().zip([250, 500, 1000, 2000, 4000, 5000, 5000]) { + assert!(*got <= most && *got + 50 >= most, "{ms:?}"); + } + *busy.lock().unwrap() = false; + app.ui.sources.retry.at = None; + save(&mut app); + assert_eq!(retry_in(&app), None, "saved"); + assert_eq!(app.ui.sources.retry.failures, 0); + } use rustgis_engine::render::rustgis_tiles::{ address::{Origin, Reach}, cache, diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index ddc17b4ec6..2e785346d9 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -2913,6 +2913,47 @@ fn settings_left_to_save_share_one_deadline_at_exit() { assert!(said.iter().any(|t| t.contains("Some settings changed in this session weren't saved")), "{said:?}"); } +/// What a save's fresh read of the stored sources leaves out is said, though more was said +/// before: a password another window stored since is said at its own count; a save over what this +/// window wrote says nothing again. +#[test] +fn secrets_another_window_stored_since_are_said_again() { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let row = |address: &str, key: &str| json!({"kind": "file", "name": "", "address": address, key: "hidden"}); + let stored = json!({"favourites": [row("/a.csv", "password"), row("/b.csv", "password")]}).to_string(); + let store: PrefStore = Arc::new(Mutex::new(HashMap::from([("data_sources".to_string(), stored)]))); + let mut app = window_over(&store, &PrefOutcomes::default()); + let said = |app: &RustGisApp| -> Vec { + app.session + .notices_since(0) + .iter() + .filter(|n| n.text.contains("a password, key or token: not kept")) + .map(|n| n.text.clone()) + .collect() + }; + app.run("sources.favourite", json!({"kind": "file", "address": "/c.csv"})).unwrap(); + assert!(said(&app).iter().any(|t| t.starts_with("2 values")), "{:?}", said(&app)); + // Another window stores one more with a key. + { + let mut store = store.lock().unwrap(); + let mut v: serde_json::Value = serde_json::from_str(&store["data_sources"]).unwrap(); + v["favourites"].as_array_mut().unwrap().push(row("/d.csv", "api_key")); + store.insert("data_sources".into(), v.to_string()); + } + let before = said(&app).len(); + app.run("sources.favourite", json!({"kind": "file", "address": "/e.csv"})).unwrap(); + let now = said(&app); + assert_eq!(now.len(), before + 1, "{now:?}"); + assert!(now.last().is_some_and(|t| t.starts_with("1 value ")), "{now:?}"); + // Over what this window wrote: nothing new, nothing said. + app.run("sources.favourite", json!({"kind": "file", "address": "/f.csv"})).unwrap(); + assert_eq!(said(&app).len(), before + 1, "{:?}", said(&app)); + let mut kept = stored_favorites(&store); + kept.sort(); + assert_eq!(kept, ["/a.csv", "/b.csv", "/c.csv", "/d.csv", "/e.csv", "/f.csv"]); +} + /// A data sources save refused because a newer RustGIS stored them in a form this version can't /// read is said once and not tried again on a timer, only after another change here. #[test] From 7b0ef9e7ac8e29e59fd57a7f0272b64903cc4d43 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:10:26 -0600 Subject: [PATCH 18/27] fix(ui): the first data sources save doesn't repeat what loading said, and busy and failed saves back off apart (#1962) --- crates/ui-egui/src/sourcespane.rs | 54 +++++++++++++++++++++++++++++-- crates/ui-egui/tests/smoke.rs | 4 ++- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 6d0d746063..40a101e6d6 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -29,6 +29,12 @@ pub struct State { /// What this session last wrote: a save that finds it stored has nothing to lay its changes /// over. last_written: Option, + /// What the first read of them found stored: until this session writes, a save that finds it + /// still stored reads nothing new. + last_read: Option, + /// Whether the retries counted in `retry` are of another copy being busy, not of failed + /// writes: each counts its own run, so one doesn't lengthen the other's wait. + retry_busy: bool, /// When a data sources save that didn't happen (the preferences busy, unreadable or /// failing) is tried again. retry: Retry, @@ -115,6 +121,7 @@ pub fn load(app: &mut RustGisApp) { // stays; the stored lists are added after it. What of them isn't used here is said. let stored = rustgis_engine::sources::Sources::from_json(&text); app.session.sources.merge(stored); + app.ui.sources.last_read = Some(text); // After the merge: sources it moved past a list's limit are said too. say_unread(app); } @@ -175,10 +182,12 @@ fn attempt(app: &mut RustGisApp) -> Option { let now = web_time::Instant::now(); let (mut next, mut unreadable, mut fresh) = (None, None, false); let (sources, last) = (&app.session.sources, app.ui.sources.last_written.as_deref()); + // What this session last wrote, else what its first read found: what was said of it is known. + let known = last.or(app.ui.sources.last_read.as_deref()); let outcome = update(PREF, &mut |stored| { - // What is stored isn't what this session last wrote: read again, so what reading it - // leaves out is counted from it alone. - fresh = stored.filter(|s| !s.trim_start_matches('\u{feff}').trim().is_empty()).is_some_and(|s| Some(s) != last); + // What is stored isn't what this session last wrote or first read: another window changed + // it, and what reading it leaves out is counted from it alone. + fresh = stored.filter(|s| !s.trim_start_matches('\u{feff}').trim().is_empty()).is_some_and(|s| Some(s) != known); let mut rebased = sources.clone(); match rebased.rebase(stored, last) { Ok(()) => { @@ -209,6 +218,11 @@ fn attempt(app: &mut RustGisApp) -> Option { } (crate::PrefUpdate::Busy, _) => { let since = *state.busy_since.get_or_insert(now); + // A run of busy answers counts apart from failed writes. + if !state.retry_busy { + state.retry.failures = 0; + state.retry_busy = true; + } state.retry.failed(now, BUSY_RETRY.0, BUSY_RETRY.1); if now.duration_since(since) >= BUSY_SAY { let said = @@ -229,6 +243,10 @@ fn attempt(app: &mut RustGisApp) -> Option { } _ => { state.busy_since = None; + if state.retry_busy { + state.retry.failures = 0; + state.retry_busy = false; + } state.retry.failed(now, FAILED_RETRY.0, FAILED_RETRY.1); // Said when a save refuses, though the same was said when the sources were read. if let Some(why) = unreadable @@ -821,6 +839,36 @@ mod tests { assert_eq!(retry_in(&app), None, "saved"); assert_eq!(app.ui.sources.retry.failures, 0); } + + /// Busy answers and failed writes each count their own run of retries: a write failing after + /// a busy spell waits a failure's first delay, and busy again starts from a quarter second. + #[test] + fn busy_and_failed_saves_back_off_apart() { + use std::sync::{Arc, Mutex}; + let answer = Arc::new(Mutex::new(crate::PrefUpdate::Busy)); + let given = answer.clone(); + let services = crate::Services { update_pref: Some(Box::new(move |_, _| *given.lock().unwrap())), ..Default::default() }; + let mut app = RustGisApp::with_sample().with_services(services); + app.session.note_source(rustgis_engine::sources::Source { + kind: "file".into(), + name: "a".into(), + address: "/a.csv".into(), + extra: serde_json::Value::Null, + }); + let wait = |app: &mut RustGisApp, outcome: crate::PrefUpdate| { + *answer.lock().unwrap() = outcome; + app.ui.sources.retry.at = None; + save(app); + retry_in(app).unwrap_or_default().as_millis() + }; + let near = |got: u128, want: u128| got <= want && got + 50 >= want; + let busy = [wait(&mut app, crate::PrefUpdate::Busy), wait(&mut app, crate::PrefUpdate::Busy)]; + let failed = [wait(&mut app, crate::PrefUpdate::Failed), wait(&mut app, crate::PrefUpdate::Failed)]; + let again = wait(&mut app, crate::PrefUpdate::Busy); + assert!(near(busy[0], 250) && near(busy[1], 500), "{busy:?}"); + assert!(near(failed[0], FAILED_RETRY.0.as_millis()) && near(failed[1], 2 * FAILED_RETRY.0.as_millis()), "{failed:?}"); + assert!(near(again, 250), "{again}"); + } use rustgis_engine::render::rustgis_tiles::{ address::{Origin, Reach}, cache, diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 2e785346d9..0397cae3d0 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -2933,7 +2933,9 @@ fn secrets_another_window_stored_since_are_said_again() { .collect() }; app.run("sources.favourite", json!({"kind": "file", "address": "/c.csv"})).unwrap(); - assert!(said(&app).iter().any(|t| t.starts_with("2 values")), "{:?}", said(&app)); + // Said once by the first read; the first save, over what that read found, doesn't say it again. + assert_eq!(said(&app).iter().filter(|t| t.starts_with("2 values")).count(), 1, "{:?}", said(&app)); + assert_eq!(said(&app).len(), 1, "{:?}", said(&app)); // Another window stores one more with a key. { let mut store = store.lock().unwrap(); From 77cec672598a5da68f205d3a710a3a7cad6d7fe3 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:58:38 -0600 Subject: [PATCH 19/27] fix(ui): busy and failed data sources saves keep their own counts, and the backoff tests check the delay set (#1962) --- crates/ui-egui/src/sourcespane.rs | 62 +++++++++++++++---------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 40a101e6d6..2101d1d2d7 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -32,9 +32,10 @@ pub struct State { /// What the first read of them found stored: until this session writes, a save that finds it /// still stored reads nothing new. last_read: Option, - /// Whether the retries counted in `retry` are of another copy being busy, not of failed - /// writes: each counts its own run, so one doesn't lengthen the other's wait. - retry_busy: bool, + /// Busy answers and failed writes in a row since the last save that happened (or was + /// refused), counted apart: each backs off on its own count, whichever comes between. + busy_tries: u32, + failed_tries: u32, /// When a data sources save that didn't happen (the preferences busy, unreadable or /// failing) is tried again. retry: Retry, @@ -54,6 +55,8 @@ struct Retry { at: Option, /// Failed tries in a row. failures: u32, + /// The delay the last failure set. + last: std::time::Duration, } impl Retry { @@ -63,7 +66,8 @@ impl Retry { /// One more failure in a row: tried again after `first`, doubling each time up to `most`. fn failed(&mut self, now: web_time::Instant, first: std::time::Duration, most: std::time::Duration) { self.failures = self.failures.saturating_add(1); - self.at = Some(now + first.saturating_mul(1 << self.failures.saturating_sub(1).min(16)).min(most)); + self.last = first.saturating_mul(1 << self.failures.saturating_sub(1).min(16)).min(most); + self.at = Some(now + self.last); } fn done(&mut self) { *self = Retry::default(); @@ -206,6 +210,7 @@ fn attempt(app: &mut RustGisApp) -> Option { match (outcome, next) { (crate::PrefUpdate::Saved, Some((sources, text))) => { state.retry.done(); + (state.busy_tries, state.failed_tries) = (0, 0); (state.busy_since, state.refusal_said, state.last_written, state.refused_at) = (None, false, Some(text), None); // Saved: a later busy spell or refusal is said again. What the write left out of what // it read (secrets, cut names, repeated rows) is gone from the store, so what a fresh @@ -218,12 +223,10 @@ fn attempt(app: &mut RustGisApp) -> Option { } (crate::PrefUpdate::Busy, _) => { let since = *state.busy_since.get_or_insert(now); - // A run of busy answers counts apart from failed writes. - if !state.retry_busy { - state.retry.failures = 0; - state.retry_busy = true; - } + // Busy answers count apart from failed writes. + state.retry.failures = state.busy_tries; state.retry.failed(now, BUSY_RETRY.0, BUSY_RETRY.1); + state.busy_tries = state.retry.failures; if now.duration_since(since) >= BUSY_SAY { let said = crate::tl!("The data sources aren't saved yet: another copy of RustGIS keeps its preferences busy. Trying again."); @@ -235,6 +238,7 @@ fn attempt(app: &mut RustGisApp) -> Option { (crate::PrefUpdate::Refused, _) => { state.busy_since = None; state.retry.done(); + (state.busy_tries, state.failed_tries) = (0, 0); state.refused_at = Some(app.session.sources.generation); let said = crate::tl!( "The data sources aren't saved: a newer RustGIS saved them in a form this version can't read, so they are kept as they are." @@ -243,11 +247,9 @@ fn attempt(app: &mut RustGisApp) -> Option { } _ => { state.busy_since = None; - if state.retry_busy { - state.retry.failures = 0; - state.retry_busy = false; - } + state.retry.failures = state.failed_tries; state.retry.failed(now, FAILED_RETRY.0, FAILED_RETRY.1); + state.failed_tries = state.retry.failures; // Said when a save refuses, though the same was said when the sources were read. if let Some(why) = unreadable && !state.refusal_said @@ -822,26 +824,24 @@ mod tests { extra: serde_json::Value::Null, }; app.session.note_source(source("a")); - let mut waits = Vec::new(); + let mut delays = Vec::new(); for _ in 0..7 { // Due now, whatever the delay was. app.ui.sources.retry.at = None; save(&mut app); - waits.push(retry_in(&app).unwrap_or_default()); - } - let ms: Vec = waits.iter().map(std::time::Duration::as_millis).collect(); - for (got, most) in ms.iter().zip([250, 500, 1000, 2000, 4000, 5000, 5000]) { - assert!(*got <= most && *got + 50 >= most, "{ms:?}"); + delays.push(app.ui.sources.retry.last.as_millis()); } + assert_eq!(delays, [250, 500, 1000, 2000, 4000, 5000, 5000]); *busy.lock().unwrap() = false; app.ui.sources.retry.at = None; save(&mut app); assert_eq!(retry_in(&app), None, "saved"); - assert_eq!(app.ui.sources.retry.failures, 0); + assert_eq!((app.ui.sources.retry.failures, app.ui.sources.busy_tries), (0, 0)); } - /// Busy answers and failed writes each count their own run of retries: a write failing after - /// a busy spell waits a failure's first delay, and busy again starts from a quarter second. + /// Busy answers and failed writes each count their own retries: a write failing after a busy + /// spell waits a failure's first delay, and busy again goes on from its own count, so + /// alternating still backs off to each one's cap. #[test] fn busy_and_failed_saves_back_off_apart() { use std::sync::{Arc, Mutex}; @@ -855,19 +855,19 @@ mod tests { address: "/a.csv".into(), extra: serde_json::Value::Null, }); - let wait = |app: &mut RustGisApp, outcome: crate::PrefUpdate| { + let delay = |app: &mut RustGisApp, outcome: crate::PrefUpdate| { *answer.lock().unwrap() = outcome; app.ui.sources.retry.at = None; save(app); - retry_in(app).unwrap_or_default().as_millis() + app.ui.sources.retry.last.as_millis() }; - let near = |got: u128, want: u128| got <= want && got + 50 >= want; - let busy = [wait(&mut app, crate::PrefUpdate::Busy), wait(&mut app, crate::PrefUpdate::Busy)]; - let failed = [wait(&mut app, crate::PrefUpdate::Failed), wait(&mut app, crate::PrefUpdate::Failed)]; - let again = wait(&mut app, crate::PrefUpdate::Busy); - assert!(near(busy[0], 250) && near(busy[1], 500), "{busy:?}"); - assert!(near(failed[0], FAILED_RETRY.0.as_millis()) && near(failed[1], 2 * FAILED_RETRY.0.as_millis()), "{failed:?}"); - assert!(near(again, 250), "{again}"); + let (busy, failed) = (crate::PrefUpdate::Busy, crate::PrefUpdate::Failed); + let first = FAILED_RETRY.0.as_millis(); + let delays: Vec = [busy, busy, failed, failed, busy, failed].into_iter().map(|o| delay(&mut app, o)).collect(); + assert_eq!(delays, [250, 500, first, 2 * first, 1000, 4 * first]); + // Alternating still reaches each cap. + let alternating: Vec = (0..16).map(|i| delay(&mut app, if i % 2 == 0 { busy } else { failed })).collect(); + assert_eq!(alternating[14..], [BUSY_RETRY.1.as_millis(), FAILED_RETRY.1.as_millis()]); } use rustgis_engine::render::rustgis_tiles::{ address::{Origin, Reach}, From 4ddf5e6c93e1aeb1f23fd8bbd1188e9e0ba95168 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:14:27 -0600 Subject: [PATCH 20/27] fix(engine): a setting left to save doesn't write over a value another copy stored since (#1962) --- crates/engine/src/prefs.rs | 76 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index b98e15c010..5c3de21d2f 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -70,13 +70,21 @@ fn write_in(path: &Path, key: &str, value: &str) -> Result { let mut refused = REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); pending.remove(&id); refused.remove(&id); + let mut seen = SEEN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); // Written, refused or failing here, it is no longer a retry that failed. if done != Ok(Updated::Busy) { FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + seen.remove(&id); } match done { - // Left to save: tried again once the other copy lets go of the lock. + // Left to save: tried again once the other copy lets go of the lock, unless that copy + // stores the key meanwhile. What is stored for it now is read without the lock (a write + // replaces the file whole): the first time it is left, so a later change here doesn't + // take the other copy's value for this one's. Ok(Updated::Busy) => { + if let Some(stored) = stored_text(path, key) { + seen.entry(id.clone()).or_insert(stored); + } pending.insert(id, value.to_string()); } // Saved: a refusal of the key said before is over, and is said again if one comes back. @@ -103,6 +111,25 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); +/// What each key left to save held when it was first left (`None`: not there): a retry that +/// finds something else stored, another copy's later write, keeps that and drops this one's. +static SEEN: Mutex>> = Mutex::new(std::collections::BTreeMap::new()); + +/// What the preferences at `path` hold for `key` as text (`Some(None)`: not there), read without +/// the lock; none when the file can't be read. +fn stored_text(path: &Path, key: &str) -> Option> { + match std::fs::read(path) { + Ok(bytes) => parse_preferences(&bytes).ok().map(|map| map.get(key).and_then(Value::as_str).map(str::to_string)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(None), + Err(_) => None, + } +} + +/// Says that a setting left to save wasn't, as another copy of RustGIS stored it since. +fn overtaken_notice(key: &str) -> String { + format!("the setting {key} changed here isn't saved: another copy of RustGIS saved it since, so that copy's value is kept") +} + /// Values left to save whose last retry failed, said once until one is saved. static FAILED: Mutex> = Mutex::new(std::collections::BTreeSet::new()); @@ -177,12 +204,30 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec Date: Mon, 30 Nov 2026 13:14:27 -0600 Subject: [PATCH 21/27] fix(ui): a data sources save left during a frame's interface asks for its retry frame (#1962) --- crates/ui-egui/src/lib.rs | 10 +++---- crates/ui-egui/src/sourcespane.rs | 45 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 79b71aa2bb..645bb6af69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8030,13 +8030,9 @@ impl RustGisApp { { ctx.request_repaint(); } - // A setting a save during `ui` left to save (another copy saving its preferences) is tried - // again on a later frame, which an idle window wouldn't otherwise draw: `logic` looked - // before this frame's panes saved. The same backoff as there, so a value that keeps failing - // doesn't wake the window more often. - if let Some(retry) = sourcespane::retry_prefs(self) { - ctx.request_repaint_after(retry); - } + // What a save during `ui` left to save (the data sources, other settings) is tried again + // on a later frame, which an idle window wouldn't otherwise draw. + sourcespane::wake_after_ui(self, &ctx); // egui times clicks by the frame they arrive in: at a slow frame rate the two clicks of a // double-click land too far apart for its default delay (#1321). It reads the delay when // the next frame begins, before that frame's `logic`, so it's set here, from this frame's diff --git a/crates/ui-egui/src/sourcespane.rs b/crates/ui-egui/src/sourcespane.rs index 2101d1d2d7..d4d0119eb0 100644 --- a/crates/ui-egui/src/sourcespane.rs +++ b/crates/ui-egui/src/sourcespane.rs @@ -323,6 +323,20 @@ fn save_sources_at_exit(app: &mut RustGisApp, deadline: web_time::Instant) { } } +/// At the end of a frame's interface: what a save during it left to save while another copy +/// saved its preferences (the data sources, from a command the interface ran, and the other +/// settings) asks for the frame that tries it again, which an idle window wouldn't otherwise +/// draw: `logic` looked before this frame's panes and commands saved. The same backoff as there, +/// so a save that keeps failing doesn't wake the window more often. +pub fn wake_after_ui(app: &mut RustGisApp, ctx: &egui::Context) { + if let Some(retry) = retry_in(app) { + ctx.request_repaint_after(retry); + } + if let Some(retry) = retry_prefs(app) { + ctx.request_repaint_after(retry); + } +} + /// How soon a data sources save left to do is tried again, if one is: the frame that tries it /// is asked for. pub fn retry_in(app: &RustGisApp) -> Option { @@ -800,6 +814,37 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { mod tests { use super::*; + /// What a save left to save asks for the frame that tries it again: a data sources save that + /// found another copy saving, as a command run during `ui` leaves one; nothing left, nothing + /// asked for. + #[test] + fn a_data_sources_save_left_asks_for_its_retry() { + let services = crate::Services { update_pref: Some(Box::new(|_, _| crate::PrefUpdate::Busy)), ..Default::default() }; + let mut app = RustGisApp::with_sample().with_services(services); + let ctx = egui::Context::default(); + let wakes = |app: &mut RustGisApp| { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| wake_after_ui(app, ui.ctx())); + output.textures_delta.clear(); + ctx.has_requested_repaint() + }; + // A new context asks for its first frames itself. + for _ in 0..4 { + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + } + save(&mut app); + assert!(!wakes(&mut app), "nothing left"); + app.session.note_source(rustgis_engine::sources::Source { + kind: "file".into(), + name: "a".into(), + address: "/a.csv".into(), + extra: serde_json::Value::Null, + }); + save(&mut app); + assert!(retry_in(&app).is_some(), "left to save"); + assert!(wakes(&mut app), "its retry asked for"); + } + /// A data sources save that finds another copy saving is tried again after a quarter second, /// doubling while it stays busy, up to five seconds; a save that happens starts again. #[test] From a0a83ff0724425b4e2e1753a77d37d8a0fa884c7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:40:26 -0600 Subject: [PATCH 22/27] revert(engine): keep queued settings as before; the same-key race is left out --- crates/engine/src/prefs.rs | 76 ++------------------------------------ 1 file changed, 3 insertions(+), 73 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5c3de21d2f..b98e15c010 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -70,21 +70,13 @@ fn write_in(path: &Path, key: &str, value: &str) -> Result { let mut refused = REFUSED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); pending.remove(&id); refused.remove(&id); - let mut seen = SEEN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); // Written, refused or failing here, it is no longer a retry that failed. if done != Ok(Updated::Busy) { FAILED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); - seen.remove(&id); } match done { - // Left to save: tried again once the other copy lets go of the lock, unless that copy - // stores the key meanwhile. What is stored for it now is read without the lock (a write - // replaces the file whole): the first time it is left, so a later change here doesn't - // take the other copy's value for this one's. + // Left to save: tried again once the other copy lets go of the lock. Ok(Updated::Busy) => { - if let Some(stored) = stored_text(path, key) { - seen.entry(id.clone()).or_insert(stored); - } pending.insert(id, value.to_string()); } // Saved: a refusal of the key said before is over, and is said again if one comes back. @@ -111,25 +103,6 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); -/// What each key left to save held when it was first left (`None`: not there): a retry that -/// finds something else stored, another copy's later write, keeps that and drops this one's. -static SEEN: Mutex>> = Mutex::new(std::collections::BTreeMap::new()); - -/// What the preferences at `path` hold for `key` as text (`Some(None)`: not there), read without -/// the lock; none when the file can't be read. -fn stored_text(path: &Path, key: &str) -> Option> { - match std::fs::read(path) { - Ok(bytes) => parse_preferences(&bytes).ok().map(|map| map.get(key).and_then(Value::as_str).map(str::to_string)), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(None), - Err(_) => None, - } -} - -/// Says that a setting left to save wasn't, as another copy of RustGIS stored it since. -fn overtaken_notice(key: &str) -> String { - format!("the setting {key} changed here isn't saved: another copy of RustGIS saved it since, so that copy's value is kept") -} - /// Values left to save whose last retry failed, said once until one is saved. static FAILED: Mutex> = Mutex::new(std::collections::BTreeSet::new()); @@ -204,30 +177,12 @@ fn retry_pending_in(only: Option<&Path>, wait: std::time::Duration) -> (Vec Date: Mon, 30 Nov 2026 19:22:21 -0600 Subject: [PATCH 23/27] fix(engine): settings saved without the shared lock are said once a session (#1962) --- apps/rustgis-mobile/src/shell.rs | 8 ++++++ apps/rustgis/src/main.rs | 12 ++++++++ crates/engine/src/prefs.rs | 47 +++++++++++++++++++++++++++++++- 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 76c06bb986..7b3434a03d 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -970,6 +970,14 @@ fn settings_saved(result: Result, String>) { match result { Ok(set_aside) => { *last = None; + // Saved without the lock (said once a session): two copies can then write over each + // other's data sources. + if let Some(why) = rustgis_engine::prefs::unlocked_once() { + settings_notices().push(i18n::fmt( + "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved data sources.", + &[("why", &why)], + )); + } if let Some(path) = set_aside { settings_notices().push(i18n::fmt( "Your settings couldn't be read, so RustGIS started new ones. The old settings file was kept as {path}.", diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 34a49f0851..eed504b80e 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -63,8 +63,14 @@ mod prefs { SetAside(PathBuf), /// A setting couldn't be saved. NotSaved(String), + /// Settings were saved without the lock other copies of RustGIS share, and why. + Unlocked(String), } + /// What a save without the shared lock says, once a session. + const UNLOCKED: &str = + "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved data sources."; + static NOTICES: Mutex> = Mutex::new(Vec::new()); /// Repeated equivalent failures stay quiet; changed recovery details must reach the window. static LAST_FAILURE: Mutex> = Mutex::new(None); @@ -91,6 +97,11 @@ mod prefs { pub fn saved(result: Result, String>) { match result { Ok(set_aside) => { + // Saved without the lock (said once a session): two copies can then write over each + // other's data sources. + if let Some(why) = rustgis_engine::prefs::unlocked_once() { + notices().push(Notice::Unlocked(why)); + } *LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; if let Some(path) = set_aside { log::warn!("unreadable preferences set aside as {}", path.display()); @@ -147,6 +158,7 @@ mod prefs { &[("path", &path.display().to_string())], ), Notice::NotSaved(error) => fmt("Settings could not be saved reliably ({error}).", &[("error", error)]), + Notice::Unlocked(why) => fmt(UNLOCKED, &[("why", why)]), } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index b98e15c010..5089337068 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -103,6 +103,25 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); +/// Why the preferences at each path were saved without the lock, and whether that was said +/// ([`unlocked_once`]). +static UNLOCKED: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + +/// Why the preferences were saved without the lock this session (a lock file that can't be +/// opened or isn't a regular file, a folder that can't be locked), the first time it is asked +/// after one was; none after, and none while every save had the lock. Without it, two copies of +/// RustGIS saving at once can write over each other's data sources, which the app says once. +pub fn unlocked_once() -> Option { + let dir = rustgis_data::dirs::config_dir()?; + unlocked_once_in(&dir.join(FILE)) +} + +fn unlocked_once_in(path: &Path) -> Option { + let mut unlocked = UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let (why, said) = unlocked.get_mut(path)?; + (!std::mem::replace(said, true)).then(|| why.clone()) +} + /// Values left to save whose last retry failed, said once until one is saved. static FAILED: Mutex> = Mutex::new(std::collections::BTreeSet::new()); @@ -315,12 +334,14 @@ fn lock(path: &Path) -> Result { // owner's alone. // Saved without the lock where it can't be had (some network folders, a lock file that isn't // a regular file of this user's or can't be opened), as before the lock: logged once a - // session, as every save would log it again. + // session, as every save would log it again, and kept for the app to say once + // ([`unlocked_once`]), as two copies saving at once can then write over each other. let unlockable = |why: String| { static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("preferences saved without a lock: {why}"); } + UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).entry(path.to_path_buf()).or_insert((why, false)); Ok(Locked::Unlockable) }; std::fs::create_dir_all(dir).map_err(|error| format!("couldn't create {}: {error}", dir.display()))?; @@ -863,6 +884,7 @@ mod tests { drop(held); assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); + assert_eq!(unlocked_once_in(&path), None, "saved with the lock: nothing to say"); // A value given back as none leaves the preference as it was. assert_eq!(update_file(&path, "k", |_| None).unwrap(), Updated::Unchanged); assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); @@ -875,10 +897,33 @@ mod tests { std::os::unix::fs::symlink(dir.join("elsewhere"), &lock_path).unwrap(); assert!(matches!(lock(&path), Ok(Locked::Unlockable))); assert!(!dir.join("elsewhere").exists()); + // Saved without it, and that is there to say once. + assert_eq!(update_file(&path, "k", |_| Some("w".into())).unwrap(), Updated::Saved(None)); + assert!(unlocked_once_in(&path).is_some_and(|why| why.contains("json.lock"))); + assert_eq!(unlocked_once_in(&path), None, "said once"); } std::fs::remove_dir_all(dir).unwrap(); } + /// A lock file that isn't a regular file (a folder in its place) can't be locked: the + /// preferences are saved without it, and why is there to say once a session. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_save_without_the_lock_is_there_to_say_once() { + let dir = std::env::temp_dir().join(format!("rustgis-preferences-unlocked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(FILE); + std::fs::create_dir_all(path.with_extension("json.lock")).unwrap(); + assert_eq!(unlocked_once_in(&path), None); + assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); + assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); + assert!(unlocked_once_in(&path).is_some_and(|why| why.contains("json.lock"))); + assert_eq!(write_in(&path, "k", "w").unwrap(), Updated::Saved(None)); + assert_eq!(unlocked_once_in(&path), None, "said once a session"); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Recovery preserves the malformed snapshot, even if the path now contains another save. #[test] fn recovery_keeps_the_bytes_that_failed_parsing() { From 0be767531b98423a0633a48e4a85cef8970c7f98 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:15:00 -0600 Subject: [PATCH 24/27] fix(engine): a save without the lock is said only once one happened, and names any setting (#1962) --- apps/rustgis-mobile/src/shell.rs | 5 +-- apps/rustgis/src/main.rs | 13 ++++--- crates/engine/src/prefs.rs | 58 +++++++++++++++++++++++--------- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 7b3434a03d..54730cc491 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -973,10 +973,7 @@ fn settings_saved(result: Result, String>) { // Saved without the lock (said once a session): two copies can then write over each // other's data sources. if let Some(why) = rustgis_engine::prefs::unlocked_once() { - settings_notices().push(i18n::fmt( - "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved data sources.", - &[("why", &why)], - )); + settings_notices().push(i18n::fmt(rustgis_engine::prefs::UNLOCKED_NOTICE, &[("why", &why)])); } if let Some(path) = set_aside { settings_notices().push(i18n::fmt( diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index eed504b80e..d027f8ffe8 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -67,10 +67,6 @@ mod prefs { Unlocked(String), } - /// What a save without the shared lock says, once a session. - const UNLOCKED: &str = - "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved data sources."; - static NOTICES: Mutex> = Mutex::new(Vec::new()); /// Repeated equivalent failures stay quiet; changed recovery details must reach the window. static LAST_FAILURE: Mutex> = Mutex::new(None); @@ -158,7 +154,7 @@ mod prefs { &[("path", &path.display().to_string())], ), Notice::NotSaved(error) => fmt("Settings could not be saved reliably ({error}).", &[("error", error)]), - Notice::Unlocked(why) => fmt(UNLOCKED, &[("why", why)]), + Notice::Unlocked(why) => fmt(rustgis_engine::prefs::UNLOCKED_NOTICE, &[("why", why)]), } } @@ -1176,6 +1172,13 @@ mod tests { assert!(super::recovery_store(Some(dir.join("fresh"))).is_ok()); } + /// A save without the lock says why, and that any setting can be written over. + #[test] + fn a_save_without_the_lock_says_why() { + let text = prefs::text(&prefs::Notice::Unlocked("couldn't open prefs.json.lock".into())); + assert!(text.contains("couldn't open prefs.json.lock") && text.contains("saved settings, data sources included"), "{text}"); + } + #[test] fn settings_that_cannot_be_saved_are_said_once_until_saving_works() { use prefs::Notice; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5089337068..21771b5048 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -103,14 +103,22 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); +/// What the app says, translated, of a save without the lock ([`unlocked_once`]): `{why}` is the +/// reason given. +pub const UNLOCKED_NOTICE: &str = "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included."; + /// Why the preferences at each path were saved without the lock, and whether that was said /// ([`unlocked_once`]). static UNLOCKED: Mutex> = Mutex::new(std::collections::BTreeMap::new()); /// Why the preferences were saved without the lock this session (a lock file that can't be /// opened or isn't a regular file, a folder that can't be locked), the first time it is asked -/// after one was; none after, and none while every save had the lock. Without it, two copies of -/// RustGIS saving at once can write over each other's data sources, which the app says once. +/// after such a save happened; none after, and none while every save had the lock or none +/// without it was written (a value left as it was writes nothing, so it waits for the first save +/// that does). Without the lock, two copies of RustGIS saving at once can write over each +/// other's settings, which the app says once. +/// +/// The app says it with [`UNLOCKED_NOTICE`], translated, `{why}` the reason given. pub fn unlocked_once() -> Option { let dir = rustgis_data::dirs::config_dir()?; unlocked_once_in(&dir.join(FILE)) @@ -284,12 +292,18 @@ pub fn update(key: &str, value: impl FnOnce(Option<&str>) -> Option) -> /// [`update`] of the file at `path` (a test folder in tests), with its lock. fn update_file(path: &Path, key: &str, value: impl FnOnce(Option<&str>) -> Option) -> Result { - let _held = match lock(path)? { + let (_held, unlocked) = match lock(path)? { Locked::Busy => return Ok(Updated::Busy), - Locked::Held(held) => Some(held), - Locked::Unlockable => None, + Locked::Held(held) => (Some(held), None), + Locked::Unlockable(why) => (None, Some(why)), }; - write_with(path, key, value, std::fs::read(path), sync_directory) + let done = write_with(path, key, value, std::fs::read(path), sync_directory); + // Saved without the lock: kept for the app to say once ([`unlocked_once`]), as two copies + // saving at once can then write over each other. A save that didn't happen says nothing. + if let (Some(why), Ok(Updated::Saved(_))) = (unlocked, &done) { + UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).entry(path.to_path_buf()).or_insert((why, false)); + } + done } /// [`write`] to the file at `path` (a test folder in tests): returns where a malformed file went. @@ -321,8 +335,9 @@ enum Locked { Held(Lock), /// Another copy of RustGIS holds it. Busy, - /// This folder can't be locked at all (some network folders): saved without it, as before. - Unlockable, + /// This folder can't be locked at all (some network folders), and why: saved without it, as + /// before. + Unlockable(String), } /// Tries the lock once, never waiting: [`Locked::Busy`] while another copy holds it. @@ -334,15 +349,14 @@ fn lock(path: &Path) -> Result { // owner's alone. // Saved without the lock where it can't be had (some network folders, a lock file that isn't // a regular file of this user's or can't be opened), as before the lock: logged once a - // session, as every save would log it again, and kept for the app to say once - // ([`unlocked_once`]), as two copies saving at once can then write over each other. + // session, as every save would log it again; the app says it once a save happens + // ([`update_file`]). let unlockable = |why: String| { static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("preferences saved without a lock: {why}"); } - UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).entry(path.to_path_buf()).or_insert((why, false)); - Ok(Locked::Unlockable) + Ok(Locked::Unlockable(why)) }; std::fs::create_dir_all(dir).map_err(|error| format!("couldn't create {}: {error}", dir.display()))?; let file = match rustgis_data::io::open_lock_file(&lock_path, true, 0o600) { @@ -831,6 +845,7 @@ mod tests { REFUSED.lock().unwrap().retain(|(p, _), _| p != path); SAID_NEWER.lock().unwrap().retain(|(p, _)| p != path); FAILED.lock().unwrap().retain(|(p, _)| p != path); + UNLOCKED.lock().unwrap().remove(path); } /// At exit, a value left to save that turns out refused (a newer RustGIS stored the key @@ -895,7 +910,7 @@ mod tests { let lock_path = path.with_extension("json.lock"); std::fs::remove_file(&lock_path).unwrap(); std::os::unix::fs::symlink(dir.join("elsewhere"), &lock_path).unwrap(); - assert!(matches!(lock(&path), Ok(Locked::Unlockable))); + assert!(matches!(lock(&path), Ok(Locked::Unlockable(_)))); assert!(!dir.join("elsewhere").exists()); // Saved without it, and that is there to say once. assert_eq!(update_file(&path, "k", |_| Some("w".into())).unwrap(), Updated::Saved(None)); @@ -914,8 +929,21 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(FILE); - std::fs::create_dir_all(path.with_extension("json.lock")).unwrap(); - assert_eq!(unlocked_once_in(&path), None); + forget_values(&path); + let lock_dir = path.with_extension("json.lock"); + // Without the lock, a write that fails (the preferences unreadable: a folder in their + // place) says nothing of the lock; nor does a later save that has it. + std::fs::create_dir_all(&lock_dir).unwrap(); + std::fs::create_dir_all(&path).unwrap(); + assert!(update_file(&path, "k", |_| Some("v".into())).is_err()); + assert_eq!(unlocked_once_in(&path), None, "nothing saved without the lock"); + std::fs::remove_dir(&path).unwrap(); + std::fs::remove_dir(&lock_dir).unwrap(); + assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); + assert_eq!(unlocked_once_in(&path), None, "saved with the lock"); + // Saved without it: said once. + std::fs::remove_file(&lock_dir).unwrap(); + std::fs::create_dir_all(&lock_dir).unwrap(); assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); assert!(unlocked_once_in(&path).is_some_and(|why| why.contains("json.lock"))); From c3db030f6ee9b9c752458adce972c41d43676da5 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:37:35 -0600 Subject: [PATCH 25/27] fix(engine): a file replaced without the lock is said even when its sync fails, and the notice text sits at each app's call (#1962) --- apps/rustgis-mobile/src/shell.rs | 7 ++-- apps/rustgis/src/main.rs | 7 ++-- crates/engine/src/prefs.rs | 60 ++++++++++++++++++++------------ 3 files changed, 48 insertions(+), 26 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 54730cc491..ff95f8067f 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -971,9 +971,12 @@ fn settings_saved(result: Result, String>) { Ok(set_aside) => { *last = None; // Saved without the lock (said once a session): two copies can then write over each - // other's data sources. + // other's settings, data sources included. if let Some(why) = rustgis_engine::prefs::unlocked_once() { - settings_notices().push(i18n::fmt(rustgis_engine::prefs::UNLOCKED_NOTICE, &[("why", &why)])); + settings_notices().push(i18n::fmt( + "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included.", + &[("why", &why)], + )); } if let Some(path) = set_aside { settings_notices().push(i18n::fmt( diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index d027f8ffe8..b88101e6fc 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -94,7 +94,7 @@ mod prefs { match result { Ok(set_aside) => { // Saved without the lock (said once a session): two copies can then write over each - // other's data sources. + // other's settings, data sources included. if let Some(why) = rustgis_engine::prefs::unlocked_once() { notices().push(Notice::Unlocked(why)); } @@ -154,7 +154,10 @@ mod prefs { &[("path", &path.display().to_string())], ), Notice::NotSaved(error) => fmt("Settings could not be saved reliably ({error}).", &[("error", error)]), - Notice::Unlocked(why) => fmt(rustgis_engine::prefs::UNLOCKED_NOTICE, &[("why", why)]), + Notice::Unlocked(why) => fmt( + "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included.", + &[("why", why)], + ), } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 21771b5048..33515c27f4 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -103,10 +103,6 @@ static PENDING: Values = Mutex::new(std::collections::BTreeMap::new()); /// kept for this session (a read of the setting gives them), never tried again. static REFUSED: Values = Mutex::new(std::collections::BTreeMap::new()); -/// What the app says, translated, of a save without the lock ([`unlocked_once`]): `{why}` is the -/// reason given. -pub const UNLOCKED_NOTICE: &str = "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included."; - /// Why the preferences at each path were saved without the lock, and whether that was said /// ([`unlocked_once`]). static UNLOCKED: Mutex> = Mutex::new(std::collections::BTreeMap::new()); @@ -117,8 +113,6 @@ static UNLOCKED: Mutex> = Mu /// without it was written (a value left as it was writes nothing, so it waits for the first save /// that does). Without the lock, two copies of RustGIS saving at once can write over each /// other's settings, which the app says once. -/// -/// The app says it with [`UNLOCKED_NOTICE`], translated, `{why}` the reason given. pub fn unlocked_once() -> Option { let dir = rustgis_data::dirs::config_dir()?; unlocked_once_in(&dir.join(FILE)) @@ -292,15 +286,37 @@ pub fn update(key: &str, value: impl FnOnce(Option<&str>) -> Option) -> /// [`update`] of the file at `path` (a test folder in tests), with its lock. fn update_file(path: &Path, key: &str, value: impl FnOnce(Option<&str>) -> Option) -> Result { + update_file_with(path, key, value, sync_directory) +} + +/// [`update_file`] with `sync` confirming the replaced file (a failing one in tests). +fn update_file_with( + path: &Path, + key: &str, + value: impl FnOnce(Option<&str>) -> Option, + sync: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { let (_held, unlocked) = match lock(path)? { Locked::Busy => return Ok(Updated::Busy), Locked::Held(held) => (Some(held), None), Locked::Unlockable(why) => (None, Some(why)), }; - let done = write_with(path, key, value, std::fs::read(path), sync_directory); - // Saved without the lock: kept for the app to say once ([`unlocked_once`]), as two copies - // saving at once can then write over each other. A save that didn't happen says nothing. - if let (Some(why), Ok(Updated::Saved(_))) = (unlocked, &done) { + // The sync runs only once the file was replaced, so it tells a replaced file apart from a + // write that didn't happen, whatever the sync itself comes to. + let mut replaced = false; + let done = write_with(path, key, value, std::fs::read(path), |p| { + replaced = true; + sync(p) + }); + // Replaced without the lock (some network folders, a lock file that isn't a regular file of + // this user's or can't be opened), as before the lock: logged once a session, as every save + // would log it again, and kept for the app to say once ([`unlocked_once`]), as two copies + // saving at once can then write over each other. A write that didn't happen says nothing. + if let (Some(why), true) = (unlocked, replaced) { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + log::warn!("preferences saved without a lock: {why}"); + } UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).entry(path.to_path_buf()).or_insert((why, false)); } done @@ -347,17 +363,9 @@ fn lock(path: &Path) -> Result { let dir = path.parent().ok_or("the settings folder isn't available")?; // Never through a link (the open itself refuses one on Unix), only a regular file, its // owner's alone. - // Saved without the lock where it can't be had (some network folders, a lock file that isn't - // a regular file of this user's or can't be opened), as before the lock: logged once a - // session, as every save would log it again; the app says it once a save happens - // ([`update_file`]). - let unlockable = |why: String| { - static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { - log::warn!("preferences saved without a lock: {why}"); - } - Ok(Locked::Unlockable(why)) - }; + // Saved without the lock where it can't be had, as before the lock; logged and said once a + // save replaces the file ([`update_file_with`]). + let unlockable = |why: String| Ok(Locked::Unlockable(why)); std::fs::create_dir_all(dir).map_err(|error| format!("couldn't create {}: {error}", dir.display()))?; let file = match rustgis_data::io::open_lock_file(&lock_path, true, 0o600) { Ok(file) => file, @@ -941,9 +949,17 @@ mod tests { std::fs::remove_dir(&lock_dir).unwrap(); assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); assert_eq!(unlocked_once_in(&path), None, "saved with the lock"); - // Saved without it: said once. + // Replaced without it, though its durability couldn't be confirmed (as on some network + // folders): an error, and said once all the same, as the file was written. std::fs::remove_file(&lock_dir).unwrap(); std::fs::create_dir_all(&lock_dir).unwrap(); + let failing = |_: &Path| Err(std::io::Error::other("no sync here")); + assert!(update_file_with(&path, "k", |_| Some("u".into()), failing).is_err_and(|e| e.contains("replaced"))); + assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("u")); + assert!(unlocked_once_in(&path).is_some_and(|why| why.contains("json.lock"))); + assert_eq!(unlocked_once_in(&path), None, "said once"); + // As at a new session: a save without it that succeeds is said once. + forget_values(&path); assert_eq!(update_file(&path, "k", |_| Some("v".into())).unwrap(), Updated::Saved(None)); assert_eq!(read_at(&path).unwrap().get("k").and_then(Value::as_str), Some("v")); assert!(unlocked_once_in(&path).is_some_and(|why| why.contains("json.lock"))); From 4a8d1d9f451b49dae38b93dbedf69764faa28522 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:52:59 -0600 Subject: [PATCH 26/27] fix(ui): a save without the lock is said whatever the save came to, and logged per settings file (#1962) --- apps/rustgis-mobile/src/shell.rs | 17 +++++++++-------- apps/rustgis/src/main.rs | 11 ++++++----- crates/engine/src/prefs.rs | 6 +++--- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index ff95f8067f..579c296a3a 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -967,17 +967,18 @@ fn read_settings() -> serde_json::Map { fn settings_saved(result: Result, String>) { static LAST_FAILURE: Mutex> = Mutex::new(None); let mut last = LAST_FAILURE.lock().unwrap_or_else(|e| e.into_inner()); + // Saved without the lock (said once a session): two copies can then write over each + // other's settings, data sources included. Asked whatever the save came to, as a file + // replaced without the lock whose sync then failed is an error. + if let Some(why) = rustgis_engine::prefs::unlocked_once() { + settings_notices().push(i18n::fmt( + "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included.", + &[("why", &why)], + )); + } match result { Ok(set_aside) => { *last = None; - // Saved without the lock (said once a session): two copies can then write over each - // other's settings, data sources included. - if let Some(why) = rustgis_engine::prefs::unlocked_once() { - settings_notices().push(i18n::fmt( - "Settings are saved without a lock ({why}), so two copies of RustGIS open at once can overwrite each other's saved settings, data sources included.", - &[("why", &why)], - )); - } if let Some(path) = set_aside { settings_notices().push(i18n::fmt( "Your settings couldn't be read, so RustGIS started new ones. The old settings file was kept as {path}.", diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index b88101e6fc..2753a92ea9 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -91,13 +91,14 @@ mod prefs { /// Keeps what a save came to for the window: a malformed file set aside (which also explains /// an earlier read failure still waiting), or a failure whose outcome changed since last time. pub fn saved(result: Result, String>) { + // Saved without the lock (said once a session): two copies can then write over each + // other's settings, data sources included. Asked whatever the save came to, as a file + // replaced without the lock whose sync then failed is an error. + if let Some(why) = rustgis_engine::prefs::unlocked_once() { + notices().push(Notice::Unlocked(why)); + } match result { Ok(set_aside) => { - // Saved without the lock (said once a session): two copies can then write over each - // other's settings, data sources included. - if let Some(why) = rustgis_engine::prefs::unlocked_once() { - notices().push(Notice::Unlocked(why)); - } *LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; if let Some(path) = set_aside { log::warn!("unreadable preferences set aside as {}", path.display()); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 33515c27f4..e5c874394a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -313,11 +313,11 @@ fn update_file_with( // would log it again, and kept for the app to say once ([`unlocked_once`]), as two copies // saving at once can then write over each other. A write that didn't happen says nothing. if let (Some(why), true) = (unlocked, replaced) { - static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { + let mut unlocked = UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let std::collections::btree_map::Entry::Vacant(entry) = unlocked.entry(path.to_path_buf()) { log::warn!("preferences saved without a lock: {why}"); + entry.insert((why, false)); } - UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).entry(path.to_path_buf()).or_insert((why, false)); } done } From d3c377c03bae5a48d6fd7f2811a3510fdeb44ce4 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:55:35 -0600 Subject: [PATCH 27/27] docs(engine): say where the save-without-a-lock notice and its log line come from (#1962) --- apps/rustgis-mobile/src/shell.rs | 3 ++- apps/rustgis/src/main.rs | 1 + crates/engine/src/prefs.rs | 4 ++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 579c296a3a..85923bb16b 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -963,7 +963,8 @@ fn read_settings() -> serde_json::Map { } /// Says what a save of the settings came to: an unreadable file set aside, or a failure, said -/// once until a save works again. +/// once until a save works again. A save made without the shared lock is said once a session, +/// whatever the save came to. fn settings_saved(result: Result, String>) { static LAST_FAILURE: Mutex> = Mutex::new(None); let mut last = LAST_FAILURE.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 2753a92ea9..82c1924eff 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -90,6 +90,7 @@ mod prefs { /// Keeps what a save came to for the window: a malformed file set aside (which also explains /// an earlier read failure still waiting), or a failure whose outcome changed since last time. + /// A save made without the shared lock is said once a session, whatever the save came to. pub fn saved(result: Result, String>) { // Saved without the lock (said once a session): two copies can then write over each // other's settings, data sources included. Asked whatever the save came to, as a file diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index e5c874394a..a44cc6d14b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -309,8 +309,8 @@ fn update_file_with( sync(p) }); // Replaced without the lock (some network folders, a lock file that isn't a regular file of - // this user's or can't be opened), as before the lock: logged once a session, as every save - // would log it again, and kept for the app to say once ([`unlocked_once`]), as two copies + // this user's or can't be opened), as before the lock: logged once a session for each + // settings file, as every save would log it again, and kept for the app to say once ([`unlocked_once`]), as two copies // saving at once can then write over each other. A write that didn't happen says nothing. if let (Some(why), true) = (unlocked, replaced) { let mut unlocked = UNLOCKED.lock().unwrap_or_else(|poisoned| poisoned.into_inner());