Skip to main content

settings_model/
source.rs

1//! The settings a process reads: the source its host installed.
2//!
3//! The session installs its settings as resources of the workspace; a sandboxed app installs its
4//! channel to the session; a service the session started, and a browser page, install a
5//! [`HostDocument`] of what their host gives them; a window of the toolkit alone installs none.
6//! A process with none installed reads every setting's default.
7
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, RwLock};
10
11use serde_json::{Map, Value};
12use tilo_lock::{MutexRecover as _, RwLockRecover as _};
13
14#[derive(Debug)]
15pub enum ConditionalUpdate {
16    Superseded,
17    Stored,
18}
19
20#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct ChangeOrigin {
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub action: Option<String>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub actor: Option<String>,
26}
27
28impl ChangeOrigin {
29    pub const LOCAL_USER: &'static str = "local-user";
30
31    #[must_use]
32    pub fn action(action: impl Into<String>) -> Self {
33        Self {
34            action: Some(action.into()),
35            actor: None,
36        }
37    }
38
39    #[must_use]
40    pub fn by(mut self, actor: impl Into<String>) -> Self {
41        self.actor = Some(actor.into());
42        self
43    }
44
45    #[must_use]
46    pub fn local(action: impl Into<String>) -> Self {
47        Self::action(action).by(Self::LOCAL_USER)
48    }
49}
50
51/// What a read-modify-write makes of the current section: the leaves to
52/// merge into it. Called once, with the section as stored at that moment.
53pub type SectionChange<'a> = dyn FnMut(&Map<String, Value>) -> Map<String, Value> + 'a;
54
55pub trait SettingsSource: Send + Sync {
56    fn load(&self) -> Map<String, Value>;
57
58    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()>;
59
60    fn update_section_by(
61        &self,
62        name: &str,
63        values: Map<String, Value>,
64        origin: &ChangeOrigin,
65    ) -> std::io::Result<()> {
66        let _ = origin;
67        self.update_section(name, values)
68    }
69
70    /// Read section `name` and merge what `change` makes of it, recording
71    /// `origin`, as one step no other write to this source lands inside.
72    /// This is the read-modify-write behind a typed key's update: a toggle
73    /// pressed twice in quick succession flips twice.
74    ///
75    /// The default reads and then writes, which is atomic only where the
76    /// source's writer serialises them itself (an app's settings channel,
77    /// whose host applies writes in order); a source that owns its document
78    /// overrides it to hold its lock across both.
79    ///
80    /// # Errors
81    /// As [`Self::update_section`].
82    fn update_section_with(
83        &self,
84        name: &str,
85        origin: &ChangeOrigin,
86        change: &mut SectionChange<'_>,
87    ) -> std::io::Result<()> {
88        let current = match self.load().remove(name) {
89            Some(Value::Object(section)) => section,
90            _ => Map::new(),
91        };
92        self.update_section_by(name, change(&current), origin)
93    }
94
95    /// Merge each of `sections` as one change made by `origin`: one step history takes back
96    /// together, a choice spanning sections (the model agents answer with) included.
97    ///
98    /// # Errors
99    /// As [`Self::update_section`].
100    fn update_sections(
101        &self,
102        sections: Vec<(String, Map<String, Value>)>,
103        origin: &ChangeOrigin,
104    ) -> std::io::Result<()> {
105        for (name, values) in sections {
106            self.update_section_by(&name, values, origin)?;
107        }
108        Ok(())
109    }
110
111    /// [`Self::update_sections`], only if each of `expected` (a section, and what it held when
112    /// the caller read it) still holds what it did. `Superseded` means a newer change replaced
113    /// what the caller read.
114    ///
115    /// # Errors
116    /// As [`Self::update_section`].
117    fn compare_update_sections(
118        &self,
119        _expected: &[(&str, Map<String, Value>)],
120        _sections: Vec<(String, Map<String, Value>)>,
121        _origin: &ChangeOrigin,
122    ) -> std::io::Result<ConditionalUpdate> {
123        Err(std::io::Error::new(
124            std::io::ErrorKind::Unsupported,
125            "conditional settings persistence is unavailable",
126        ))
127    }
128
129    /// Why writing `values` to section `name` is refused — a field the section declares read only
130    /// would change — asked before the settings channel writes an app's values there. The field
131    /// is changed by the action a section declares and by nothing else, so no app's write reaches
132    /// it. `None` from a source that keeps no such declarations.
133    fn readonly_refusal(&self, _name: &str, _values: &Map<String, Value>) -> Option<String> {
134        None
135    }
136
137    /// Take back (`undo`) or bring back the last step any of `invokers` (actors, as a change
138    /// names them) took on section `section`, of the app `app` where the section keeps each
139    /// app's preferences apart. Whether there was one.
140    ///
141    /// # Errors
142    /// The settings' history is not kept here, or the step was refused.
143    fn step(
144        &self,
145        _section: &str,
146        _app: Option<&str>,
147        _undo: bool,
148        _invokers: &[String],
149    ) -> std::io::Result<bool> {
150        Err(std::io::Error::new(
151            std::io::ErrorKind::Unsupported,
152            "the settings' history is kept by the session",
153        ))
154    }
155
156    /// The changes of section `section`, oldest first, each as the stamp it carries in the
157    /// settings' history (or will, once written): which setter set what, and who invoked it.
158    ///
159    /// # Errors
160    /// The settings' history is not kept here.
161    fn stamps(&self, _section: &str) -> std::io::Result<Vec<tilo_actions::stamp::Stamp>> {
162        Err(std::io::Error::new(
163            std::io::ErrorKind::Unsupported,
164            "the settings' history is kept by the session",
165        ))
166    }
167
168    fn flush_pending(&self) {}
169
170    fn take_deferred_failures(&self) -> Vec<DeferredFailure> {
171        Vec::new()
172    }
173
174    fn revision(&self) -> u64;
175
176    /// Rings every time [`Self::revision`] changes, so a reader waiting for
177    /// a change wakes at once instead of looking again and again.
178    fn changes(&self) -> &ChangeSignal;
179}
180
181/// [`SettingsSource::compare_update_sections`] of one section: merge `values` into `name` only
182/// if it still holds `expected`.
183///
184/// # Errors
185/// As [`SettingsSource::update_section`].
186pub fn compare_update_section(
187    source: &dyn SettingsSource,
188    name: &str,
189    expected: &Map<String, Value>,
190    values: Map<String, Value>,
191) -> std::io::Result<ConditionalUpdate> {
192    source.compare_update_sections(
193        &[(name, expected.clone())],
194        vec![(name.to_owned(), values)],
195        &ChangeOrigin::default(),
196    )
197}
198
199macro_rules! shared_source {
200    ($(fn $name:ident(&self $(, $arg:ident: $ty:ty)* $(,)?) $(-> $ret:ty)?;)*) => {
201        impl<T: SettingsSource + ?Sized> SettingsSource for Arc<T> {
202            $(
203                fn $name(&self $(, $arg: $ty)*) $(-> $ret)? {
204                    (**self).$name($($arg),*)
205                }
206            )*
207        }
208    };
209}
210
211shared_source! {
212    fn load(&self) -> Map<String, Value>;
213    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()>;
214    fn update_section_by(
215        &self,
216        name: &str,
217        values: Map<String, Value>,
218        origin: &ChangeOrigin,
219    ) -> std::io::Result<()>;
220    fn update_section_with(
221        &self,
222        name: &str,
223        origin: &ChangeOrigin,
224        change: &mut SectionChange<'_>,
225    ) -> std::io::Result<()>;
226    fn update_sections(
227        &self,
228        sections: Vec<(String, Map<String, Value>)>,
229        origin: &ChangeOrigin,
230    ) -> std::io::Result<()>;
231    fn compare_update_sections(
232        &self,
233        expected: &[(&str, Map<String, Value>)],
234        sections: Vec<(String, Map<String, Value>)>,
235        origin: &ChangeOrigin,
236    ) -> std::io::Result<ConditionalUpdate>;
237    fn readonly_refusal(&self, name: &str, values: &Map<String, Value>) -> Option<String>;
238    fn step(
239        &self,
240        section: &str,
241        app: Option<&str>,
242        undo: bool,
243        invokers: &[String],
244    ) -> std::io::Result<bool>;
245    fn stamps(&self, section: &str) -> std::io::Result<Vec<tilo_actions::stamp::Stamp>>;
246    fn flush_pending(&self);
247    fn take_deferred_failures(&self) -> Vec<DeferredFailure>;
248    fn revision(&self) -> u64;
249    fn changes(&self) -> &ChangeSignal;
250}
251
252#[derive(Default)]
253pub struct ChangeSignal {
254    listeners: Mutex<Vec<std::sync::Weak<Listener>>>,
255}
256
257/// What a reader runs when the document changed: hand the news on, nothing
258/// slow; it runs on the thread that made or noticed the change.
259pub type Listener = dyn Fn() + Send + Sync;
260
261impl ChangeSignal {
262    pub fn listen(&self, listener: &Arc<Listener>) {
263        let mut listeners = self.listeners.lock_recover();
264        listeners.retain(|known| known.strong_count() > 0);
265        listeners.push(Arc::downgrade(listener));
266    }
267
268    pub fn ring(&self) {
269        let listeners: Vec<Arc<Listener>> = self
270            .listeners
271            .lock_recover()
272            .iter()
273            .filter_map(std::sync::Weak::upgrade)
274            .collect();
275        for listener in listeners {
276            listener();
277        }
278    }
279}
280
281static SOURCE: RwLock<Option<Arc<dyn SettingsSource>>> = RwLock::new(None);
282
283#[derive(Clone, Debug, PartialEq, Eq)]
284pub struct DeferredFailure {
285    pub sections: Vec<String>,
286    pub error: String,
287}
288
289/// Make `source` the settings document of this process, or restore the
290/// local profile with `None`. A host does this once, as it starts; a test
291/// that needs a document of its own takes a [`scoped_source`], which no
292/// other test sees.
293pub fn install_source(source: Option<Arc<dyn SettingsSource>>) {
294    *SOURCE.write_recover() = source;
295    INSTALLED.fetch_add(1, Ordering::AcqRel);
296}
297
298/// How many settings documents this process has installed in place of others.
299static INSTALLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
300
301/// The version of `source` as this process reads it: the document's own revision, told apart
302/// from every document installed in another's place before it, so a reader that caches what it
303/// read by version reads a replaced document again even where the two number alike. A reader
304/// told only the document's own revision takes a document put in place of another for the one
305/// it replaced, and keeps reading what the old one said.
306#[must_use]
307pub fn installed_version(source: &dyn SettingsSource) -> u64 {
308    let mut folded = 0xcbf2_9ce4_8422_2325u64 ^ INSTALLED.load(Ordering::Acquire);
309    for byte in source.revision().to_le_bytes() {
310        folded = (folded ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
311    }
312    folded
313}
314
315pub fn installed_source() -> Option<Arc<dyn SettingsSource>> {
316    if let Some(scoped) = SCOPED.with(|scoped| scoped.borrow().last().cloned()) {
317        return scoped;
318    }
319    SOURCE.read_recover().clone()
320}
321
322thread_local! {
323    static SCOPED: std::cell::RefCell<Vec<Option<Arc<dyn SettingsSource>>>> =
324        const { std::cell::RefCell::new(Vec::new()) };
325}
326
327#[must_use = "the scope ends when it is dropped"]
328pub fn scoped_source(source: Option<Arc<dyn SettingsSource>>) -> SourceScope {
329    SCOPED.with(|scoped| scoped.borrow_mut().push(source));
330    // A document put in front of the one this thread read is a new version of it, as
331    // [`install_source`]'s is.
332    INSTALLED.fetch_add(1, Ordering::AcqRel);
333    SourceScope {
334        _not_send: std::marker::PhantomData,
335    }
336}
337
338pub struct SourceScope {
339    _not_send: std::marker::PhantomData<*const ()>,
340}
341
342impl Drop for SourceScope {
343    fn drop(&mut self) {
344        SCOPED.with(|scoped| {
345            scoped.borrow_mut().pop();
346        });
347        INSTALLED.fetch_add(1, Ordering::AcqRel);
348    }
349}
350
351/// Merge `values` into section `name` of `doc`, keeping every other section
352/// and every key `values` does not mention. A section of the wrong type is
353/// replaced: there is nothing to preserve in a value that cannot be read.
354pub fn merge_section(doc: &mut Map<String, Value>, name: &str, values: Map<String, Value>) {
355    let entry = doc
356        .entry(name.to_string())
357        .or_insert_with(|| Value::Object(Map::new()));
358    if !entry.is_object() {
359        *entry = Value::Object(Map::new());
360    }
361    if let Some(obj) = entry.as_object_mut() {
362        for (k, v) in values {
363            obj.insert(k, v);
364        }
365    }
366}
367
368type Persist = dyn Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync;
369
370pub struct HostDocument {
371    doc: Mutex<Map<String, Value>>,
372    revision: AtomicU64,
373    persist: Box<Persist>,
374    changes: ChangeSignal,
375}
376
377impl HostDocument {
378    pub fn new(
379        initial: Map<String, Value>,
380        persist: impl Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync + 'static,
381    ) -> Self {
382        Self {
383            doc: Mutex::new(initial),
384            revision: AtomicU64::new(1),
385            persist: Box::new(persist),
386            changes: ChangeSignal::default(),
387        }
388    }
389}
390
391impl HostDocument {
392    /// Merge what `change` makes of the document, under its lock, persisting it first; `None`
393    /// from `change` leaves it as it is.
394    fn change(
395        &self,
396        change: impl FnOnce(&Map<String, Value>) -> Option<Vec<(String, Map<String, Value>)>>,
397    ) -> std::io::Result<ConditionalUpdate> {
398        let mut doc = self.doc.lock_recover();
399        let Some(sections) = change(&doc) else {
400            return Ok(ConditionalUpdate::Superseded);
401        };
402        let mut next = doc.clone();
403        for (name, values) in sections {
404            merge_section(&mut next, &name, values);
405        }
406        (self.persist)(&next)?;
407        *doc = next;
408        self.revision.fetch_add(1, Ordering::AcqRel);
409        drop(doc);
410        self.changes.ring();
411        Ok(ConditionalUpdate::Stored)
412    }
413}
414
415impl SettingsSource for HostDocument {
416    fn load(&self) -> Map<String, Value> {
417        self.doc.lock_recover().clone()
418    }
419
420    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()> {
421        let mut values = Some(values);
422        self.update_section_with(name, &ChangeOrigin::default(), &mut |_| {
423            values.take().unwrap_or_default()
424        })
425    }
426
427    fn update_section_with(
428        &self,
429        name: &str,
430        _origin: &ChangeOrigin,
431        change: &mut SectionChange<'_>,
432    ) -> std::io::Result<()> {
433        self.change(|doc| {
434            let current = match doc.get(name) {
435                Some(Value::Object(section)) => section.clone(),
436                _ => Map::new(),
437            };
438            Some(vec![(name.to_owned(), change(&current))])
439        })
440        .map(drop)
441    }
442
443    fn update_sections(
444        &self,
445        sections: Vec<(String, Map<String, Value>)>,
446        _origin: &ChangeOrigin,
447    ) -> std::io::Result<()> {
448        self.change(|_| Some(sections)).map(drop)
449    }
450
451    fn compare_update_sections(
452        &self,
453        expected: &[(&str, Map<String, Value>)],
454        sections: Vec<(String, Map<String, Value>)>,
455        _origin: &ChangeOrigin,
456    ) -> std::io::Result<ConditionalUpdate> {
457        self.change(|doc| {
458            expected
459                .iter()
460                .all(|(name, expected)| match doc.get(*name) {
461                    Some(Value::Object(section)) => section == expected,
462                    _ => expected.is_empty(),
463                })
464                .then_some(sections)
465        })
466    }
467
468    fn revision(&self) -> u64 {
469        self.revision.load(Ordering::Acquire)
470    }
471
472    fn changes(&self) -> &ChangeSignal {
473        &self.changes
474    }
475}
476
477/// One version of the document a [`SettingsSource`] holds, for readers that follow it.
478#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
479pub struct SettingsStamp(pub u64);
480
481/// A settings document's body read as an object: anything else is the empty document, so a
482/// broken file reads as every setting's default.
483#[must_use]
484pub fn parse(text: &str) -> Map<String, Value> {
485    match serde_json::from_str::<Value>(text) {
486        Ok(Value::Object(m)) => m,
487        _ => Map::new(),
488    }
489}
490
491/// Section `name` of `doc` as an object. A missing section, or one that is not an object,
492/// yields an empty map.
493#[must_use]
494pub fn section_of(mut doc: Map<String, Value>, name: &str) -> Map<String, Value> {
495    match doc.remove(name) {
496        Some(Value::Object(m)) => m,
497        _ => Map::new(),
498    }
499}
500
501/// Section `name` of what `source` holds, as [`section_of`].
502#[must_use]
503pub fn load_section_in(source: &dyn SettingsSource, name: &str) -> Map<String, Value> {
504    section_of(source.load(), name)
505}
506
507/// The settings of a profile kept apart from the person's (a headless app's, a test's, the
508/// models a host keeps for a workspace it serves), by its root: one per root for the life of the
509/// process, kept in the root's `settings.json`, which a write replaces whole.
510#[must_use]
511pub fn profile(root: &std::path::Path) -> Arc<HostDocument> {
512    static PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<HostDocument>)>> = Mutex::new(Vec::new());
513    let mut profiles = PROFILES.lock_recover();
514    if let Some((_, held)) = profiles.iter().find(|(held, _)| held == root) {
515        return Arc::clone(held);
516    }
517    let file = root.join(PROFILE_FILE);
518    let kept = std::fs::read(&file)
519        .ok()
520        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
521        .unwrap_or_default();
522    let document = Arc::new(HostDocument::new(kept, move |document| {
523        let bytes = serde_json::to_vec(document).map_err(std::io::Error::other)?;
524        if let Some(parent) = file.parent() {
525            std::fs::create_dir_all(parent)?;
526        }
527        let partial = file.with_extension("json.partial");
528        std::fs::write(&partial, bytes)?;
529        std::fs::rename(&partial, &file)
530    }));
531    profiles.push((root.to_owned(), Arc::clone(&document)));
532    document
533}
534
535/// Keep the settings of the profile at `root` in what `source` makes, in place of its own
536/// document ([`profile`]), unless something keeps them already: what a host that keeps a
537/// person's settings as resources of a workspace gives the profile it opens a window on, so they
538/// are kept, stepped and read back as that host keeps the person's, and a later window on the
539/// profile finds what an earlier one set.
540pub fn keep_profile(root: &std::path::Path, source: impl FnOnce() -> Arc<dyn SettingsSource>) {
541    let mut kept = KEPT_PROFILES.lock_recover();
542    if !kept.iter().any(|(held, _)| held == root) {
543        kept.push((root.to_owned(), source()));
544    }
545}
546
547/// The settings of the profile at `root`: what a host gave it to keep them ([`keep_profile`]),
548/// else its own document ([`profile`]).
549#[must_use]
550pub fn profile_source(root: &std::path::Path) -> Arc<dyn SettingsSource> {
551    let kept = KEPT_PROFILES
552        .lock_recover()
553        .iter()
554        .find(|(held, _)| held == root)
555        .map(|(_, source)| Arc::clone(source));
556    kept.unwrap_or_else(|| profile(root))
557}
558
559static KEPT_PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<dyn SettingsSource>)>> =
560    Mutex::new(Vec::new());
561
562/// The file a [`profile`] is kept in, below its root.
563const PROFILE_FILE: &str = "settings.json";
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568    use serde_json::json;
569
570    fn object(value: Value) -> Map<String, Value> {
571        let Value::Object(map) = value else {
572            panic!("not an object")
573        };
574        map
575    }
576
577    tilo_test_env::scenario! {
578        fn a_host_document_stores_what_its_persist_accepts;
579
580        phase host_document_merges_persists_then_publishes;
581        {
582            let persisted = Arc::new(Mutex::new(Vec::new()));
583            let sink = Arc::clone(&persisted);
584            let doc = HostDocument::new(
585                object(json!({"region": {"locale": "de-DE"}, "power": 3})),
586                move |doc| {
587                    sink.lock().unwrap().push(Value::Object(doc.clone()));
588                    Ok(())
589                },
590            );
591            let before = doc.revision();
592            doc.update_section("power", object(json!({"idle": 5})))
593                .unwrap();
594            doc.update_section("region", object(json!({"units": "metric"})))
595                .unwrap();
596            let expected =
597                json!({"region": {"locale": "de-DE", "units": "metric"}, "power": {"idle": 5}});
598            assert_eq!(Value::Object(doc.load()), expected);
599            assert_eq!(persisted.lock().unwrap().last(), Some(&expected));
600            assert_eq!(doc.revision(), before + 2);
601        }
602
603        phase a_conditional_section_update_stores_only_over_what_it_read;
604        {
605            let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| Ok(()));
606            let read = object(json!({"x": 1}));
607            assert!(matches!(
608                compare_update_section(&doc, "a", &read, object(json!({"x": 2}))).unwrap(),
609                ConditionalUpdate::Stored
610            ));
611            assert!(matches!(
612                compare_update_section(&doc, "a", &read, object(json!({"x": 3}))).unwrap(),
613                ConditionalUpdate::Superseded
614            ));
615            assert!(matches!(
616                compare_update_section(&doc, "new", &Map::new(), object(json!({"y": 1})))
617                    .unwrap(),
618                ConditionalUpdate::Stored
619            ));
620            assert_eq!(
621                Value::Object(doc.load()),
622                json!({"a": {"x": 2}, "new": {"y": 1}})
623            );
624        }
625
626        phase a_refused_persist_leaves_the_document_unchanged;
627        {
628            let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| {
629                Err(std::io::Error::other("quota"))
630            });
631            let before = doc.revision();
632            assert!(doc.update_section("a", object(json!({"x": 2}))).is_err());
633            assert_eq!(Value::Object(doc.load()), json!({"a": {"x": 1}}));
634            assert_eq!(doc.revision(), before);
635        }
636    }
637
638    #[test]
639    fn a_scoped_document_is_its_threads_alone_and_ends_with_its_scope() {
640        let document = |mode: &str| -> Arc<dyn SettingsSource> {
641            Arc::new(HostDocument::new(
642                object(json!({"appearance": {"mode": mode}})),
643                |_| Ok(()),
644            ))
645        };
646        let mode = || -> Option<String> {
647            let doc = installed_source()?.load();
648            Some(doc.get("appearance")?.get("mode")?.as_str()?.to_owned())
649        };
650        let outer = scoped_source(Some(document("light")));
651        assert_eq!(mode().as_deref(), Some("light"));
652        let elsewhere = std::thread::spawn(move || mode().as_deref() != Some("light"))
653            .join()
654            .unwrap_or(false);
655        assert!(elsewhere);
656        {
657            let _inner = scoped_source(Some(document("dark")));
658            assert_eq!(mode().as_deref(), Some("dark"));
659        }
660        assert_eq!(mode().as_deref(), Some("light"));
661        drop(outer);
662        assert!(SCOPED.with(|scoped| scoped.borrow().is_empty()));
663    }
664}