aidaemon_work/scheduler/
needs_model.rs1use std::collections::BTreeSet;
5use std::sync::Mutex;
6
7use aidaemon_tools::services::SettingsStore;
8use tracing::warn;
9
10pub const GOALS_KEY: &str = "needs_model_noticed_goals";
12pub const TRIGGERS_KEY: &str = "needs_model_noticed_triggers";
14
15pub struct NeedsModelNotices {
18 key: &'static str,
19 told: Mutex<Option<BTreeSet<String>>>,
21}
22
23impl NeedsModelNotices {
24 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 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 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 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
101pub 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 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 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 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}