Repository navigation
fix(settings): save preferences durably and report failures #1695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
131d855
360a5a0
c15a91b
f58cfdb
c3e217b
7aa554e
ef73e6b
8362ce7
e5a25f9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,9 +34,13 @@ struct Menus { | |
| #[derive(Default)] | ||
| struct Menus {} | ||
|
|
||
| /// Preferences in `prefs.json` beside the platform's other app settings. | ||
| /// Preferences in `prefs.json` beside the platform's other app settings. Settings that can't be | ||
| /// read or saved are said in the window, not only logged: a setting that looks saved but isn't | ||
| /// would be lost silently when RustGIS closes. | ||
| mod prefs { | ||
| use std::path::PathBuf; | ||
| use std::sync::Mutex; | ||
| use std::sync::atomic::{AtomicBool, Ordering}; | ||
|
|
||
| use rustgis_ui_egui::Services; | ||
| use serde_json::{Map, Value}; | ||
|
|
@@ -45,28 +49,100 @@ mod prefs { | |
| rustgis_engine::data::dirs::config_dir() | ||
| } | ||
|
|
||
| /// A problem with the preferences file, waiting for the window to say it. | ||
| #[derive(Debug, PartialEq)] | ||
| pub enum Notice { | ||
| /// The file couldn't be read: the defaults are in use. | ||
| Unreadable(String), | ||
| /// A malformed file was moved here, and new settings started in its place. | ||
| SetAside(PathBuf), | ||
| /// A setting couldn't be saved. | ||
| NotSaved(String), | ||
| } | ||
|
|
||
| static NOTICES: Mutex<Vec<Notice>> = Mutex::new(Vec::new()); | ||
| /// Repeated equivalent failures stay quiet; changed recovery details must reach the window. | ||
| static LAST_FAILURE: Mutex<Option<String>> = Mutex::new(None); | ||
|
|
||
| /// The waiting notices; a panic while one was added doesn't lose the others. | ||
| fn notices() -> std::sync::MutexGuard<'static, Vec<Notice>> { | ||
| NOTICES.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) | ||
| } | ||
|
|
||
| /// The saved preferences, or none when the file can't be read: said once a run. | ||
| fn read() -> Map<String, Value> { | ||
| static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); | ||
| static WARNED: AtomicBool = AtomicBool::new(false); | ||
| rustgis_engine::prefs::read().unwrap_or_else(|error| { | ||
| if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) { | ||
| if !WARNED.swap(true, Ordering::Relaxed) { | ||
| log::warn!("{error}"); | ||
| notices().push(Notice::Unreadable(error)); | ||
| } | ||
| Map::new() | ||
| }) | ||
| } | ||
|
|
||
| /// Keeps what a save came to for the window: a malformed file set aside (which also explains | ||
| /// an earlier read failure still waiting), or a failure whose outcome changed since last time. | ||
| pub fn saved(result: Result<Option<PathBuf>, String>) { | ||
| match result { | ||
| Ok(set_aside) => { | ||
| *LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None; | ||
| if let Some(path) = set_aside { | ||
| log::warn!("unreadable preferences set aside as {}", path.display()); | ||
| let mut notices = notices(); | ||
| notices.retain(|n| !matches!(n, Notice::Unreadable(_))); | ||
| notices.push(Notice::SetAside(path)); | ||
| } | ||
| } | ||
| Err(error) => { | ||
| log::warn!("{error}"); | ||
| let mut last = LAST_FAILURE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); | ||
| if last.as_deref() != Some(error.as_str()) { | ||
| *last = Some(error.clone()); | ||
| notices().push(Notice::NotSaved(error)); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// The problems since the last call, oldest first. | ||
| pub fn take_notices() -> Vec<Notice> { | ||
| std::mem::take(&mut *notices()) | ||
| } | ||
|
|
||
| /// A save during logic or UI may queue a notice after this frame's drain. Ensure another | ||
| /// frame delivers it even when the user stops interacting with the window. | ||
| pub fn repaint_if_pending(ctx: &egui::Context) { | ||
| if !notices().is_empty() { | ||
| ctx.request_repaint(); | ||
| } | ||
| } | ||
|
|
||
| /// A notice's text in the current language. | ||
| pub fn text(notice: &Notice) -> String { | ||
| use rustgis_ui_egui::i18n::fmt; | ||
| match notice { | ||
| Notice::Unreadable(error) => { | ||
| fmt("Your settings couldn't be read ({error}), so RustGIS is using its defaults.", &[("error", error)]) | ||
| } | ||
| Notice::SetAside(path) => fmt( | ||
| "Your settings couldn't be read, so RustGIS started new ones. The old settings file was kept as {path}.", | ||
| &[("path", &path.display().to_string())], | ||
| ), | ||
| Notice::NotSaved(error) => fmt("Settings could not be saved reliably ({error}).", &[("error", error)]), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Quality (medium-low confidence): the not-saved notice drops the consequence that the module doc above it promises to convey. The doc comment on this module says a setting that looks saved but isn't "would be lost silently when RustGIS closes". For a hard failure ( The durability case (the file was replaced but the directory sync failed) is a different outcome, and the wording here fits it. The two outcomes share one I'm not treating this as blocking. Raising it because the notice is the only signal the user gets.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The notice includes the operation's error, which distinguishes a failed replacement from an already-visible replacement whose durability is unconfirmed. Splitting the presentation into separate failed-write and unconfirmed-durability notices is left for the release quality pass, as a wording improvement. A blanket “lost when RustGIS closes” consequence would be inaccurate for the latter case. |
||
| } | ||
| } | ||
|
|
||
| /// The desktop's keychain and the preference hooks over `prefs.json`; saves report through | ||
| /// [`saved`]. | ||
| pub fn services() -> Services { | ||
| let secrets: std::sync::Arc<dyn rustgis_engine::data::secrets::SecretStore> = | ||
| std::sync::Arc::new(rustgis_keychain::Keychain::default()); | ||
| // 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| { | ||
| if let Err(error) = rustgis_engine::prefs::write(key, value) { | ||
| log::warn!("{error}"); | ||
| } | ||
| })), | ||
| save_pref: Some(Box::new(|key: &str, value: &str| saved(rustgis_engine::prefs::write(key, value)))), | ||
| secrets: Some(secrets), | ||
| ..Services::default() | ||
| } | ||
|
|
@@ -276,15 +352,22 @@ impl eframe::App for App { | |
| } | ||
| self.0.ui.titlebar = titlebar; | ||
| } | ||
| // Settings that couldn't be read or saved, since the last frame. | ||
| for notice in prefs::take_notices() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bug (medium confidence): a notice queued during a frame can stay hidden until another frame happens. Saves run inside Suggested fix: request a repaint when notices are waiting. Add a Worth checking in the headless
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in c3e217b. Both desktop logic and UI request another frame when preference notices remain queued after their work. A failed save is therefore delivered without another input event. The regression settles an idle context, checks that a pending failure requests a frame, then checks that draining it lets the context settle again. Focused regression, full native CI, WebAssembly and hooks passed. |
||
| let text = prefs::text(¬ice); | ||
| self.0.session.notify(text, true); | ||
| } | ||
| self.0.logic(ctx); | ||
| #[cfg(target_os = "macos")] | ||
| self.menus(ctx); | ||
| if self.0.quit_requested { | ||
| ctx.send_viewport_cmd(egui::ViewportCommand::Close); | ||
| } | ||
| prefs::repaint_if_pending(ctx); | ||
| } | ||
| fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { | ||
| self.0.ui(ui); | ||
| prefs::repaint_if_pending(ui.ctx()); | ||
| } | ||
| #[cfg(not(target_os = "macos"))] | ||
| fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) { | ||
|
|
@@ -620,7 +703,7 @@ fn main() -> eframe::Result { | |
| #[cfg(test)] | ||
| #[allow(clippy::unwrap_used, clippy::panic)] | ||
| mod tests { | ||
| use super::{backends, crash, flag, running}; | ||
| use super::{backends, crash, flag, prefs, running}; | ||
| use eframe::wgpu::Backends; | ||
|
|
||
| #[test] | ||
|
|
@@ -711,6 +794,58 @@ mod tests { | |
| assert!(super::recovery_store(Some(dir.join("fresh"))).is_ok()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn settings_that_cannot_be_saved_are_said_once_until_saving_works() { | ||
| use prefs::Notice; | ||
| // Clean saves say nothing. | ||
| prefs::saved(Ok(None)); | ||
| assert_eq!(prefs::take_notices(), []); | ||
| // An idle window must get another frame when a save queues a notice late in a frame. | ||
| let ctx = egui::Context::default(); | ||
| let frame = || { | ||
| let mut output = ctx.run_ui(egui::RawInput::default(), |ui| prefs::repaint_if_pending(ui.ctx())); | ||
| output.textures_delta.clear(); | ||
| }; | ||
| for _ in 0..4 { | ||
| frame(); | ||
| } | ||
| assert!(!ctx.has_requested_repaint(), "clean preferences keep the window idle"); | ||
| // A full disk: said once, not for every setting that follows. | ||
| prefs::saved(Err("could not save preferences: no space left".into())); | ||
| prefs::saved(Err("could not save preferences: no space left".into())); | ||
| frame(); | ||
| assert!(ctx.has_requested_repaint(), "the pending failure requests its delivery frame"); | ||
| assert_eq!(prefs::take_notices(), [Notice::NotSaved("could not save preferences: no space left".into())]); | ||
| for _ in 0..4 { | ||
| frame(); | ||
| } | ||
| assert!(!ctx.has_requested_repaint(), "draining the notice lets the window settle"); | ||
| // Recovery can advance during a failure episode: do not retain obsolete instructions. | ||
| let changed = | ||
| "preferences were replaced, but their durability could not be confirmed; malformed preferences were kept at prefs.json.bad"; | ||
| prefs::saved(Err(changed.into())); | ||
| assert_eq!(prefs::take_notices(), [Notice::NotSaved(changed.into())]); | ||
| prefs::saved(Err(changed.into())); | ||
| assert!(prefs::take_notices().is_empty(), "equivalent recovery outcomes stay quiet"); | ||
| // Once a save works, the next failure is news again. | ||
| prefs::saved(Ok(None)); | ||
| prefs::saved(Err("could not save preferences: read-only".into())); | ||
| assert_eq!(prefs::take_notices(), [Notice::NotSaved("could not save preferences: read-only".into())]); | ||
| prefs::saved(Ok(None)); | ||
| // A malformed file set aside says where it went. | ||
| let bad = std::path::PathBuf::from("prefs.json.bad"); | ||
| prefs::saved(Ok(Some(bad.clone()))); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Quality / test coverage (AGENTS.md "test both ways", medium-low confidence): the new startup notice is not covered. Nothing exercises A short addition would close it: push an
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is additional coverage for working notice behavior: startup queues Unreadable, and saved(Ok(Some(path))) removes it before queuing SetAside. Existing tests cover clean saves, failed-save suppression and recovery-path delivery. The additional queued-startup-notice assertion is left for the release quality pass. |
||
| assert_eq!(prefs::take_notices(), [Notice::SetAside(bad.clone())]); | ||
| let text = prefs::text(&Notice::SetAside(bad)); | ||
| assert!(text.contains("prefs.json.bad"), "{text}"); | ||
| // Both a failed replacement and an unconfirmed final flush give an accurate notice. | ||
| for error in ["could not save preferences: read-only", "preferences were replaced, but their durability could not be confirmed"] { | ||
| let text = prefs::text(&Notice::NotSaved(error.into())); | ||
| assert!(text.contains("Settings could not be saved reliably") && text.contains(error), "{text}"); | ||
| assert!(!text.contains("changes last only until"), "{text}"); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn crash_times_are_utc_dates() { | ||
| assert_eq!(crash::utc(0), "1970-01-01 00:00:00"); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AGENTS.md (medium confidence): the failed-save notice has no count.
AGENTS.md asks for "one notice per kind with a count" and for saying "what, how much and where". This notice is deduplicated to one per run of failures, but it does not say how many settings weren't saved, or which ones. The count could be kept in
FAILING(for example anAtomicU32of skipped saves) and reported when a save finally works, or included in the notice text. The test on lines 146–166 should then assert the count.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The warning covers the whole settings store: changes last only until the app closes, while the existing file is preserved. Repeated failed attempts can update the same key, so their count would not tell the user how many distinct settings are unsaved. Keeping one error per failure episode avoids repeated warnings without presenting a misleading loss count.