1use 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
51pub 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 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(¤t), origin)
93 }
94
95 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 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 fn readonly_refusal(&self, _name: &str, _values: &Map<String, Value>) -> Option<String> {
134 None
135 }
136
137 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 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 fn changes(&self) -> &ChangeSignal;
179}
180
181pub 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
257pub 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
283pub type Fallback = fn() -> Option<Arc<dyn SettingsSource>>;
285
286static FALLBACK: RwLock<Option<Fallback>> = RwLock::new(None);
288
289pub fn register_fallback(fallback: Fallback) {
294 *FALLBACK.write_recover() = Some(fallback);
295}
296
297#[must_use]
301pub fn source() -> Option<Arc<dyn SettingsSource>> {
302 installed_source().or_else(|| (*FALLBACK.read_recover())?())
303}
304
305#[derive(Clone, Debug, PartialEq, Eq)]
306pub struct DeferredFailure {
307 pub sections: Vec<String>,
308 pub error: String,
309}
310
311pub fn install_source(source: Option<Arc<dyn SettingsSource>>) {
316 *SOURCE.write_recover() = source;
317 INSTALLED.fetch_add(1, Ordering::AcqRel);
318}
319
320static INSTALLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
322
323#[must_use]
329pub fn installed_version(source: &dyn SettingsSource) -> u64 {
330 let mut folded = 0xcbf2_9ce4_8422_2325u64 ^ INSTALLED.load(Ordering::Acquire);
331 for byte in source.revision().to_le_bytes() {
332 folded = (folded ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
333 }
334 folded
335}
336
337pub fn installed_source() -> Option<Arc<dyn SettingsSource>> {
338 if let Some(scoped) = SCOPED.with(|scoped| scoped.borrow().last().cloned()) {
339 return scoped;
340 }
341 SOURCE.read_recover().clone()
342}
343
344thread_local! {
345 static SCOPED: std::cell::RefCell<Vec<Option<Arc<dyn SettingsSource>>>> =
346 const { std::cell::RefCell::new(Vec::new()) };
347}
348
349#[must_use = "the scope ends when it is dropped"]
350pub fn scoped_source(source: Option<Arc<dyn SettingsSource>>) -> SourceScope {
351 SCOPED.with(|scoped| scoped.borrow_mut().push(source));
352 INSTALLED.fetch_add(1, Ordering::AcqRel);
355 SourceScope {
356 _not_send: std::marker::PhantomData,
357 }
358}
359
360pub struct SourceScope {
361 _not_send: std::marker::PhantomData<*const ()>,
362}
363
364impl Drop for SourceScope {
365 fn drop(&mut self) {
366 SCOPED.with(|scoped| {
367 scoped.borrow_mut().pop();
368 });
369 INSTALLED.fetch_add(1, Ordering::AcqRel);
370 }
371}
372
373pub fn merge_section(doc: &mut Map<String, Value>, name: &str, values: Map<String, Value>) {
377 let entry = doc
378 .entry(name.to_string())
379 .or_insert_with(|| Value::Object(Map::new()));
380 if !entry.is_object() {
381 *entry = Value::Object(Map::new());
382 }
383 if let Some(obj) = entry.as_object_mut() {
384 for (k, v) in values {
385 obj.insert(k, v);
386 }
387 }
388}
389
390type Persist = dyn Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync;
391
392pub struct HostDocument {
393 doc: Mutex<Map<String, Value>>,
394 revision: AtomicU64,
395 persist: Box<Persist>,
396 changes: ChangeSignal,
397}
398
399impl HostDocument {
400 pub fn new(
401 initial: Map<String, Value>,
402 persist: impl Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync + 'static,
403 ) -> Self {
404 Self {
405 doc: Mutex::new(initial),
406 revision: AtomicU64::new(1),
407 persist: Box::new(persist),
408 changes: ChangeSignal::default(),
409 }
410 }
411}
412
413impl HostDocument {
414 fn change(
417 &self,
418 change: impl FnOnce(&Map<String, Value>) -> Option<Vec<(String, Map<String, Value>)>>,
419 ) -> std::io::Result<ConditionalUpdate> {
420 let mut doc = self.doc.lock_recover();
421 let Some(sections) = change(&doc) else {
422 return Ok(ConditionalUpdate::Superseded);
423 };
424 let mut next = doc.clone();
425 for (name, values) in sections {
426 merge_section(&mut next, &name, values);
427 }
428 (self.persist)(&next)?;
429 *doc = next;
430 self.revision.fetch_add(1, Ordering::AcqRel);
431 drop(doc);
432 self.changes.ring();
433 Ok(ConditionalUpdate::Stored)
434 }
435}
436
437impl SettingsSource for HostDocument {
438 fn load(&self) -> Map<String, Value> {
439 self.doc.lock_recover().clone()
440 }
441
442 fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()> {
443 let mut values = Some(values);
444 self.update_section_with(name, &ChangeOrigin::default(), &mut |_| {
445 values.take().unwrap_or_default()
446 })
447 }
448
449 fn update_section_with(
450 &self,
451 name: &str,
452 _origin: &ChangeOrigin,
453 change: &mut SectionChange<'_>,
454 ) -> std::io::Result<()> {
455 self.change(|doc| {
456 let current = match doc.get(name) {
457 Some(Value::Object(section)) => section.clone(),
458 _ => Map::new(),
459 };
460 Some(vec![(name.to_owned(), change(¤t))])
461 })
462 .map(drop)
463 }
464
465 fn update_sections(
466 &self,
467 sections: Vec<(String, Map<String, Value>)>,
468 _origin: &ChangeOrigin,
469 ) -> std::io::Result<()> {
470 self.change(|_| Some(sections)).map(drop)
471 }
472
473 fn compare_update_sections(
474 &self,
475 expected: &[(&str, Map<String, Value>)],
476 sections: Vec<(String, Map<String, Value>)>,
477 _origin: &ChangeOrigin,
478 ) -> std::io::Result<ConditionalUpdate> {
479 self.change(|doc| {
480 expected
481 .iter()
482 .all(|(name, expected)| match doc.get(*name) {
483 Some(Value::Object(section)) => section == expected,
484 _ => expected.is_empty(),
485 })
486 .then_some(sections)
487 })
488 }
489
490 fn revision(&self) -> u64 {
491 self.revision.load(Ordering::Acquire)
492 }
493
494 fn changes(&self) -> &ChangeSignal {
495 &self.changes
496 }
497}
498
499#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
501pub struct SettingsStamp(pub u64);
502
503#[must_use]
506pub fn parse(text: &str) -> Map<String, Value> {
507 match serde_json::from_str::<Value>(text) {
508 Ok(Value::Object(m)) => m,
509 _ => Map::new(),
510 }
511}
512
513#[must_use]
516pub fn section_of(mut doc: Map<String, Value>, name: &str) -> Map<String, Value> {
517 match doc.remove(name) {
518 Some(Value::Object(m)) => m,
519 _ => Map::new(),
520 }
521}
522
523#[must_use]
525pub fn load_section_in(source: &dyn SettingsSource, name: &str) -> Map<String, Value> {
526 section_of(source.load(), name)
527}
528
529#[must_use]
533pub fn profile(root: &std::path::Path) -> Arc<HostDocument> {
534 static PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<HostDocument>)>> = Mutex::new(Vec::new());
535 let mut profiles = PROFILES.lock_recover();
536 if let Some((_, held)) = profiles.iter().find(|(held, _)| held == root) {
537 return Arc::clone(held);
538 }
539 let file = root.join(PROFILE_FILE);
540 let kept = std::fs::read(&file)
541 .ok()
542 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
543 .unwrap_or_default();
544 let document = Arc::new(HostDocument::new(kept, move |document| {
545 let bytes = serde_json::to_vec(document).map_err(std::io::Error::other)?;
546 if let Some(parent) = file.parent() {
547 std::fs::create_dir_all(parent)?;
548 }
549 let partial = file.with_extension("json.partial");
550 std::fs::write(&partial, bytes)?;
551 std::fs::rename(&partial, &file)
552 }));
553 profiles.push((root.to_owned(), Arc::clone(&document)));
554 document
555}
556
557pub fn keep_profile(root: &std::path::Path, source: impl FnOnce() -> Arc<dyn SettingsSource>) {
563 let mut kept = KEPT_PROFILES.lock_recover();
564 if !kept.iter().any(|(held, _)| held == root) {
565 kept.push((root.to_owned(), source()));
566 }
567}
568
569#[must_use]
572pub fn profile_source(root: &std::path::Path) -> Arc<dyn SettingsSource> {
573 let kept = KEPT_PROFILES
574 .lock_recover()
575 .iter()
576 .find(|(held, _)| held == root)
577 .map(|(_, source)| Arc::clone(source));
578 kept.unwrap_or_else(|| profile(root))
579}
580
581static KEPT_PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<dyn SettingsSource>)>> =
582 Mutex::new(Vec::new());
583
584const PROFILE_FILE: &str = "settings.json";
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590 use serde_json::json;
591
592 fn object(value: Value) -> Map<String, Value> {
593 let Value::Object(map) = value else {
594 panic!("not an object")
595 };
596 map
597 }
598
599 tilo_test_env::scenario! {
600 fn a_host_document_stores_what_its_persist_accepts;
601
602 phase host_document_merges_persists_then_publishes;
603 {
604 let persisted = Arc::new(Mutex::new(Vec::new()));
605 let sink = Arc::clone(&persisted);
606 let doc = HostDocument::new(
607 object(json!({"region": {"locale": "de-DE"}, "power": 3})),
608 move |doc| {
609 sink.lock().unwrap().push(Value::Object(doc.clone()));
610 Ok(())
611 },
612 );
613 let before = doc.revision();
614 doc.update_section("power", object(json!({"idle": 5})))
615 .unwrap();
616 doc.update_section("region", object(json!({"units": "metric"})))
617 .unwrap();
618 let expected =
619 json!({"region": {"locale": "de-DE", "units": "metric"}, "power": {"idle": 5}});
620 assert_eq!(Value::Object(doc.load()), expected);
621 assert_eq!(persisted.lock().unwrap().last(), Some(&expected));
622 assert_eq!(doc.revision(), before + 2);
623 }
624
625 phase a_conditional_section_update_stores_only_over_what_it_read;
626 {
627 let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| Ok(()));
628 let read = object(json!({"x": 1}));
629 assert!(matches!(
630 compare_update_section(&doc, "a", &read, object(json!({"x": 2}))).unwrap(),
631 ConditionalUpdate::Stored
632 ));
633 assert!(matches!(
634 compare_update_section(&doc, "a", &read, object(json!({"x": 3}))).unwrap(),
635 ConditionalUpdate::Superseded
636 ));
637 assert!(matches!(
638 compare_update_section(&doc, "new", &Map::new(), object(json!({"y": 1})))
639 .unwrap(),
640 ConditionalUpdate::Stored
641 ));
642 assert_eq!(
643 Value::Object(doc.load()),
644 json!({"a": {"x": 2}, "new": {"y": 1}})
645 );
646 }
647
648 phase a_refused_persist_leaves_the_document_unchanged;
649 {
650 let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| {
651 Err(std::io::Error::other("quota"))
652 });
653 let before = doc.revision();
654 assert!(doc.update_section("a", object(json!({"x": 2}))).is_err());
655 assert_eq!(Value::Object(doc.load()), json!({"a": {"x": 1}}));
656 assert_eq!(doc.revision(), before);
657 }
658 }
659
660 #[test]
661 fn a_scoped_document_is_its_threads_alone_and_ends_with_its_scope() {
662 let document = |mode: &str| -> Arc<dyn SettingsSource> {
663 Arc::new(HostDocument::new(
664 object(json!({"appearance": {"mode": mode}})),
665 |_| Ok(()),
666 ))
667 };
668 let mode = || -> Option<String> {
669 let doc = installed_source()?.load();
670 Some(doc.get("appearance")?.get("mode")?.as_str()?.to_owned())
671 };
672 let outer = scoped_source(Some(document("light")));
673 assert_eq!(mode().as_deref(), Some("light"));
674 let elsewhere = std::thread::spawn(move || mode().as_deref() != Some("light"))
675 .join()
676 .unwrap_or(false);
677 assert!(elsewhere);
678 {
679 let _inner = scoped_source(Some(document("dark")));
680 assert_eq!(mode().as_deref(), Some("dark"));
681 }
682 assert_eq!(mode().as_deref(), Some("light"));
683 drop(outer);
684 assert!(SCOPED.with(|scoped| scoped.borrow().is_empty()));
685 }
686}