1use crate::protocol::{ClientMessage, DaemonMessage, SearchResultWire};
2use fount_core::{IndexCatalog, SearchResult};
3use std::thread;
4use thiserror::Error;
5use tokio::sync::{mpsc, oneshot};
6use tracing::{debug, error, info, warn};
7
8#[derive(Debug, Error)]
10pub enum EngineError {
11 #[error("Search engine actor channel closed")]
12 ActorStopped,
13 #[error("Failed to launch entry: {0}")]
14 LaunchFailed(String),
15}
16
17pub enum EngineCommand {
19 Search {
21 query: String,
22 limit: usize,
23 reply: oneshot::Sender<Vec<SearchResult>>,
24 },
25 Exec {
27 id: String,
28 execute_process: bool,
29 reply: oneshot::Sender<Result<(), String>>,
30 },
31 Reload { reply: oneshot::Sender<usize> },
33 Shutdown { reply: oneshot::Sender<()> },
35}
36
37#[derive(Clone, Debug)]
39pub struct EngineHandle {
40 tx: mpsc::Sender<EngineCommand>,
41}
42
43impl EngineHandle {
44 pub fn spawn() -> Self {
47 let catalog = IndexCatalog::from_default_config();
48 Self::spawn_with_catalog(catalog)
49 }
50
51 pub fn spawn_with_catalog(mut catalog: IndexCatalog) -> Self {
56 let (tx, mut rx) = mpsc::channel::<EngineCommand>(256);
57
58 catalog.tick(10);
60
61 thread::Builder::new()
62 .name("fount-engine-actor".into())
63 .spawn(move || {
64 info!(
65 entries = catalog.len(),
66 "Search engine actor started on dedicated OS thread"
67 );
68
69 while let Some(cmd) = rx.blocking_recv() {
70 match cmd {
71 EngineCommand::Search {
72 query,
73 limit,
74 reply,
75 } => {
76 catalog.search(&query);
77 catalog.tick(10);
78 let results = catalog.results(limit);
79 let _ = reply.send(results);
80 }
81 EngineCommand::Exec {
82 id,
83 execute_process,
84 reply,
85 } => {
86 let outcome = match catalog.get_by_id(&id).cloned() {
87 Some(entry) => {
88 let exec_res = if execute_process {
89 entry
90 .action
91 .execute()
92 .map(|_| ())
93 .map_err(|e| e.to_string())
94 } else {
95 Ok(())
96 };
97
98 if exec_res.is_ok() {
99 let new_score = catalog.record_launch(&id);
100 debug!(id = %id, new_score, "Recorded launch in frecency store");
101 if let Err(e) = catalog.save_frecency() {
102 warn!(error = %e, "Failed to save frecency store to disk");
103 }
104 }
105 exec_res
106 }
107 None => Err(format!("Entry not found: '{id}'")),
108 };
109 let _ = reply.send(outcome);
110 }
111 EngineCommand::Reload { reply } => {
112 let count = catalog.reload();
113 catalog.tick(10);
114 info!(entries = count, "Reloaded search catalog");
115 let _ = reply.send(count);
116 }
117 EngineCommand::Shutdown { reply } => {
118 info!("Shutting down search engine actor");
119 if let Err(e) = catalog.save_frecency() {
120 error!(error = %e, "Failed to save frecency state during shutdown");
121 }
122 let _ = reply.send(());
123 break;
124 }
125 }
126 }
127 })
128 .expect("Failed to spawn fount-engine-actor thread");
129
130 Self { tx }
131 }
132
133 pub async fn search(
135 &self,
136 query: impl Into<String>,
137 limit: usize,
138 ) -> Result<Vec<SearchResult>, EngineError> {
139 let (reply_tx, reply_rx) = oneshot::channel();
140 self.tx
141 .send(EngineCommand::Search {
142 query: query.into(),
143 limit,
144 reply: reply_tx,
145 })
146 .await
147 .map_err(|_| EngineError::ActorStopped)?;
148
149 reply_rx.await.map_err(|_| EngineError::ActorStopped)
150 }
151
152 pub async fn launch(
154 &self,
155 id: impl Into<String>,
156 execute_process: bool,
157 ) -> Result<(), EngineError> {
158 let (reply_tx, reply_rx) = oneshot::channel();
159 self.tx
160 .send(EngineCommand::Exec {
161 id: id.into(),
162 execute_process,
163 reply: reply_tx,
164 })
165 .await
166 .map_err(|_| EngineError::ActorStopped)?;
167
168 match reply_rx.await {
169 Ok(Ok(())) => Ok(()),
170 Ok(Err(msg)) => Err(EngineError::LaunchFailed(msg)),
171 Err(_) => Err(EngineError::ActorStopped),
172 }
173 }
174
175 pub async fn reload(&self) -> Result<usize, EngineError> {
177 let (reply_tx, reply_rx) = oneshot::channel();
178 self.tx
179 .send(EngineCommand::Reload { reply: reply_tx })
180 .await
181 .map_err(|_| EngineError::ActorStopped)?;
182
183 reply_rx.await.map_err(|_| EngineError::ActorStopped)
184 }
185
186 pub async fn shutdown(&self) -> Result<(), EngineError> {
188 let (reply_tx, reply_rx) = oneshot::channel();
189 self.tx
190 .send(EngineCommand::Shutdown { reply: reply_tx })
191 .await
192 .map_err(|_| EngineError::ActorStopped)?;
193
194 reply_rx.await.map_err(|_| EngineError::ActorStopped)
195 }
196
197 pub async fn dispatch(&self, msg: ClientMessage) -> DaemonMessage {
199 match msg {
200 ClientMessage::Search { query, limit } => {
201 match self.search(query.clone(), limit as usize).await {
202 Ok(results) => DaemonMessage::Results {
203 query,
204 items: results.into_iter().map(SearchResultWire::from).collect(),
205 },
206 Err(e) => DaemonMessage::Error {
207 message: e.to_string(),
208 },
209 }
210 }
211 ClientMessage::Exec { id, execute } => match self.launch(id.clone(), execute).await {
212 Ok(()) => DaemonMessage::Launched {
213 id,
214 success: true,
215 error: None,
216 },
217 Err(e) => DaemonMessage::Launched {
218 id,
219 success: false,
220 error: Some(e.to_string()),
221 },
222 },
223 ClientMessage::Reload => match self.reload().await {
224 Ok(count) => DaemonMessage::Reloaded {
225 count: count as u32,
226 },
227 Err(e) => DaemonMessage::Error {
228 message: e.to_string(),
229 },
230 },
231 ClientMessage::Ping => DaemonMessage::Pong,
232 }
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239 use fount_core::FrecencyStore;
240 use std::fs;
241 use tempfile::tempdir;
242
243 #[tokio::test]
244 async fn test_actor_search_launch_and_frecency() {
245 let temp = tempdir().unwrap();
246 let apps_dir = temp.path().join("applications");
247 let frecency_path = temp.path().join("frecency.bin");
248 fs::create_dir_all(&apps_dir).unwrap();
249
250 fs::write(
251 apps_dir.join("code.desktop"),
252 r#"
253[Desktop Entry]
254Type=Application
255Name=Code Editor
256Exec=code
257"#,
258 )
259 .unwrap();
260
261 fs::write(
262 apps_dir.join("console.desktop"),
263 r#"
264[Desktop Entry]
265Type=Application
266Name=Console Terminal
267Exec=kgx
268"#,
269 )
270 .unwrap();
271
272 let mut catalog = IndexCatalog::with_dirs(vec![apps_dir.clone()]);
273 catalog.set_frecency_store(FrecencyStore::open_or_create(frecency_path.clone()));
274 catalog.set_include_system_actions(true);
275
276 let handle = EngineHandle::spawn_with_catalog(catalog);
277
278 let results = handle.search("code", 5).await.unwrap();
280 assert!(!results.is_empty());
281 assert_eq!(results[0].entry.id, "code.desktop");
282
283 let sys_results = handle.search("shutdown", 5).await.unwrap();
285 assert!(!sys_results.is_empty());
286 assert_eq!(sys_results[0].entry.id, "action:poweroff");
287
288 for _ in 0..5 {
290 handle.launch("console.desktop", false).await.unwrap();
291 }
292 assert!(frecency_path.is_file());
293
294 let recent = handle.search("", 5).await.unwrap();
296 assert_eq!(recent[0].entry.id, "console.desktop");
297
298 let resp = handle
300 .dispatch(ClientMessage::Search {
301 query: "co".into(),
302 limit: 5,
303 })
304 .await;
305 match resp {
306 DaemonMessage::Results { items, .. } => {
307 assert!(!items.is_empty());
308 assert_eq!(items[0].id, "console.desktop");
309 }
310 other => panic!("Unexpected daemon response: {other:?}"),
311 }
312
313 let count = handle.reload().await.unwrap();
315 assert_eq!(count, 7); handle.shutdown().await.unwrap();
318 }
319}