platform-w8: net change of 2 commits

- platform-w8: written by an agent
- platform-w8: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 17:25:03 +00:00
parent 8805761140
commit 2bbd01087b
14 changed files with 776 additions and 67 deletions
+10
View File
@@ -18,6 +18,7 @@ testing = []
[dependencies]
craft-atomic = { workspace = true }
craft-host = { workspace = true }
log = { workspace = true }
serde = { version = "1", features = ["derive"] }
serde_json = { workspace = true }
toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] }
@@ -27,6 +28,15 @@ web-time = "1.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
dirs = "7"
# `LocalStorageFiles`: the browser's localStorage.
[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3", features = ["Storage", "Window"] }
[dev-dependencies]
craft-settings = { path = ".", features = ["testing"] }
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
tempfile = "3"
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = "0.3"
+54 -11
View File
@@ -12,7 +12,8 @@ Atomic writes come from [`craft-atomic`](../atomic/README.md).
- Never crashes: every error comes back in a `LoadReport`, `TickResult` or `Result`; the crate
denies `unwrap`, `expect`, `panic` and friends, and the workspace forbids `unsafe`.
- No application code: it depends only on `craft-atomic`, `serde`, `toml_edit` and `dirs`, and
- No application code: it depends only on `craft-atomic`, `serde`, `toml_edit`, `web-time`,
`log`, `dirs` (native) and `web-sys` (browser), and
knows nothing about any app's settings, defaults, UI or file formats. Apps supply their type
and their own parsers for older files.
- No UI: it reports; the application decides what to show.
@@ -74,13 +75,14 @@ let scale = store.get().appearance.ui_scale;
store.update(|p| p.appearance.theme = "dark".into());
// Every frame: saves 500 ms after the last change, retries failures with backoff.
let tick = store.tick(std::time::Instant::now());
// `web_time::Instant` is `std::time::Instant` on native targets and also works in a browser.
let tick = store.tick(web_time::Instant::now());
if let SaveStatus::Failed(err) = &tick.status {
// show it; the store keeps retrying
}
if let Some(deadline) = tick.next_deadline {
// eframe only repaints on input, so ask for one at the deadline or an idle app never saves:
ctx.request_repaint_after(deadline.saturating_duration_since(std::time::Instant::now()));
ctx.request_repaint_after(deadline.saturating_duration_since(web_time::Instant::now()));
}
// On exit.
@@ -150,6 +152,30 @@ Values are merged into the document that was loaded: tables merge key by key, ar
scalars are replaced whole, comments, key order, unknown keys and each replaced line's trailing
comment stay. Each write goes through `craft-atomic`, so a failed save leaves the old file intact.
When another process changed the file since this store last read or wrote it, only this store's
own changes are merged into the file on disk, item by item. `Settings::merge_rule(path)` names
the rule for each key path; the default is `MergeRule::ByKey`:
| Rule | When both processes changed the item |
|---|---|
| `ByKey` | A table merges key by key, each key by its own rule; an array or a scalar takes this store's value. |
| `Whole` | This store's value replaces the other's whole, so a window's place and size never come from two processes. |
| `Recent { cap, key }` | A most-recently-used list: entries this store added or used again lead, entries it removed stay removed, the other's follow in their order, cut to `cap`. |
| `Entries { key }` | A list of user entries: additions from both are kept, removals from both hold, an entry both changed takes this store's version, and an added entry follows the entry before it. |
`key` names a list entry; an entry it answers `None` for is dropped, so a value the settings type
cannot read is not carried into the merged list.
```rust,ignore
fn merge_rule(path: &[&str]) -> MergeRule {
match path {
["recent"] => MergeRule::Recent { cap: 10, key: |v| v.as_str().map(str::to_owned) },
["window"] => MergeRule::Whole,
_ => MergeRule::ByKey,
}
}
```
Just before each write the store reads the file and compares its **contents** (not its mtime,
which can stay the same on FAT, HFS+ or network shares) with what it last read or wrote:
@@ -163,12 +189,14 @@ which can stay the same on FAT, HFS+ or network shares) with what it last read o
### Concurrency contract
Saving is **best effort, last writer wins**, not multi-process locking. Hand edits and a
second instance's unknown keys and comments are preserved as above, but two processes saving
within the same moment can still race: the later write wins on known keys. Settings are small
and change rarely, so this is the contract apps should assume. An app that needs strict
coordination between processes (for example a launcher writing another app's settings) should
add its own lock around `flush()`.
Each save holds an advisory lock, `.config.toml.lock` beside the file
(`SettingsFiles::lock`), from the disk check to the write, so two processes saving at the same
moment (logging out closes every window together) take turns: the later one sees and merges what
the earlier one wrote. A save waits at most 2 seconds for the lock; past that, or when the lock
file cannot be opened, it logs a warning and saves without it, so a stuck process never stops
another from saving. Hand edits and a second instance's unknown keys and comments are preserved
as above. A read (`SettingsStore::read`) takes no lock and writes nothing. Files with nothing to
lock, such as browser storage, keep the default `lock`, which holds none.
## Validation
@@ -181,6 +209,21 @@ cargo test --workspace
cargo check --target wasm32-unknown-unknown -p craft-settings
```
The tests in `tests/` write only to temporary folders and never touch the real config folder.
The native tests in `tests/` write only to temporary folders and never touch the real config
folder. `tests/local_storage.rs` runs only in a browser: `cargo test -p craft-settings --target
wasm32-unknown-unknown` with a matching `wasm-bindgen-test-runner` as the target's runner.
On `wasm32` the `Settings` trait, the document helpers, the error types, `Remembered` and `presets` (`PresetFolder`, with entries kept in the app's settings sections) are available.
On `wasm32` the whole store is available: `SettingsStore`, `OpenOptions`, `SharedSettings`,
`paths` (`Location`, `Probe`, `Resolved`), `migrate` and `LegacyFile`, the `Settings` trait, the
document helpers, the error types, `Remembered`, `presets` (`PresetFolder`, with entries kept in
the app's settings sections) and `recovery::backup_path`. Native only: `DiskFiles`, `profiles`,
the rest of `recovery` and `testing`.
In a browser `OpenOptions::default()` stores files in localStorage through
`LocalStorageFiles::new(4 << 20)`: each file is one item keyed by its path, so
`Location::Dir(dir)` names the key prefix, and `Location::Auto` keeps settings in memory, as a
browser has no folders. A stored item over the cap reads as absent (the store uses defaults and
the next save replaces it); a write over the cap fails and leaves the old item. A damaged item is
moved aside to `config.aside-<n>.toml`, as `std::time::SystemTime` does not work in a browser
to give the native timestamp name. A `LegacyFile` is read through the same files, so an app's old localStorage item imports
into a fresh store.
+211 -18
View File
@@ -1,6 +1,8 @@
//! TOML document handling: `schema_version`, per-section parsing and comment-preserving merges.
use toml_edit::{DocumentMut, Item, Table, TableLike, Value};
use std::collections::{HashMap, HashSet};
use toml_edit::{Array, ArrayOfTables, DocumentMut, Item, Table, TableLike, Value};
use crate::Settings;
use crate::error::SectionError;
@@ -10,18 +12,23 @@ use crate::error::SectionError;
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum MergeRule {
/// Key by key: today's merge.
/// A table merges key by key, each key by its own rule; an array or a scalar is replaced whole.
ByKey,
/// The item as a whole: ours replaces theirs.
/// The item as a whole: when both instances changed it, ours replaces theirs, so a table is never a mix of two
/// instances' keys (a window's size from one and its place from the other).
Whole,
/// A most-recently-used list of at most `cap` entries; `key` names an entry for de-duplication.
/// A most-recently-used list, most recent first: the entries this instance added or used again go to the
/// front, entries it removed stay removed, the other instance's keep their order behind, and the list is cut
/// to `cap`. An entry whose `key` is `None` is dropped.
Recent {
/// The most entries kept.
cap: usize,
/// The identity of an entry; `None` for an entry without one.
key: fn(&toml_edit::Value) -> Option<String>,
},
/// A list of entries merged by identity: `key` names an entry.
/// A list of user entries merged by identity: entries either instance added are kept, entries either removed
/// stay removed, an entry both changed takes ours, and an entry added on one side follows the entry before it
/// there. Entries with the same key are told apart by their order. An entry whose `key` is `None` is dropped.
Entries {
/// The identity of an entry; `None` for an entry without one.
key: fn(&toml_edit::Value) -> Option<String>,
@@ -270,9 +277,12 @@ fn merge_tables(into: &mut dyn TableLike, from: &dyn TableLike) {
/// - `ours == base`: nothing changes; `theirs` is kept.
/// - `base` counts as `T` reads it: a key it lacks holds its default, so a section an older file
/// did not have is not taken as all of this instance's change.
/// - Tables merge key by key: a key in both `base` and `theirs` recurses; a key removed on disk
/// and unchanged here stays removed; any other key of `ours` is written (`ours` wins at the
/// leaf, scalars and arrays replaced whole); a key `base` had and `ours` dropped is removed.
/// - Each changed item merges by the rule [`Settings::merge_rule`] names for its key path. Under
/// [`MergeRule::ByKey`], the default, tables merge key by key: a key in both `base` and `theirs`
/// recurses; a key removed on disk and unchanged here stays removed; any other key of `ours` is
/// written (`ours` wins at the leaf, scalars and arrays replaced whole); a key `base` had and
/// `ours` dropped is removed. [`MergeRule::Whole`], [`MergeRule::Recent`] and
/// [`MergeRule::Entries`] say how their item merges instead.
/// - Comments and formatting of `theirs` stay, as in [`merge_into`].
///
/// When the disk's `schema_version` is newer than `base`'s, `base` is migrated to it with
@@ -311,22 +321,23 @@ fn migrated_base<T: Settings>(base: &DocumentMut, theirs: &DocumentMut) -> Docum
migrated
}
// P3(platform-w8): pf.C-S1 (`path` is carried but no rule is asked yet)
/// Merges the keys of `ours` that changed since `base` into `theirs`; `path` is the key path of the tables, so
/// each item's [`MergeRule`] can be asked.
fn merge_changed_tables<T: Settings>(base: &dyn TableLike, ours: &dyn TableLike, theirs: &mut dyn TableLike, path: &mut Vec<String>) {
for (key, our_item) in ours.iter() {
path.push(key.to_owned());
match (base.get(key), theirs.get_mut(key)) {
(Some(base_item), Some(their_item)) => merge_changed_items::<T>(base_item, our_item, their_item, path),
// Removed on disk and unchanged here: it stays removed.
(Some(base_item), None) if same_item(base_item, our_item) => {}
// A key neither `base` nor `T`'s defaults have (a map entry both instances added): every leaf of ours is ours.
(None, Some(their_item)) => match (their_item.as_table_like_mut(), our_item.as_table_like()) {
(Some(their_table), Some(our_table)) => merge_changed_tables::<T>(&Table::new(), our_table, their_table, path),
_ => replace_item(their_item, our_item),
},
// A key neither `base` nor `T`'s defaults have (a map entry both instances added): merged against nothing,
// so under `ByKey` every leaf of ours is ours and a list keeps the entries of both.
(None, Some(their_item)) => merge_changed_items::<T>(&empty_like(our_item), our_item, their_item, path),
(_, None) => {
theirs.insert(key, our_item.clone());
}
}
path.pop();
}
let removed: Vec<String> = base.iter().map(|(k, _)| k).filter(|k| !ours.contains_key(k)).map(str::to_owned).collect();
for key in removed {
@@ -334,17 +345,199 @@ fn merge_changed_tables<T: Settings>(base: &dyn TableLike, ours: &dyn TableLike,
}
}
// P3(platform-w8): pf.C-S1
/// Merges the item at `path` by its [`MergeRule`] when ours changed it since `base`.
fn merge_changed_items<T: Settings>(base: &Item, ours: &Item, theirs: &mut Item, path: &mut Vec<String>) {
if same_item(base, ours) {
return;
}
match (base.as_table_like(), ours.as_table_like(), theirs.as_table_like_mut()) {
(Some(base), Some(ours), Some(theirs)) => merge_changed_tables::<T>(base, ours, theirs, path),
_ => replace_item(theirs, ours),
let rule = {
let keys: Vec<&str> = path.iter().map(String::as_str).collect();
T::merge_rule(&keys)
};
match rule {
MergeRule::ByKey => match (base.as_table_like(), ours.as_table_like(), theirs.as_table_like_mut()) {
(Some(base), Some(ours), Some(theirs)) => merge_changed_tables::<T>(base, ours, theirs, path),
_ => replace_item(theirs, ours),
},
MergeRule::Whole => replace_item(theirs, ours),
MergeRule::Recent { cap, key } => merge_lists(base, ours, theirs, |b, o, t| merge_recent(b, o, t, cap, key)),
MergeRule::Entries { key } => merge_lists(base, ours, theirs, |b, o, t| merge_entries(b, o, t, key)),
}
}
/// An empty item of `item`'s kind: the base of a key this instance and another both added.
fn empty_like(item: &Item) -> Item {
match item {
Item::ArrayOfTables(_) => Item::ArrayOfTables(ArrayOfTables::new()),
Item::Value(Value::Array(_)) => Item::Value(Value::Array(Array::new())),
_ if item.is_table_like() => Item::Table(Table::new()),
_ => Item::None,
}
}
/// Merges three lists with `merge`, writing the result over `theirs` in the shape of `ours`. When `theirs` is not a
/// list (a hand edit put something else there), ours replaces it; the base of a list `base` lacks is empty.
fn merge_lists(base: &Item, ours: &Item, theirs: &mut Item, merge: impl FnOnce(&[Value], &[Value], &[Value]) -> Vec<Value>) {
let (Some(our_list), Some(their_list)) = (list(ours), list(theirs)) else {
replace_item(theirs, ours);
return;
};
let base_list = list(base).unwrap_or_default();
let merged = list_item(ours, merge(&base_list, &our_list, &their_list));
replace_item(theirs, &merged);
}
/// The entries of an array or an array of tables, each as a value (a table as an inline table).
fn list(item: &Item) -> Option<Vec<Value>> {
match item {
Item::Value(Value::Array(array)) => Some(array.iter().cloned().collect()),
Item::ArrayOfTables(tables) => Some(tables.iter().map(|t| Value::InlineTable(t.clone().into_inline_table())).collect()),
_ => None,
}
}
/// `values` as an item shaped like `shape`: an array of tables stays one while every entry is a table.
fn list_item(shape: &Item, values: Vec<Value>) -> Item {
if shape.is_array_of_tables() {
let tables: Option<Vec<Table>> = values.iter().map(|v| v.as_inline_table().map(|t| t.clone().into_table())).collect();
if let Some(tables) = tables {
let mut array = ArrayOfTables::new();
for table in tables {
array.push(table);
}
return Item::ArrayOfTables(array);
}
}
let mut array: Array = values.into_iter().collect();
// Entries come from two documents with their own spacing; lay the merged list out afresh.
array.fmt();
Item::Value(Value::Array(array))
}
/// The identity of a list entry; `None` for an entry that has none, which a merge drops.
type EntryKey = fn(&Value) -> Option<String>;
/// The entries of `list` that have a key, with it. An entry without one cannot be matched across the lists and is
/// dropped, so a value the settings type cannot read is not carried into the merged list.
fn keyed(list: &[Value], key: EntryKey) -> Vec<(String, Value)> {
list.iter().filter_map(|v| Some((key(v)?, v.clone()))).collect()
}
/// A most-recently-used list: the entries this instance put at the front of `ours` ([`touched_len`]), then those
/// of `theirs` it did not remove (an entry of `base` no longer in `ours`), without duplicates and at most `cap`.
fn merge_recent(base: &[Value], ours: &[Value], theirs: &[Value], cap: usize, key: EntryKey) -> Vec<Value> {
let (base, ours, theirs) = (keyed(base, key), keyed(ours, key), keyed(theirs, key));
let has = |list: &[(String, Value)], k: &str| list.iter().any(|(x, _)| x == k);
let removed = |k: &str| has(&base, k) && !has(&ours, k);
let touched = &ours[..touched_len(&base, &ours)];
let mut merged: Vec<(String, Value)> = Vec::new();
for (k, v) in touched.iter().chain(theirs.iter().filter(|(k, _)| !removed(k))) {
if merged.len() >= cap {
break;
}
if !has(&merged, k) {
merged.push((k.clone(), v.clone()));
}
}
merged.into_iter().map(|(_, v)| v).collect()
}
/// How many of `ours`'s first entries this instance added or used again. Each use moves an entry to the front of a
/// recent list, so what it left alone is a tail of `ours` in `base`'s order: the longest such tail is untouched, and
/// everything before it (new entries, and entries that moved ahead of one loaded before them) was touched. A use
/// that leaves the order as loaded (the first entry used again) cannot be told from no use, and merges as none.
fn touched_len(base: &[(String, Value)], ours: &[(String, Value)]) -> usize {
let mut end = base.len();
for (i, (k, _)) in ours.iter().enumerate().rev() {
match base[..end].iter().rposition(|(b, _)| b == k) {
Some(at) => end = at,
None => return i + 1,
}
}
0
}
/// A list entry: its key, and how many entries before it have the same key, so equal entries stay apart by order.
type EntryId = (String, usize);
/// The keyed entries of `list` by [`EntryId`], in order.
fn entry_ids(list: &[Value], key: EntryKey) -> Vec<(EntryId, Value)> {
let mut seen: HashMap<String, usize> = HashMap::new();
keyed(list, key)
.into_iter()
.map(|(k, v)| {
let n = seen.entry(k.clone()).or_default();
let id = (k, *n);
*n += 1;
(id, v)
})
.collect()
}
/// The three lists of an `Entries` merge, by entry.
struct EntryLists {
base: HashMap<EntryId, Value>,
ours: HashMap<EntryId, Value>,
theirs: HashMap<EntryId, Value>,
}
impl EntryLists {
/// The merged value of entry `id`: added or changed here wins, removed here stays removed, and an entry left
/// alone here is what `theirs` holds (gone when the other instance removed it).
fn value(&self, id: &EntryId) -> Option<&Value> {
match (self.base.get(id), self.ours.get(id), self.theirs.get(id)) {
(Some(b), Some(o), t) if same_value(b, o) => t,
(_, Some(o), _) => Some(o),
(Some(_), None, _) => None,
(None, None, t) => t,
}
}
}
/// A list of user entries, entry by entry: entries either instance added are kept, entries either removed stay
/// removed, and an entry this instance changed takes its version. The order is ours when this instance reordered
/// the entries it loaded, else theirs; an entry only the other list has goes after the nearest entry before it there
/// that the merge keeps (at the start when there is none).
fn merge_entries(base: &[Value], ours: &[Value], theirs: &[Value], key: EntryKey) -> Vec<Value> {
let (base_ids, ours_ids, theirs_ids) = (entry_ids(base, key), entry_ids(ours, key), entry_ids(theirs, key));
let ids = |list: &[(EntryId, Value)]| -> Vec<EntryId> { list.iter().map(|(id, _)| id.clone()).collect() };
let (base_order, ours_order, theirs_order) = (ids(&base_ids), ids(&ours_ids), ids(&theirs_ids));
let lists = EntryLists {
base: base_ids.into_iter().collect(),
ours: ours_ids.into_iter().collect(),
theirs: theirs_ids.into_iter().collect(),
};
let common = |order: &[EntryId], other: &HashMap<EntryId, Value>| -> Vec<EntryId> {
order.iter().filter(|id| other.contains_key(*id)).cloned().collect()
};
let reordered = common(&ours_order, &lists.base) != common(&base_order, &lists.ours);
let (first, second) = if reordered { (&ours_order, &theirs_order) } else { (&theirs_order, &ours_order) };
anchored(&lists, first, second)
}
/// `first`'s kept entries in order, each followed by the entries only `second` has that come after it there.
fn anchored(lists: &EntryLists, first: &[EntryId], second: &[EntryId]) -> Vec<Value> {
let in_first: HashSet<&EntryId> = first.iter().collect();
let kept: HashSet<&EntryId> = first.iter().filter(|id| lists.value(id).is_some()).collect();
let mut after: HashMap<Option<&EntryId>, Vec<&EntryId>> = HashMap::new();
let mut anchor = None;
for id in second {
if kept.contains(id) {
anchor = Some(id);
} else if !in_first.contains(id) && lists.value(id).is_some() {
after.entry(anchor).or_default().push(id);
}
}
let mut merged = Vec::new();
let mut emit = |ids: &[&EntryId]| merged.extend(ids.iter().filter_map(|id| lists.value(id).cloned()));
emit(after.get(&None).map_or(&[], Vec::as_slice));
for id in first.iter().filter(|id| kept.contains(id)) {
emit(&[id]);
emit(after.get(&Some(id)).map_or(&[], Vec::as_slice));
}
merged
}
/// Replaces `theirs` with `ours`, keeping the spacing and trailing comment of a replaced value.
fn replace_item(theirs: &mut Item, ours: &Item) {
let mut fresh = ours.clone();
+32 -2
View File
@@ -83,12 +83,42 @@ impl SettingsFiles for DiskFiles {
crate::recovery::check_writable(dir)
}
/// An advisory lock on `.<file>.lock` beside `path`, so two processes saving at once (logging out closes every
/// window together) take turns at checking, merging and replacing the file instead of one losing the other's
/// changes. `None` (save unlocked) when the lock file cannot be opened or is not free within [`LOCK_WAIT`].
fn lock(&self, path: &Path) -> Option<Box<dyn Any + Send>> {
let _ = path;
todo!("pf.C-S3")
let name = path.file_name().map_or_else(|| "config.toml".into(), |n| n.to_string_lossy().into_owned());
let lock = path.with_file_name(format!(".{name}.lock"));
let file = match std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&lock) {
Ok(file) => file,
Err(e) => {
log::warn!("settings: cannot open {}, saving without it: {e}", lock.display());
return None;
}
};
let start = std::time::Instant::now();
loop {
match file.try_lock() {
Ok(()) => return Some(Box::new(file)),
Err(std::fs::TryLockError::WouldBlock) if start.elapsed() < LOCK_WAIT => std::thread::sleep(LOCK_POLL),
Err(e) => {
log::warn!("settings: {} is held, saving without it: {e}", lock.display());
return None;
}
}
}
}
}
/// How long a save waits for another process's save to finish before going ahead anyway: a save takes
/// milliseconds, and a process stuck holding the lock must not stop this one from saving.
#[cfg(not(target_arch = "wasm32"))]
const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// How often a waiting save tries the lock again.
#[cfg(not(target_arch = "wasm32"))]
const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(10);
/// New files are owner-only; on a replace `craft-atomic` keeps the existing file's mode.
#[cfg(all(unix, not(target_arch = "wasm32")))]
fn restrict_permissions(file: &std::fs::File) -> io::Result<()> {
+65 -12
View File
@@ -5,45 +5,98 @@ use std::path::{Path, PathBuf};
use super::SettingsFiles;
/// How many `.aside-<n>` names `move_aside` tries before giving up.
const MAX_ASIDE: u32 = 1000;
/// Browser settings storage under a byte cap. A stored value over the cap reads as absent, so the store uses
/// defaults, and is not reported as damaged. The backup is keyed by
/// [`backup_path`](crate::recovery::backup_path).
///
/// Each file is one localStorage item keyed by the path's text, so [`Location::Dir`](crate::Location::Dir) names
/// the key prefix. The storage is looked up on every call rather than held, which keeps the type `Send + Sync`; a
/// browser page has one thread, so nothing is shared across threads.
#[derive(Clone, Copy, Debug)]
pub struct LocalStorageFiles {
cap: usize,
}
impl LocalStorageFiles {
/// Storage that ignores a stored value over `cap` bytes.
/// Storage that ignores a stored value over `cap` bytes and refuses to write one.
pub fn new(cap: usize) -> Self {
let _ = cap;
todo!("pf.C-S4")
Self { cap }
}
/// Writes `text` under `key` when it fits the cap; over it, the old item stays and the write fails.
fn put(&self, storage: &web_sys::Storage, key: &str, text: &str) -> io::Result<()> {
if text.len() > self.cap {
return Err(io::Error::new(
io::ErrorKind::FileTooLarge,
format!("{} bytes is over the {} byte limit for browser settings", text.len(), self.cap),
));
}
storage.set_item(key, text).map_err(|e| io::Error::other(format!("localStorage refused the write: {e:?}")))
}
}
/// The page's localStorage; an error when the browser has none or blocks it (private modes, a sandboxed frame).
fn storage() -> io::Result<web_sys::Storage> {
let window = web_sys::window().ok_or_else(|| io::Error::new(io::ErrorKind::Unsupported, "no browser window"))?;
match window.local_storage() {
Ok(Some(storage)) => Ok(storage),
Ok(None) => Err(io::Error::new(io::ErrorKind::Unsupported, "localStorage is not available")),
Err(e) => Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("localStorage is blocked: {e:?}"))),
}
}
/// The item key of `path`.
fn key(path: &Path) -> String {
path.to_string_lossy().into_owned()
}
fn get(storage: &web_sys::Storage, key: &str) -> io::Result<Option<String>> {
storage.get_item(key).map_err(|e| io::Error::other(format!("localStorage refused the read: {e:?}")))
}
impl SettingsFiles for LocalStorageFiles {
fn read(&self, path: &Path) -> io::Result<Option<String>> {
let _ = (self.cap, path);
todo!("pf.C-S4")
let text = get(&storage()?, &key(path))?;
// An oversized item is ignored rather than reported as damaged: the next save replaces it.
Ok(text.filter(|text| text.len() <= self.cap))
}
fn write(&self, path: &Path, text: &str) -> io::Result<()> {
let _ = (path, text);
todo!("pf.C-S4")
self.put(&storage()?, &key(path), text)
}
/// Copies the item to `<stem>.aside-<n>.<ext>` and removes it. A counter stands in for the native rule's
/// timestamp, which the browser's `SystemTime` cannot give.
fn move_aside(&self, path: &Path) -> io::Result<PathBuf> {
let _ = path;
todo!("pf.C-S4")
let storage = storage()?;
let from = key(path);
let Some(text) = get(&storage, &from)? else {
return Err(io::Error::new(io::ErrorKind::NotFound, "nothing to move aside"));
};
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("config");
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml");
for n in 1..=MAX_ASIDE {
let target = path.with_file_name(format!("{stem}.aside-{n}.{ext}"));
if get(&storage, &key(&target))?.is_some() {
continue;
}
// The damaged text is kept whole even over the cap: it is the user's to recover.
storage.set_item(&key(&target), &text).map_err(|e| io::Error::other(format!("localStorage refused the copy: {e:?}")))?;
storage.remove_item(&from).map_err(|e| io::Error::other(format!("localStorage refused the removal: {e:?}")))?;
return Ok(target);
}
Err(io::Error::new(io::ErrorKind::AlreadyExists, "too many damaged copies"))
}
fn write_backup(&self, path: &Path, text: &str) -> io::Result<()> {
let _ = (path, text);
todo!("pf.C-S4")
self.put(&storage()?, &key(&crate::recovery::backup_path(path)), text)
}
fn check_writable(&self, dir: &Path) -> io::Result<()> {
let _ = dir;
todo!("pf.C-S4")
storage().map(|_| ())
}
}
+3 -1
View File
@@ -32,7 +32,7 @@
//!
//! let (mut store, report) = SettingsStore::<Prefs>::open(Location::Auto);
//! store.update(|p| p.appearance.theme = "dark".into());
//! // Call `store.tick(Instant::now())` every frame and `store.flush()` on exit.
//! // Call `store.tick(web_time::Instant::now())` every frame and `store.flush()` on exit.
//! ```
#![warn(missing_docs)]
@@ -56,6 +56,8 @@ pub use document::MergeRule;
pub use error::{LoadReport, MigrateError, ReadOnlyReason, SaveStatus, SectionError, SettingsError, Source, TickResult};
#[cfg(not(target_arch = "wasm32"))]
pub use files::DiskFiles;
#[cfg(target_arch = "wasm32")]
pub use files::LocalStorageFiles;
pub use files::SettingsFiles;
pub use migrate::LegacyFile;
pub use paths::{Location, Portable, Probe, Resolved, Rule};
+4 -5
View File
@@ -75,12 +75,11 @@ impl<T> std::fmt::Debug for LegacyFile<T> {
}
}
/// Tries each legacy file in order and returns the first one that parses, with the values it
/// reset and its path.
/// Tries each legacy file in order, read through `files` (the store's, so a browser store reads its old
/// localStorage item), and returns the first one that parses, with the values it reset and its path.
pub fn import_legacy<T>(files: &dyn SettingsFiles, legacy: &[LegacyFile<T>]) -> Option<Imported<T>> {
let _ = files; // P3(platform-w8): pf.C-S5
legacy.iter().find_map(|f| {
let bytes = std::fs::read(&f.path).ok()?;
(f.parse)(&bytes).ok().map(|(v, errors)| (v, errors, f.path.clone()))
let text = files.read(&f.path).ok()??;
(f.parse)(text.as_bytes()).ok().map(|(v, errors)| (v, errors, f.path.clone()))
})
}
+24 -8
View File
@@ -100,19 +100,25 @@ pub struct Probe {
pub platform_config_dir: Option<PathBuf>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Default for Probe {
fn default() -> Self {
Self {
env: Box::new(|name| std::env::var_os(name)),
exe_dir: std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)),
#[cfg(not(target_arch = "wasm32"))]
platform_config_dir: dirs::config_dir(),
#[cfg(target_arch = "wasm32")]
platform_config_dir: None,
}
}
}
/// A browser has no environment, executable or config folder.
#[cfg(target_arch = "wasm32")]
impl Default for Probe {
fn default() -> Self {
Self { env: Box::new(|_| None), exe_dir: None, platform_config_dir: None }
}
}
impl std::fmt::Debug for Probe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Probe").field("exe_dir", &self.exe_dir).field("platform_config_dir", &self.platform_config_dir).finish_non_exhaustive()
@@ -199,11 +205,17 @@ fn resolve_checked(
/// Creates `dir` and proves a file can be written in it: a folder can exist and still be read-only.
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
#[cfg(not(target_arch = "wasm32"))]
return crate::recovery::check_writable(dir);
{
std::fs::create_dir_all(dir)?;
crate::recovery::check_writable(dir)
}
// Only `Location::Auto` asks, and a browser resolves it to memory before any folder is judged.
#[cfg(target_arch = "wasm32")]
Ok(())
{
let _ = dir;
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "a browser has no folders"))
}
}
/// Whether `dir`, or for a folder that doesn't exist yet its nearest existing ancestor (where
@@ -247,7 +259,9 @@ fn bundle_parent(exe_dir: &Path) -> Option<&Path> {
/// The platform cache folder for `app_id` (`%LOCALAPPDATA%` on Windows, so it does not roam).
pub fn cache_dir(app_id: &str) -> Option<PathBuf> {
#[cfg(not(target_arch = "wasm32"))]
return dirs::cache_dir().map(|d| d.join(app_id));
{
dirs::cache_dir().map(|d| d.join(app_id))
}
#[cfg(target_arch = "wasm32")]
{
let _ = app_id;
@@ -258,7 +272,9 @@ pub fn cache_dir(app_id: &str) -> Option<PathBuf> {
/// The platform data folder for `app_id`, for recovery files and other non-settings state.
pub fn data_dir(app_id: &str) -> Option<PathBuf> {
#[cfg(not(target_arch = "wasm32"))]
return dirs::data_local_dir().map(|d| d.join(app_id));
{
dirs::data_local_dir().map(|d| d.join(app_id))
}
#[cfg(target_arch = "wasm32")]
{
let _ = app_id;
+8 -4
View File
@@ -381,7 +381,6 @@ impl<T: Settings> SettingsStore<T> {
Ok(Some(text)) => self.load_text(path, &text, damaged, report),
Ok(None) => {
if let Some((value, errors, from)) = migrate::import_legacy(&*self.files, legacy) {
// P3(platform-w8): pf.C-S5
self.value = value;
self.dirty = true;
report.source = Source::Legacy(from);
@@ -440,6 +439,9 @@ impl<T: Settings> SettingsStore<T> {
self.dirty = false;
return Ok(());
};
// Held from the disk check to the write, so another process saving at the same moment waits instead of
// writing over the changes this save merges in. An early return releases it.
let lock = self.files.lock(&path);
let (backup, theirs) = self.check_disk(&path)?;
if let Some(on_disk) = backup {
self.files.write_backup(&path, &on_disk)?;
@@ -460,6 +462,7 @@ impl<T: Settings> SettingsStore<T> {
}
let text = document::render(&self.doc);
self.files.write(&path, &text)?;
drop(lock);
self.base = self.doc.clone();
self.seen_text = Some(text);
self.dirty = false;
@@ -473,9 +476,10 @@ impl<T: Settings> SettingsStore<T> {
/// (it parses and is not blank), and its document, upgraded to this build's schema, when
/// another instance or a hand edit changed it since this store last read or wrote it.
///
/// The contract is best effort, not multi-process locking: `save` merges this store's changes
/// since its base into that document ([`merge_changes`]), so the other writer's comments,
/// unknown keys and settings survive. A file that no longer parses is moved aside (the edit
/// `save` holds the files' lock ([`SettingsFiles::lock`]) around this check and its write, so two
/// processes saving at once take turns, and merges this store's changes since its base into that
/// document ([`merge_changes`]), so the other writer's comments, unknown keys and settings survive.
/// The lock is advisory and waits a bounded time; past that the save goes ahead. A file that no longer parses is moved aside (the edit
/// is kept, the previous backup stays), and a file from a newer build, or one whose migration
/// fails, makes the store read-only instead of overwriting it, the same as at startup.
fn check_disk(&mut self, path: &Path) -> Result<(Option<String>, Option<DocumentMut>), SettingsError> {
+70
View File
@@ -0,0 +1,70 @@
//! Integration tests of craft-settings: the store over the browser's localStorage.
#![cfg(target_arch = "wasm32")]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use craft_settings::{LegacyFile, LocalStorageFiles, Location, OpenOptions, SectionError, Settings, SettingsFiles, SettingsStore, Source};
use serde::{Deserialize, Serialize};
use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
wasm_bindgen_test_configure!(run_in_browser);
/// The byte cap the trial's storage enforces: room for a small file, not for [`Web::note`] at [`CAP`] bytes.
const CAP: usize = 256;
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
#[serde(default)]
struct Web {
dark: bool,
note: String,
}
impl Settings for Web {
const APP_ID: &'static str = "webcraft";
const SCHEMA_VERSION: u32 = 1;
}
fn options(dir: &str) -> OpenOptions<Web> {
OpenOptions::new(Location::Dir(PathBuf::from(dir))).files(Arc::new(LocalStorageFiles::new(CAP)))
}
/// The old item's text is the theme name.
fn parse_legacy(bytes: &[u8]) -> Result<(Web, Vec<SectionError>), String> {
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
Ok((Web { dark: text == "dark", note: String::new() }, Vec::new()))
}
// Settings on the web live in localStorage: a reload must see the last save, an oversized save must not destroy the
// saved settings, and the old hand-written item must carry over once.
#[wasm_bindgen_test]
fn a_store_over_local_storage_round_trips_refuses_over_the_cap_and_imports_the_legacy_item() {
let storage = web_sys::window().unwrap().local_storage().unwrap().unwrap();
for key in ["/web/config.toml", "/web/config.toml.bak", "/fresh/config.toml", "wordcraft.ui"] {
storage.remove_item(key).unwrap();
}
// A change saved by `flush` is what the next page load reads.
let (mut store, _) = SettingsStore::<Web>::open_with(options("/web"));
assert!(store.update(|w| w.dark = true));
store.flush().unwrap();
let (mut reloaded, report) = SettingsStore::<Web>::open_with(options("/web"));
assert!(reloaded.get().dark, "{report:?}");
assert!(matches!(report.source, Source::File), "{report:?}");
// A value over the cap fails the save and leaves the saved item as it was.
assert!(reloaded.update(|w| w.note = "x".repeat(CAP)));
assert!(reloaded.flush().is_err());
let stored = LocalStorageFiles::new(CAP).read(Path::new("/web/config.toml")).unwrap().unwrap();
assert!(stored.contains("dark = true") && !stored.contains("xxxx"), "{stored}");
let (again, _) = SettingsStore::<Web>::open_with(options("/web"));
assert!(again.get().dark && again.get().note.is_empty());
// With no settings item yet, the legacy item imports into a fresh store.
LocalStorageFiles::new(CAP).write(Path::new("wordcraft.ui"), "dark").unwrap();
let legacy = LegacyFile { path: PathBuf::from("wordcraft.ui"), parse: parse_legacy };
let (fresh, report) = SettingsStore::<Web>::open_with(options("/fresh").legacy(vec![legacy]));
assert!(fresh.get().dark, "{report:?}");
assert!(matches!(report.source, Source::Legacy(_)), "{report:?}");
}
+8
View File
@@ -1,7 +1,15 @@
//! Integration tests, built into the library's own test executable.
// These use `tempfile`, the file system and `MemoryFiles`, none of which a browser build has.
#[cfg(not(target_arch = "wasm32"))]
mod common;
#[cfg(not(target_arch = "wasm32"))]
mod merge;
#[cfg(not(target_arch = "wasm32"))]
mod migrate;
#[cfg(not(target_arch = "wasm32"))]
mod recovery;
#[cfg(not(target_arch = "wasm32"))]
mod store;
mod local_storage;
+145 -1
View File
@@ -3,13 +3,72 @@ use super::common;
use common::{Prefs, open_in, read_config, write_config};
use craft_settings::document::{merge_changes, parse};
use craft_settings::{MergeRule, Settings};
use serde::{Deserialize, Serialize};
fn merged(base: &str, ours: &str, theirs: &str) -> String {
merged_as::<Prefs>(base, ours, theirs)
}
fn merged_as<T: Settings>(base: &str, ours: &str, theirs: &str) -> String {
let mut theirs = parse(theirs).unwrap();
merge_changes::<Prefs>(&parse(base).unwrap(), &parse(ours).unwrap(), &mut theirs);
merge_changes::<T>(&parse(base).unwrap(), &parse(ours).unwrap(), &mut theirs);
theirs.to_string()
}
/// The merged file as [`Ruled`] reads it; a list entry the type cannot read fails the read.
fn merged_ruled(base: &str, ours: &str, theirs: &str) -> Ruled {
toml_edit::de::from_document(parse(&merged_as::<Ruled>(base, ours, theirs)).unwrap()).unwrap()
}
/// How many entries `recent` keeps.
const RECENT_CAP: usize = 4;
/// Settings whose items name their own merge rules, as an app's recent files, AutoCorrect entries and window are.
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
#[serde(default)]
struct Ruled {
recent: Vec<String>,
/// `[from, to]` pairs.
autocorrect: Vec<Vec<String>>,
window: Window,
}
#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)]
#[serde(default)]
struct Window {
x: i64,
width: i64,
}
impl Settings for Ruled {
const APP_ID: &'static str = "ruledcraft";
const SCHEMA_VERSION: u32 = 1;
fn merge_rule(path: &[&str]) -> MergeRule {
match path {
["recent"] => MergeRule::Recent { cap: RECENT_CAP, key: text },
["autocorrect"] => MergeRule::Entries { key: replaced_text },
["window"] => MergeRule::Whole,
_ => MergeRule::ByKey,
}
}
}
/// A recent entry by its text.
fn text(v: &toml_edit::Value) -> Option<String> {
v.as_str().map(str::to_owned)
}
/// An AutoCorrect pair by the text it replaces.
fn replaced_text(v: &toml_edit::Value) -> Option<String> {
v.as_array()?.get(0)?.as_str().map(str::to_owned)
}
fn pairs(list: &[[&str; 2]]) -> Vec<Vec<String>> {
list.iter().map(|pair| pair.iter().map(|s| (*s).to_owned()).collect()).collect()
}
// A key only the other instance changed keeps its value; a key only we changed is written; when
// both changed one key, ours wins.
#[test]
@@ -60,3 +119,88 @@ fn a_section_the_file_lacked_merges_only_the_keys_each_instance_changed() {
let general = &reopened.get().general;
assert_eq!((general.language.as_str(), general.autosave_minutes), ("fr", 9), "{}", read_config(tmp.path()));
}
/// A file holding `recent = <list>`.
fn recent(list: &[&str]) -> String {
format!("schema_version = 1\nrecent = {list:?}\n")
}
/// A file holding `autocorrect = <pairs>`.
fn autocorrect(list: &[[&str; 2]]) -> String {
format!("schema_version = 1\nautocorrect = {list:?}\n")
}
// Two instances share a recent list: neither may lose the other's entries, and what this one opened or used again
// leads.
#[test]
fn a_recent_list_moves_used_entries_forward_and_honours_removals_and_the_cap() {
// Here `c` was used again, `d` opened and `a` removed; the other instance used `b` again and opened `e`.
let out = merged_ruled(&recent(&["a", "b", "c"]), &recent(&["d", "c", "b"]), &recent(&["e", "b", "a", "c"]));
assert_eq!(out.recent, ["d", "c", "e", "b"]);
// Each instance opened one file into a full list: both new entries lead, cut to the cap.
let out = merged_ruled(&recent(&["a", "b", "c", "d"]), &recent(&["x", "a", "b", "c"]), &recent(&["y", "a", "b", "c"]));
assert_eq!(out.recent, ["x", "y", "a", "b"]);
assert_eq!(out.recent.len(), RECENT_CAP);
// Clearing the list here removes what this instance had loaded, not what the other one added since.
let out = merged_ruled(&recent(&["a", "b"]), &recent(&[]), &recent(&["c", "a", "b"]));
assert_eq!(out.recent, ["c"]);
}
// Two instances edit one list of user entries: every addition survives, every removal holds, a change made here wins,
// and an added entry lands after the entry it was added behind, not at the end.
#[test]
fn entries_from_both_instances_are_kept_with_removals_and_anchored_insertion() {
// Here: `teh` changed, `adn` added after it, `hte` removed. There: `teh2` added, `recieve` removed.
let base = autocorrect(&[["teh", "the"], ["hte", "the"], ["recieve", "receive"]]);
let ours = autocorrect(&[["teh", "THE"], ["adn", "and"], ["recieve", "receive"]]);
let theirs = autocorrect(&[["teh", "the"], ["hte", "the"], ["teh2", "the"]]);
let out = merged_ruled(&base, &ours, &theirs);
assert_eq!(out.autocorrect, pairs(&[["teh", "THE"], ["adn", "and"], ["teh2", "the"]]));
// Entries added on each side keep their place among the shared ones: `zz` before everything, `ww` between `teh`
// and `hte`, `yy` after `hte`.
let base = autocorrect(&[["teh", "the"], ["hte", "the"]]);
let ours = autocorrect(&[["zz", "z"], ["teh", "the"], ["hte", "the"], ["yy", "y"]]);
let theirs = autocorrect(&[["teh", "the"], ["ww", "w"], ["hte", "the"]]);
let out = merged_ruled(&base, &ours, &theirs);
assert_eq!(out.autocorrect, pairs(&[["zz", "z"], ["teh", "the"], ["ww", "w"], ["hte", "the"], ["yy", "y"]]));
}
// A window moved here and resized there must come out as one instance's window, never this one's place with the
// other's size, which neither instance ever held.
#[test]
fn a_whole_rule_table_is_replaced_not_mixed() {
let base = "schema_version = 1\n[window]\nx = 0\nwidth = 800\n";
let ours = "schema_version = 1\n[window]\nx = 300\nwidth = 800\n";
let theirs = "schema_version = 1\n[window]\nx = 0\nwidth = 1000\nextra = 1\n";
let text = merged_as::<Ruled>(base, ours, theirs);
let out = parse(&text).unwrap();
assert_eq!((out["window"]["x"].as_integer(), out["window"]["width"].as_integer()), (Some(300), Some(800)), "{text}");
assert!(out["window"].get("extra").is_none(), "no key of theirs survives: {text}");
// Left alone here while another setting changed, the other instance's window stays whole, keys and all.
let ours = "schema_version = 1\nrecent = [\"a\"]\n[window]\nx = 0\nwidth = 800\n";
let text = merged_as::<Ruled>(base, ours, theirs);
let out = parse(&text).unwrap();
assert_eq!((out["window"]["x"].as_integer(), out["window"]["width"].as_integer()), (Some(0), Some(1000)), "{text}");
assert_eq!(out["window"]["extra"].as_integer(), Some(1), "{text}");
}
// A hand edit or an older build can leave entries the type cannot read; carried into the merge they would make the
// whole list read as its default in every later session.
#[test]
fn a_bad_list_entry_is_dropped_not_carried() {
let out = merged_ruled(&recent(&[]), &recent(&["x"]), "schema_version = 1\nrecent = [{ path = \"y\" }, \"z\", 7]\n");
assert_eq!(out.recent, ["x", "z"]);
// A list with no entry that has a key carries nothing, and a value that is not a list gives way to ours.
let out = merged_ruled(&recent(&[]), &recent(&["x"]), "schema_version = 1\nrecent = [1, 2]\n");
assert_eq!(out.recent, ["x"]);
let out = merged_ruled(&recent(&[]), &recent(&["x"]), "schema_version = 1\nrecent = 3\n");
assert_eq!(out.recent, ["x"]);
let out = merged_ruled(&autocorrect(&[]), &autocorrect(&[["teh", "the"]]), "schema_version = 1\nautocorrect = [[\"ok\", \"fine\"], \"bare\", [3, 4]]\n");
assert_eq!(out.autocorrect, pairs(&[["teh", "the"], ["ok", "fine"]]));
}
+123 -2
View File
@@ -2,14 +2,16 @@
use super::common;
use std::any::Any;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use common::{Prefs, Theme, config_path, empty_probe, open_in, open_keyed, read_config, write_config};
use craft_settings::store::{FIRST_RETRY_DELAY, MAX_RETRY_DELAY};
use craft_settings::testing::MemoryFiles;
use craft_settings::{Location, OpenOptions, SaveStatus, SettingsStore};
use craft_settings::{Location, OpenOptions, SaveStatus, SettingsFiles, SettingsStore};
#[test]
fn comments_unknown_keys_and_order_survive_a_save() {
@@ -218,3 +220,122 @@ fn a_read_falls_back_to_the_platform_folder_like_an_open() {
assert!(report.warning.is_some());
assert_eq!(store.get().general.language, "platform", "an open takes the same folder");
}
/// A call the store made on its files.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Call {
Lock,
Read,
Backup,
Write,
/// The lock's guard was dropped.
Unlock,
}
type Calls = Arc<Mutex<Vec<Call>>>;
/// [`MemoryFiles`] that records the order of the store's calls, with a lock whose release is recorded too.
#[derive(Default)]
struct Recording {
inner: MemoryFiles,
calls: Calls,
}
impl Recording {
fn record(&self, call: Call) {
self.calls.lock().unwrap().push(call);
}
/// The calls since the last take.
fn take(&self) -> Vec<Call> {
std::mem::take(&mut *self.calls.lock().unwrap())
}
}
struct Guard(Calls);
impl Drop for Guard {
fn drop(&mut self) {
self.0.lock().unwrap().push(Call::Unlock);
}
}
impl SettingsFiles for Recording {
fn read(&self, path: &Path) -> io::Result<Option<String>> {
self.record(Call::Read);
self.inner.read(path)
}
fn write(&self, path: &Path, text: &str) -> io::Result<()> {
self.record(Call::Write);
self.inner.write(path, text)
}
fn move_aside(&self, path: &Path) -> io::Result<PathBuf> {
self.inner.move_aside(path)
}
fn write_backup(&self, path: &Path, text: &str) -> io::Result<()> {
self.record(Call::Backup);
self.inner.write_backup(path, text)
}
fn check_writable(&self, dir: &Path) -> io::Result<()> {
self.inner.check_writable(dir)
}
fn lock(&self, path: &Path) -> Option<Box<dyn Any + Send>> {
let _ = path;
self.record(Call::Lock);
Some(Box::new(Guard(self.calls.clone())))
}
}
// SG-41: two processes saving at once must take turns from the disk check to the write, or the later one writes over
// what the earlier one just merged in.
#[test]
fn a_save_holds_the_files_lock_from_the_disk_check_to_the_write() {
let dir = Path::new("/memory");
let files = Arc::new(Recording::default());
let options = OpenOptions::new(Location::Dir(PathBuf::from(dir))).probe(empty_probe()).files(files.clone());
let (mut store, _) = SettingsStore::<Prefs>::open_with(options);
files.take();
// The first save: no file yet, so no backup.
store.update(|p| p.general.language = "fr".into());
store.flush().unwrap();
assert_eq!(files.take(), [Call::Lock, Call::Read, Call::Write, Call::Unlock]);
// A save over an existing file keeps its backup inside the lock too.
store.update(|p| p.general.language = "de".into());
store.flush().unwrap();
assert_eq!(files.take(), [Call::Lock, Call::Read, Call::Backup, Call::Write, Call::Unlock]);
// A save that fails partway releases the lock.
files.inner.fail_writes(true);
store.update(|p| p.general.language = "nl".into());
assert!(store.flush().is_err());
let calls = files.take();
assert_eq!(calls.first(), Some(&Call::Lock), "{calls:?}");
assert_eq!(calls.last(), Some(&Call::Unlock), "{calls:?}");
assert!(!calls.contains(&Call::Write), "{calls:?}");
files.inner.fail_writes(false);
// A store with no file takes no lock.
let options = OpenOptions::new(Location::Memory).probe(empty_probe()).files(files.clone());
let (mut memory, _) = SettingsStore::<Prefs>::open_with(options);
memory.update(|p| p.general.language = "fr".into());
memory.flush().unwrap();
assert!(!files.take().contains(&Call::Lock));
// Nor does a read-only one: this file comes from a newer build.
let newer = Path::new("/newer");
files.inner.write(&config_path(newer), "schema_version = 99\n").unwrap();
let options = OpenOptions::new(Location::Dir(PathBuf::from(newer))).probe(empty_probe()).files(files.clone());
let (mut read_only, _) = SettingsStore::<Prefs>::open_with(options);
assert!(read_only.is_read_only());
files.take();
read_only.update(|p| p.general.language = "fr".into());
assert!(read_only.flush().is_err());
assert!(!files.take().contains(&Call::Lock));
}
+19 -3
View File
@@ -67,8 +67,15 @@ mount), the store opens read-only and says so at startup.
broken: only that `[section]` falls back to defaults and the app is told which one.
- A file written by a newer build is shown but never overwritten.
- Comments, key order and keys the app does not know survive saves. If two instances of an app
are open, each re-reads the file before writing so those survive; known keys are
last-writer-wins.
are open, each re-reads the file before writing and merges in only its own changes, so the
other's survive. The app names how each item merges with `Settings::merge_rule`: key by key
(the default), whole (a window's place and size come from one instance), a recent list (what
this instance opened or used again leads, cut to its limit) or a list of user entries
(additions and removals from both are kept, an added entry stays after the entry before it).
- Each save holds an advisory lock, `.config.toml.lock` beside the file, from re-reading the file
to writing it, so two instances saving at the same moment take turns instead of one writing
over the other's merge. A save waits at most 2 seconds for it, then saves anyway and logs a
warning, so a stuck process never stops another from saving.
## Migration
@@ -98,8 +105,17 @@ files there too.
Adoption order: PhotoCraft and DesignCraft first (closest to and furthest from the target
behaviour), then the rest.
## Settings on the web
A browser build (`wasm32`) opens the same `SettingsStore`. Its files are localStorage items
(`LocalStorageFiles`, the default there), keyed by path, so `Location::Dir(dir)` names the key
prefix; `Location::Auto` keeps settings in memory. Storage holds about 5 MB per site, so the
store caps an item at 4 MB: a stored item over the cap reads as absent and the next save replaces
it, and a save over the cap fails and keeps the old item. An app's older hand-written item is a
`LegacyFile` read through the same storage. Browser storage takes no lock; tabs of one site share
the items, and each save still merges in what another tab wrote since.
## Not yet
- Reloading settings when the file changes on disk while the app runs
- Removing imported legacy files
- Settings on the web (`wasm32`), where only the trait, document helpers and error types exist