diff --git a/crates/capri-core/src/store.rs b/crates/capri-core/src/store.rs new file mode 100644 index 0000000..85bb8ca --- /dev/null +++ b/crates/capri-core/src/store.rs @@ -0,0 +1,85 @@ +//! Live settings shared by every service: one owner, saved atomically, changes broadcast. +use std::sync::Arc; + +use anyhow::Result; +use tokio::sync::watch; + +use crate::settings::Section; +use crate::{Paths, Settings}; + +pub struct SettingsStore { + paths: Paths, + tx: watch::Sender, +} + +impl SettingsStore { + pub fn new(paths: Paths, settings: Settings) -> Arc { + Arc::new(Self { paths, tx: watch::Sender::new(settings) }) + } + + pub fn paths(&self) -> &Paths { + &self.paths + } + + /// Snapshot of the current settings. + pub fn get(&self) -> Settings { + self.tx.borrow().clone() + } + + /// Receives every saved change (`changed().await`, then `borrow()`). + pub fn subscribe(&self) -> watch::Receiver { + self.tx.subscribe() + } + + /// Applies a change, saves it, and notifies subscribers. Nothing is applied if saving fails. + pub fn update(&self, change: impl FnOnce(&mut Settings)) -> Result<()> { + let mut next = self.get(); + change(&mut next); + if next == *self.tx.borrow() { + return Ok(()); + } + next.save(&self.paths)?; + self.tx.send_replace(next); + Ok(()) + } + + pub fn section(&self) -> T { + self.tx.borrow().section() + } + + pub fn set_section(&self, value: &T) -> Result<()> { + self.update(|s| s.set_section(value)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::{Deserialize, Serialize}; + + #[derive(Serialize, Deserialize, Default, Clone, PartialEq, Debug)] + #[serde(default)] + struct Demo { + enabled: bool, + level: u8, + } + impl Section for Demo { + const NAME: &'static str = "demo"; + } + + #[test] + fn sections_roundtrip_and_notify() { + let dir = tempfile::tempdir().unwrap(); + let paths = Paths::under(dir.path().to_path_buf()); + paths.ensure().unwrap(); + let store = SettingsStore::new(paths.clone(), Settings::default()); + let mut rx = store.subscribe(); + assert_eq!(store.section::(), Demo::default()); + store.set_section(&Demo { enabled: true, level: 3 }).unwrap(); + assert!(rx.has_changed().unwrap()); + assert_eq!(Settings::load(&paths).unwrap().section::().level, 3); + let _ = rx.borrow_and_update(); + store.set_section(&Demo { enabled: true, level: 3 }).unwrap(); + assert!(!rx.has_changed().unwrap(), "unchanged values are not broadcast"); + } +}