use std::collections::BTreeSet;
use std::sync::Mutex;
use aidaemon_tools::services::SettingsStore;
use tracing::warn;
pub const GOALS_KEY: &str = "needs_model_noticed_goals";
pub const TRIGGERS_KEY: &str = "needs_model_noticed_triggers";
pub struct NeedsModelNotices {
key: &'static str,
told: Mutex<Option<BTreeSet<String>>>,
}
impl NeedsModelNotices {
pub fn new(key: &'static str) -> Self {
Self {
key,
told: Mutex::new(None),
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Option<BTreeSet<String>>> {
self.told
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
async fn load<S: SettingsStore + ?Sized>(&self, store: &S) {
if self.lock().is_some() {
return;
}
let stored = match store.get_setting(self.key).await {
Ok(Some(raw)) if !raw.is_empty() => serde_json::from_str::<BTreeSet<String>>(&raw)
.unwrap_or_else(|error| {
warn!(key = self.key, %error, "Unreadable needs-a-model record; starting empty");
BTreeSet::new()
}),
Ok(_) => BTreeSet::new(),
Err(error) => {
warn!(key = self.key, %error, "Failed to read the needs-a-model record");
BTreeSet::new()
}
};
let mut told = self.lock();
if told.is_none() {
*told = Some(stored);
}
}
async fn save<S: SettingsStore + ?Sized>(&self, store: &S, told: &BTreeSet<String>) {
let raw = serde_json::to_string(told).unwrap_or_else(|_| "[]".into());
if let Err(error) = store.set_setting(self.key, &raw).await {
warn!(key = self.key, %error, "Failed to save the needs-a-model record");
}
}
pub async fn first<S: SettingsStore + ?Sized>(&self, store: &S, name: &str) -> bool {
self.load(store).await;
let snapshot = {
let mut told = self.lock();
let told = told.get_or_insert_with(BTreeSet::new);
if !told.insert(name.to_string()) {
return false;
}
told.clone()
};
self.save(store, &snapshot).await;
true
}
pub async fn clear<S: SettingsStore + ?Sized>(&self, store: &S) {
self.load(store).await;
let had = {
let mut told = self.lock();
let told = told.get_or_insert_with(BTreeSet::new);
let had = !told.is_empty();
told.clear();
had
};
if had {
self.save(store, &BTreeSet::new()).await;
}
}
}
pub fn clear_on_connect(
mut connected: tokio::sync::watch::Receiver<bool>,
settings: std::sync::Arc<dyn SettingsStore>,
records: Vec<std::sync::Arc<NeedsModelNotices>>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
if *connected.borrow_and_update() {
for record in &records {
record.clear(settings.as_ref()).await;
}
}
if connected.changed().await.is_err() {
break;
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use std::collections::HashMap;
#[derive(Default)]
struct Settings(Mutex<HashMap<String, String>>);
#[async_trait]
impl SettingsStore for Settings {
async fn get_setting(&self, key: &str) -> anyhow::Result<Option<String>> {
Ok(self.0.lock().unwrap().get(key).cloned())
}
async fn set_setting(&self, key: &str, value: &str) -> anyhow::Result<()> {
self.0.lock().unwrap().insert(key.into(), value.into());
Ok(())
}
}
#[tokio::test]
async fn each_automation_is_told_once_across_a_restart() {
let store = Settings::default();
let notices = NeedsModelNotices::new(GOALS_KEY);
assert!(notices.first(&store, "goal-synthetic-1").await);
assert!(!notices.first(&store, "goal-synthetic-1").await);
assert!(notices.first(&store, "goal-synthetic-2").await);
let restarted = NeedsModelNotices::new(GOALS_KEY);
assert!(!restarted.first(&store, "goal-synthetic-1").await);
assert!(!restarted.first(&store, "goal-synthetic-2").await);
assert!(restarted.first(&store, "goal-synthetic-3").await);
let triggers = NeedsModelNotices::new(TRIGGERS_KEY);
assert!(triggers.first(&store, "goal-synthetic-1").await);
}
#[tokio::test]
async fn a_connected_model_forgets_so_a_removed_one_tells_again() {
let store = Settings::default();
let notices = NeedsModelNotices::new(GOALS_KEY);
assert!(notices.first(&store, "goal-synthetic-1").await);
notices.clear(&store).await;
assert!(notices.first(&store, "goal-synthetic-1").await);
notices.first(&store, "goal-synthetic-2").await;
let restarted = NeedsModelNotices::new(GOALS_KEY);
restarted.clear(&store).await;
let again = NeedsModelNotices::new(GOALS_KEY);
assert!(again.first(&store, "goal-synthetic-1").await);
assert!(again.first(&store, "goal-synthetic-2").await);
}
#[tokio::test]
async fn clearing_with_nothing_told_writes_nothing() {
let store = Settings::default();
NeedsModelNotices::new(GOALS_KEY).clear(&store).await;
assert!(store.0.lock().unwrap().is_empty());
}
}