aidaemon-work 0.27.3

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
Documentation
//! The automations already told they need a model, kept in the settings
//! table so a restart does not tell them again.

use std::collections::BTreeSet;
use std::sync::Mutex;

use aidaemon_tools::services::SettingsStore;
use tracing::warn;

/// The settings key for scheduled tasks and mandates (by goal id).
pub const GOALS_KEY: &str = "needs_model_noticed_goals";
/// The settings key for triggers (by source).
pub const TRIGGERS_KEY: &str = "needs_model_noticed_triggers";

/// Who was told they need a model while none is connected: one notice per
/// automation, across restarts, until a model is connected.
pub struct NeedsModelNotices {
    key: &'static str,
    /// What the store holds, once read.
    told: Mutex<Option<BTreeSet<String>>>,
}

impl NeedsModelNotices {
    /// The record under `key` in the settings table.
    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)
    }

    /// The record, read from `store` the first time.
    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");
        }
    }

    /// Record that `name` is told it needs a model: `true` the first time
    /// since a model was last connected, even across restarts.
    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
    }

    /// A model is connected: forget who was told, so a model removed later
    /// tells each automation again. Writes only when something was recorded.
    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;
        }
    }
}

/// Clear each of `records` whenever `connected` says a model is connected
/// (at once if one is now), until the sender is gone.
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);

        // A restart: a new record over the same store.
        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);

        // Another key's record is its own.
        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);

        // Connected while the daemon was down: the next start clears it.
        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());
    }
}