Skip to main content

aidaemon_work/scheduler/
needs_model.rs

1//! The automations already told they need a model, kept in the settings
2//! table so a restart does not tell them again.
3
4use std::collections::BTreeSet;
5use std::sync::Mutex;
6
7use aidaemon_tools::services::SettingsStore;
8use tracing::warn;
9
10/// The settings key for scheduled tasks and mandates (by goal id).
11pub const GOALS_KEY: &str = "needs_model_noticed_goals";
12/// The settings key for triggers (by source).
13pub const TRIGGERS_KEY: &str = "needs_model_noticed_triggers";
14
15/// Who was told they need a model while none is connected: one notice per
16/// automation, across restarts, until a model is connected.
17pub struct NeedsModelNotices {
18    key: &'static str,
19    /// What the store holds, once read.
20    told: Mutex<Option<BTreeSet<String>>>,
21}
22
23impl NeedsModelNotices {
24    /// The record under `key` in the settings table.
25    pub fn new(key: &'static str) -> Self {
26        Self {
27            key,
28            told: Mutex::new(None),
29        }
30    }
31
32    fn lock(&self) -> std::sync::MutexGuard<'_, Option<BTreeSet<String>>> {
33        self.told
34            .lock()
35            .unwrap_or_else(std::sync::PoisonError::into_inner)
36    }
37
38    /// The record, read from `store` the first time.
39    async fn load<S: SettingsStore + ?Sized>(&self, store: &S) {
40        if self.lock().is_some() {
41            return;
42        }
43        let stored = match store.get_setting(self.key).await {
44            Ok(Some(raw)) if !raw.is_empty() => serde_json::from_str::<BTreeSet<String>>(&raw)
45                .unwrap_or_else(|error| {
46                    warn!(key = self.key, %error, "Unreadable needs-a-model record; starting empty");
47                    BTreeSet::new()
48                }),
49            Ok(_) => BTreeSet::new(),
50            Err(error) => {
51                warn!(key = self.key, %error, "Failed to read the needs-a-model record");
52                BTreeSet::new()
53            }
54        };
55        let mut told = self.lock();
56        if told.is_none() {
57            *told = Some(stored);
58        }
59    }
60
61    async fn save<S: SettingsStore + ?Sized>(&self, store: &S, told: &BTreeSet<String>) {
62        let raw = serde_json::to_string(told).unwrap_or_else(|_| "[]".into());
63        if let Err(error) = store.set_setting(self.key, &raw).await {
64            warn!(key = self.key, %error, "Failed to save the needs-a-model record");
65        }
66    }
67
68    /// Record that `name` is told it needs a model: `true` the first time
69    /// since a model was last connected, even across restarts.
70    pub async fn first<S: SettingsStore + ?Sized>(&self, store: &S, name: &str) -> bool {
71        self.load(store).await;
72        let snapshot = {
73            let mut told = self.lock();
74            let told = told.get_or_insert_with(BTreeSet::new);
75            if !told.insert(name.to_string()) {
76                return false;
77            }
78            told.clone()
79        };
80        self.save(store, &snapshot).await;
81        true
82    }
83
84    /// A model is connected: forget who was told, so a model removed later
85    /// tells each automation again. Writes only when something was recorded.
86    pub async fn clear<S: SettingsStore + ?Sized>(&self, store: &S) {
87        self.load(store).await;
88        let had = {
89            let mut told = self.lock();
90            let told = told.get_or_insert_with(BTreeSet::new);
91            let had = !told.is_empty();
92            told.clear();
93            had
94        };
95        if had {
96            self.save(store, &BTreeSet::new()).await;
97        }
98    }
99}
100
101/// Clear each of `records` whenever `connected` says a model is connected
102/// (at once if one is now), until the sender is gone.
103pub fn clear_on_connect(
104    mut connected: tokio::sync::watch::Receiver<bool>,
105    settings: std::sync::Arc<dyn SettingsStore>,
106    records: Vec<std::sync::Arc<NeedsModelNotices>>,
107) -> tokio::task::JoinHandle<()> {
108    tokio::spawn(async move {
109        loop {
110            if *connected.borrow_and_update() {
111                for record in &records {
112                    record.clear(settings.as_ref()).await;
113                }
114            }
115            if connected.changed().await.is_err() {
116                break;
117            }
118        }
119    })
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use async_trait::async_trait;
126    use std::collections::HashMap;
127
128    #[derive(Default)]
129    struct Settings(Mutex<HashMap<String, String>>);
130
131    #[async_trait]
132    impl SettingsStore for Settings {
133        async fn get_setting(&self, key: &str) -> anyhow::Result<Option<String>> {
134            Ok(self.0.lock().unwrap().get(key).cloned())
135        }
136
137        async fn set_setting(&self, key: &str, value: &str) -> anyhow::Result<()> {
138            self.0.lock().unwrap().insert(key.into(), value.into());
139            Ok(())
140        }
141    }
142
143    #[tokio::test]
144    async fn each_automation_is_told_once_across_a_restart() {
145        let store = Settings::default();
146        let notices = NeedsModelNotices::new(GOALS_KEY);
147        assert!(notices.first(&store, "goal-synthetic-1").await);
148        assert!(!notices.first(&store, "goal-synthetic-1").await);
149        assert!(notices.first(&store, "goal-synthetic-2").await);
150
151        // A restart: a new record over the same store.
152        let restarted = NeedsModelNotices::new(GOALS_KEY);
153        assert!(!restarted.first(&store, "goal-synthetic-1").await);
154        assert!(!restarted.first(&store, "goal-synthetic-2").await);
155        assert!(restarted.first(&store, "goal-synthetic-3").await);
156
157        // Another key's record is its own.
158        let triggers = NeedsModelNotices::new(TRIGGERS_KEY);
159        assert!(triggers.first(&store, "goal-synthetic-1").await);
160    }
161
162    #[tokio::test]
163    async fn a_connected_model_forgets_so_a_removed_one_tells_again() {
164        let store = Settings::default();
165        let notices = NeedsModelNotices::new(GOALS_KEY);
166        assert!(notices.first(&store, "goal-synthetic-1").await);
167        notices.clear(&store).await;
168        assert!(notices.first(&store, "goal-synthetic-1").await);
169
170        // Connected while the daemon was down: the next start clears it.
171        notices.first(&store, "goal-synthetic-2").await;
172        let restarted = NeedsModelNotices::new(GOALS_KEY);
173        restarted.clear(&store).await;
174        let again = NeedsModelNotices::new(GOALS_KEY);
175        assert!(again.first(&store, "goal-synthetic-1").await);
176        assert!(again.first(&store, "goal-synthetic-2").await);
177    }
178
179    #[tokio::test]
180    async fn clearing_with_nothing_told_writes_nothing() {
181        let store = Settings::default();
182        NeedsModelNotices::new(GOALS_KEY).clear(&store).await;
183        assert!(store.0.lock().unwrap().is_empty());
184    }
185}