Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
277fcd5
fix(engine): saved data sources keep what a newer RustGIS wrote, and …
flight1973 Nov 19, 2026
d228b14
fix(engine): a data sources save keeps what another window stored sin…
flight1973 Nov 19, 2026
77e2541
fix(engine): settings a newer RustGIS stored stay refused without ret…
flight1973 Nov 19, 2026
60292df
Merge remote-tracking branch 'origin/main' into prep/keep-newer
flight1973 Nov 20, 2026
2640ac9
fix(engine): a data sources save keeps this window's login bindings, …
flight1973 Nov 20, 2026
a725fa0
fix(engine): a setting that fails to save stays to save, only objects…
flight1973 Nov 20, 2026
4996e56
fix(desktop): a setting left to save while another copy saves is retr…
flight1973 Nov 20, 2026
2d5f1f2
fix(engine): reading stored data sources drops kept details of a sour…
flight1973 Nov 21, 2026
752bce6
fix(engine): a lock file that can't be opened no longer stops saving,…
flight1973 Nov 21, 2026
39b6281
fix(desktop): settings retried with their own backoff, and what isn't…
flight1973 Nov 21, 2026
3ba8d5d
Merge remote-tracking branch 'origin/main' into finish/keep-newer
flight1973 Nov 28, 2026
1032ea2
fix(ui): a setting left to save during a frame's interface is tried a…
flight1973 Nov 28, 2026
ce6ce97
fix(mobile): settings left to save are tried once more as the app clo…
flight1973 Nov 28, 2026
a86f8c0
refactor(engine): time the retry at exit with web_time (#1962)
flight1973 Nov 28, 2026
b5936cf
fix(ui): a data sources save doesn't count as the add that noted a so…
flight1973 Nov 28, 2026
2069e27
fix(data): a lock file removed between finding it and opening it is c…
flight1973 Nov 28, 2026
948b551
refactor(engine): drop the unused prefs::has_pending (#1962)
flight1973 Nov 28, 2026
4138477
fix(engine): reading the stored data sources in doesn't count as noti…
flight1973 Nov 29, 2026
730ef9e
fix(ui): what a save's fresh read leaves out is said again, and a bus…
flight1973 Nov 29, 2026
7b0ef9e
fix(ui): the first data sources save doesn't repeat what loading said…
flight1973 Nov 29, 2026
77cec67
fix(ui): busy and failed data sources saves keep their own counts, an…
flight1973 Nov 29, 2026
6ac72c8
Merge remote-tracking branch 'origin/main' into finish/keep-newer
flight1973 Nov 29, 2026
4ddf5e6
fix(engine): a setting left to save doesn't write over a value anothe…
flight1973 Nov 30, 2026
a6fff98
fix(ui): a data sources save left during a frame's interface asks for…
flight1973 Nov 30, 2026
a0a83ff
revert(engine): keep queued settings as before; the same-key race is …
flight1973 Nov 30, 2026
acd03b3
fix(engine): settings saved without the shared lock are said once a s…
flight1973 Dec 1, 2026
0be7675
fix(engine): a save without the lock is said only once one happened, …
flight1973 Dec 1, 2026
c3db030
fix(engine): a file replaced without the lock is said even when its s…
flight1973 Dec 1, 2026
4a8d1d9
fix(ui): a save without the lock is said whatever the save came to, a…
flight1973 Dec 1, 2026
d3c377c
docs(engine): say where the save-without-a-lock notice and its log li…
flight1973 Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions apps/rustgis-mobile/src/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,8 +655,11 @@ fn use_picker<P: Phone + 'static>(
impl<P: Phone> eframe::App for App<P> {
/// 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) {
Expand Down Expand Up @@ -899,13 +902,41 @@ fn services(settings: bool, secrets: Option<Arc<dyn SecretStore>>) -> rustgis_ui
let kept: Arc<Mutex<Option<serde_json::Map<String, serde_json::Value>>>> = 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| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The phone never sets update_pref, so sourcespane::save takes its no-update branch (crates/ui-egui/src/sourcespane.rs, the update_pref.is_none() check) and writes the whole data sources list through this save_pref. That is the overwrite this PR removes on the desktop. If another copy holds the lock, prefs::write queues that whole list in PENDING, and retry_prefs writes it back without rebasing it over what the other copy stored, so the other copy's data sources are replaced by a stale list. load_pref also returns the queued value for data_sources until it is written. The PR body says the phone is covered by the same protection.

Fix: set update_pref here the way apps/rustgis/src/main.rs does (prefs::update mapped to PrefUpdate, with Newer as Refused), so the phone's data sources go through sourcespane::attempt and Sources::rebase.

The trigger is narrow (a second copy of RustGIS sharing the phone's config folder), so I rate the impact low. The coverage claim in the PR is still not met. Confidence about 0.7.

Category: bug

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
Expand All @@ -932,10 +963,20 @@ fn read_settings() -> serde_json::Map<String, serde_json::Value> {
}

/// 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<Option<PathBuf>, String>) {
static LAST_FAILURE: Mutex<Option<String>> = 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;
Expand Down
3 changes: 3 additions & 0 deletions apps/rustgis-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
77 changes: 75 additions & 2 deletions apps/rustgis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<Notice>> = Mutex::new(Vec::new());
Expand All @@ -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<Option<PathBuf>, 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;
Expand All @@ -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<rustgis_ui_egui::PrefsLeft> {
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<Notice> {
std::mem::take(&mut *notices())
Expand All @@ -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)],
),
}
}

Expand All @@ -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<String>| {
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()
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
102 changes: 102 additions & 0 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1553,6 +1553,83 @@ pub fn write_atomic_with<T, E: From<std::io::Error>>(
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<std::fs::File> {
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<std::fs::File> {
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.
Expand Down Expand Up @@ -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
Expand Down
34 changes: 5 additions & 29 deletions crates/data/src/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,35 +104,11 @@ fn source_lock(path: &Path) -> Result<SourceLock> {
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())),
Expand Down
12 changes: 1 addition & 11 deletions crates/data/src/source/shp/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,18 +119,8 @@ fn lease_file(path: &Path, create: bool) -> io::Result<Flock> {
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;
Expand Down
Loading
Loading