capri-core: add store module
This commit is contained in:
1 file changed
+85
@@ -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<Settings>,
|
||||
}
|
||||
|
||||
impl SettingsStore {
|
||||
pub fn new(paths: Paths, settings: Settings) -> Arc<Self> {
|
||||
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<Settings> {
|
||||
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<T: Section>(&self) -> T {
|
||||
self.tx.borrow().section()
|
||||
}
|
||||
|
||||
pub fn set_section<T: 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>(), Demo::default());
|
||||
store.set_section(&Demo { enabled: true, level: 3 }).unwrap();
|
||||
assert!(rx.has_changed().unwrap());
|
||||
assert_eq!(Settings::load(&paths).unwrap().section::<Demo>().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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user