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
283#[derive(Clone, Debug, PartialEq, Eq)]
284pub struct DeferredFailure {
285 pub sections: Vec<String>,
286 pub error: String,
287}
288
289pub fn install_source(source: Option<Arc<dyn SettingsSource>>) {
294 *SOURCE.write_recover() = source;
295 INSTALLED.fetch_add(1, Ordering::AcqRel);
296}
297
298static INSTALLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
300
301#[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 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
351pub 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 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(¤t))])
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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
479pub struct SettingsStamp(pub u64);
480
481#[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#[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#[must_use]
503pub fn load_section_in(source: &dyn SettingsSource, name: &str) -> Map<String, Value> {
504 section_of(source.load(), name)
505}
506
507#[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
535pub 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#[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
562const 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}