diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index b165cc8af6..85923bb16b 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -655,8 +655,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) { @@ -899,13 +902,41 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui let kept: Arc>>> = Arc::default(); let read = kept.clone(); services.load_pref = Some(Box::new(move |key: &str| { + // A value left to save is newer than the file's: it is what the setting is. + if let Some(value) = rustgis_engine::prefs::pending(key) { + return Some(value); + } let mut kept = read.lock().unwrap_or_else(|e| e.into_inner()); kept.get_or_insert_with(read_settings).get(key).and_then(serde_json::Value::as_str).map(str::to_string) })); + let reread = kept.clone(); services.save_pref = Some(Box::new(move |key: &str, value: &str| { + use rustgis_engine::prefs::Updated; let result = rustgis_engine::prefs::write(key, value); *kept.lock().unwrap_or_else(|e| e.into_inner()) = None; - settings_saved(result); + match result { + Ok(Updated::Saved(set_aside)) => settings_saved(Ok(set_aside)), + // A newer RustGIS's setting is never written over: said once for the key. + Ok(Updated::Newer) => { + if let Some(notice) = rustgis_engine::prefs::newer_notice_once(key) { + settings_saved(Err(notice)); + } + } + // Busy: left to save, and written by `retry_prefs` on a later frame. + Ok(Updated::Busy | Updated::Unchanged) => {} + Err(error) => settings_saved(Err(error)), + } + })); + services.retry_prefs = Some(Box::new(move |wait: std::time::Duration| { + let (results, left) = rustgis_engine::prefs::retry_pending(wait); + if !results.is_empty() { + *reread.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + results.into_iter().for_each(settings_saved); + 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, + }) })); } services @@ -932,10 +963,20 @@ 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()); + // 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; diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 15d3961ba4..c546b1dd27 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -1329,6 +1329,9 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e })), 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 89a8e2c061..82c1924eff 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -63,6 +63,8 @@ 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), } static NOTICES: Mutex> = Mutex::new(Vec::new()); @@ -88,7 +90,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. + /// 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 + // 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) => { *LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; @@ -110,6 +119,18 @@ 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) -> Option { + let (results, left) = rustgis_engine::prefs::retry_pending(wait); + results.into_iter().for_each(saved); + 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. pub fn take_notices() -> Vec { std::mem::take(&mut *notices()) @@ -135,6 +156,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( + "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)], + ), } } @@ -146,8 +171,45 @@ 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))), - save_pref: Some(Box::new(|key: &str, value: &str| saved(rustgis_engine::prefs::write(key, value)))), + // 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)), + // 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)), + 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, + // Never written over; the window says it (once) and stops trying. + Ok(Updated::Newer) => { + log::warn!("{}", rustgis_engine::prefs::newer_notice(key)); + PrefUpdate::Refused + } + Err(error) => { + saved(Err(error)); + PrefUpdate::Failed + } + } + })), secrets: Some(secrets), ..Services::default() } @@ -606,6 +668,10 @@ 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 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 @@ -1111,6 +1177,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/data/src/io.rs b/crates/data/src/io.rs index c37e234dcd..dd4c88952c 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1553,6 +1553,83 @@ pub fn write_atomic_with>( atomic_write_at(path, write) } +/// 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. 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 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 +/// 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; + 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()); + } + // 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()); + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + if created { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(mode))?; + } + #[cfg(not(all(unix, not(target_arch = "wasm32"))))] + let _ = created; + 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. @@ -6708,6 +6785,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 diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index ed247e0fa3..f16a93c4ff 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -104,35 +104,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 55503003f8..a44cc6d14b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -49,19 +49,343 @@ 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). 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 _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - write_at(&dir.join(FILE), key, value) + let done = update_file(path, key, |_| Some(value.to_string())); + 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); + // 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) => { + 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) => { + refused.insert(id, value.to_string()); + } + _ => {} + } + done +} + +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()); + +/// 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 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. +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()); + +/// 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 (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 { + 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 +/// 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>>, 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). +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(); + // Nothing left (the usual case): no lock taken, no file read. + if todo().is_empty() { + return (said, false); + } + let start = web_time::Instant::now(); + loop { + let mut busy = false; + { + // What is left is read and written under the same lock a write takes, so a value + // written meanwhile is never put back with an older one. + let _guard = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + for ((path, key), value) in todo() { + let done = update_file(&path, &key, |_| Some(value.clone())); + if done == Ok(Updated::Busy) { + busy = true; + break; + } + let id = (path.clone(), key.clone()); + // Saved or refused, it is no longer left to save; an error leaves it, to try again. + if done.is_ok() { + PENDING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&id); + } + match done { + // 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)); + } + } + // 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, + })); + } + } + } + } + if busy && start.elapsed() < wait { + // The browser keeps no preferences file, so nothing is ever left there to wait for + // (nor a thread to wait on). + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::sleep(std::time::Duration::from_millis(50)); + continue; + } + } + 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, + /// 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 +/// (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()); + 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 { + 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)), + }; + // 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 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()); + 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)); + } + } + done } /// [`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), and why: saved without it, as + /// before. + Unlockable(String), +} + +/// 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. + // 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, + 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)) => unlockable(format!("couldn't lock {}: {error}", lock_path.display())), + } +} + +#[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 +397,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 +405,43 @@ 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), + Updated::Newer => Err(newer_notice(key)), + } +} + +/// [`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())); + // 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(Value::Object(_) | Value::Array(_)) => return Ok(Updated::Newer), + _ => 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, + }; + 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")?; // The app wraps these in "Settings could not be saved reliably (…)", so they don't repeat it. @@ -98,7 +451,7 @@ fn write_at_with_bytes( }; std::fs::create_dir_all(dir).and_then(|_| rustgis_data::io::replace_atomic(path, &text)).map_err(|error| kept(error.to_string()))?; sync(path).map_err(|error| kept(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 @@ -247,6 +600,374 @@ 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::Builder::new() + .spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(200)); // test-wait: another copy holding the lock briefly + drop(held); + }) + .unwrap(); + 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(); + } + + /// 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("{}"), "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!(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": []}))); + forget_values(&path); + 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(); + } + + /// 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); + 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 + /// 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::Builder::new() + .spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(100)); // test-wait: another copy holding the lock briefly + drop(held); + }) + .unwrap(); + 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(); + } + + /// 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")); + 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")); + // 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!(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); + 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"); + // 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"))); + 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() { diff --git a/crates/engine/src/sources.rs b/crates/engine/src/sources.rs index ca2dd1922e..a440bd199a 100644 --- a/crates/engine/src/sources.rs +++ b/crates/engine/src/sources.rs @@ -45,9 +45,24 @@ 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 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. #[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)>, + /// 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. @@ -68,14 +83,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). @@ -146,6 +166,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 { @@ -196,21 +231,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); } @@ -218,7 +265,7 @@ impl Sources { read => { // A readable row past the cap is still the first of its identity, so a // later repeat of it is said as repeated, not counted past the cap again. - if let Some((_, source, _)) = &read { + if let Some((_, source, _, _)) = &read { seen.insert(identity(&source.kind, &source.address)); } s.kept.over += usize::from(read.is_some()); @@ -236,52 +283,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 } @@ -305,14 +367,21 @@ 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 { 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); } } } @@ -324,14 +393,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); } @@ -339,6 +401,157 @@ 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, + /// 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.details_changed.clear(); + self.generation += 1; + self.rebases += 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); + } + // 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 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))); + 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 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 { + 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. 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); + 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; + } + } + 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 back details this session replaced. + for (source, stored_had) in ours.iter().zip(had) { + if next.list(list).iter().any(|s| same(s, source)) { + carry(&mut next, &key_of(list, source), stored_had); + } + } + } + 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(); + 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 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) } /// Classifies the fields kept for each listed source again, against the source as it is now @@ -349,13 +562,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() { @@ -363,6 +571,32 @@ impl Sources { } } } + // Kept details passed with the row as it was read; beside details changed since (a web + // 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).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 => {} + } + } } /// Listing a source takes along the fields of a readable row of it kept past the list's limit @@ -373,16 +607,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()); } @@ -402,13 +645,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 @@ -417,16 +677,32 @@ 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 details this session changed from what it had drop the kept ones (a new name or + // 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)); 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())); + } + if changed || new { + 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. 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.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(); self.generation += 1; } @@ -438,15 +714,29 @@ 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. - if let Some(slot) = l.iter_mut().find(|r| same(r, &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 here: its details are its own, and win over a stored row's at the save. 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, &identity(&s.kind, &s.address)); + 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. @@ -463,6 +753,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) { @@ -471,6 +762,12 @@ 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.details_changed.remove(&key); + self.removed.insert(key); + } } if gone || kept_gone { self.generation += 1; @@ -478,6 +775,15 @@ 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, + } + } + fn list_mut(&mut self, list: &str) -> Result<&mut Vec, String> { match list { "favourites" => Ok(&mut self.favourites), @@ -496,6 +802,28 @@ 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); + (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()?; @@ -1448,14 +1776,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": []}"#, @@ -1466,6 +1804,321 @@ 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(); + // 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(); + assert!(error.contains("couldn't be read"), "{error}"); + 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_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 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", + 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": "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). + 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); + } + + /// 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). + #[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] + 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!({ + "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. + #[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/connectiontree.rs b/crates/ui-egui/src/connectiontree.rs index fdbbaf3915..ad0afa6960 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,64 @@ 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] + 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 be3b7eff98..645bb6af69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -563,6 +563,30 @@ 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 { + 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, + /// 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 /// supplies an asynchronous file picker (results arrive in `inbox`) and browser downloads. #[derive(Default)] @@ -592,6 +616,17 @@ 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), 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 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>, @@ -3443,6 +3478,14 @@ impl RustGisApp { } } + /// 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); + } + /// Enables foreground recovery for a phone. The store must be in the app's private storage /// and must be installed before the first frame, so it can offer the last run's copy. /// Call this after [`Self::with_services`], which replaces the entire service bundle. @@ -6460,7 +6503,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 { @@ -6682,7 +6725,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)) @@ -7109,7 +7152,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) => { @@ -7277,7 +7320,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, @@ -7559,9 +7602,16 @@ 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); + } 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); @@ -7980,6 +8030,9 @@ impl RustGisApp { { ctx.request_repaint(); } + // 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/readjob.rs b/crates/ui-egui/src/readjob.rs index 2e6a613430..131461b110 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -693,7 +693,7 @@ fn complete_here(app: &mut RustGisApp, asked: Asked, p: Value, done: Result)>, 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, + /// 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, + /// 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, + /// 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, + /// 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: +/// shared by the data sources and the app's other preferences. +#[derive(Default)] +struct Retry { + at: Option, + /// Failed tries in a row. + failures: u32, + /// The delay the last failure set. + last: std::time::Duration, +} + +impl Retry { + fn due(&self, now: web_time::Instant) -> bool { + self.at.is_none_or(|at| now >= at) + } + /// 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.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(); + } + /// 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: 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. +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 { let generation = app.session.sources.generation; @@ -61,17 +125,40 @@ 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. - 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,9 +166,205 @@ 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; + } + // 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); +} + +/// One try at saving the data sources through `update_pref`: what it came to. +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, 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 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(()) => { + let text = rebased.to_json(); + next = Some((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((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 + // 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); + // 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."); + 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.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." + ); + say_more(app, "newer-format", 1, said.to_string()); + } + _ => { + state.busy_since = None; + 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 + { + state.refusal_said = true; + app.session.warn(why); + } + } + } + Some(outcome) +} + +/// 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 + && let Some(left) = retry(deadline.saturating_duration_since(web_time::Instant::now())) + { + 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)])); + } +} + +/// 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; + } + loop { + let outcome = attempt(app); + if app.session.sources.generation == app.ui.sources_saved { + return; + } + let busy = outcome == Some(crate::PrefUpdate::Busy); + 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"), + ), + // 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}"); + app.session.warn(crate::i18n::fmt( + "The data sources changed in this session weren't saved as RustGIS closed: {why}.", + &[("why", said)], + )); + return; + } + #[cfg(not(target_arch = "wasm32"))] + std::thread::sleep(std::time::Duration::from_millis(50)); + } +} + +/// 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 { + 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()) +} + +/// Saves again the app's other preferences left to save while another copy saved its own +/// (`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.wait(now); + } + 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(); + None } } @@ -530,6 +813,107 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { #[cfg(test)] 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] + 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 delays = Vec::new(); + for _ in 0..7 { + // Due now, whatever the delay was. + app.ui.sources.retry.at = None; + save(&mut app); + 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, app.ui.sources.busy_tries), (0, 0)); + } + + /// 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}; + 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 delay = |app: &mut RustGisApp, outcome: crate::PrefUpdate| { + *answer.lock().unwrap() = outcome; + app.ui.sources.retry.at = None; + save(app); + app.ui.sources.retry.last.as_millis() + }; + 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}, cache, diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 6a9408d67c..5291d4fa2c 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -2620,6 +2620,365 @@ 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); + // 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(), ["/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, ["/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. + 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_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_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())); +} + +/// 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:?}" + ); +} + +/// 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. +#[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); + 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(); + 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:?}"); +} + +/// 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(); + // 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(); + 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] +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.