Skip to main content

fount_daemon/ipc/
unix_socket.rs

1use crate::engine_actor::EngineHandle;
2use crate::protocol::{
3    ExecParams, ExecResultPayload, ReloadResultPayload, RpcError, RpcId, RpcRequest, RpcResponse,
4    SearchParams, SearchResultPayload,
5};
6use serde::Serialize;
7use std::env;
8use std::io;
9use std::path::{Path, PathBuf};
10use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
11use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
12use tokio::net::{UnixListener, UnixStream};
13use tracing::{debug, info, warn};
14
15/// Maximum allowed NDJSON line length (1 MiB) to prevent unbounded memory growth.
16const MAX_LINE_SIZE: usize = 1024 * 1024;
17
18/// Resolves the default Unix Domain Socket path:
19/// `$XDG_RUNTIME_DIR/fount.sock` (fallback `/tmp/fount.sock`).
20pub fn default_socket_path() -> PathBuf {
21    if let Ok(runtime_dir) = env::var("XDG_RUNTIME_DIR")
22        && !runtime_dir.is_empty()
23    {
24        return PathBuf::from(runtime_dir).join("fount.sock");
25    }
26    PathBuf::from("/tmp/fount.sock")
27}
28
29/// Reads a single newline-delimited JSON line up to `MAX_LINE_SIZE` bytes.
30/// Returns `Ok(None)` on clean EOF.
31pub async fn read_json_line<R: AsyncBufReadExt + Unpin>(
32    reader: &mut R,
33) -> io::Result<Option<String>> {
34    let mut line = String::new();
35    let bytes_read = reader
36        .take((MAX_LINE_SIZE + 1) as u64)
37        .read_line(&mut line)
38        .await?;
39
40    if bytes_read == 0 {
41        return Ok(None);
42    }
43
44    if bytes_read > MAX_LINE_SIZE {
45        return Err(io::Error::new(
46            io::ErrorKind::InvalidData,
47            format!("Line exceeds maximum allowed size ({MAX_LINE_SIZE} bytes)"),
48        ));
49    }
50
51    Ok(Some(line))
52}
53
54/// Serializes `payload` as compact single-line JSON terminated by `\n` and flushes.
55pub async fn write_json_line<W: AsyncWriteExt + Unpin>(
56    writer: &mut W,
57    payload: &impl Serialize,
58) -> io::Result<()> {
59    let mut serialized = serde_json::to_string(payload).map_err(io::Error::other)?;
60    serialized.push('\n');
61    writer.write_all(serialized.as_bytes()).await?;
62    writer.flush().await
63}
64
65/// Binds a `UnixListener` to `socket_path` (cleaning up any stale socket file first).
66pub fn bind_unix_listener(socket_path: &Path) -> io::Result<UnixListener> {
67    if let Some(parent) = socket_path.parent() {
68        std::fs::create_dir_all(parent)?;
69    }
70
71    if socket_path.exists() {
72        let _ = std::fs::remove_file(socket_path);
73    }
74
75    UnixListener::bind(socket_path)
76}
77
78/// Runs the Unix Domain Socket IPC server loop using an already-bound `UnixListener`.
79pub async fn serve_unix_listener(listener: UnixListener, engine: EngineHandle) -> io::Result<()> {
80    loop {
81        let (stream, _addr) = listener.accept().await?;
82        let engine_clone = engine.clone();
83
84        tokio::spawn(async move {
85            if let Err(e) = handle_client_connection(stream, engine_clone).await {
86                debug!(error = %e, "Unix socket client connection ended with error");
87            }
88        });
89    }
90}
91
92/// Binds and runs the Unix Domain Socket IPC server at `socket_path`.
93pub async fn run_unix_socket_server(
94    socket_path: PathBuf,
95    engine: EngineHandle,
96) -> io::Result<()> {
97    let listener = bind_unix_listener(&socket_path)?;
98    info!(path = %socket_path.display(), "Unix domain socket server listening (JSON-RPC 2.0 NDJSON)");
99    serve_unix_listener(listener, engine).await
100}
101
102/// Handles a single persistent client connection, processing NDJSON JSON-RPC 2.0 requests.
103async fn handle_client_connection(stream: UnixStream, engine: EngineHandle) -> io::Result<()> {
104    let (read_half, mut write_half) = stream.into_split();
105    let mut reader = BufReader::new(read_half);
106
107    while let Some(line) = read_json_line(&mut reader).await? {
108        let trimmed = line.trim();
109        if trimmed.is_empty() {
110            continue;
111        }
112
113        let raw_value: serde_json::Value = match serde_json::from_str(trimmed) {
114            Ok(v) => v,
115            Err(e) => {
116                warn!(error = %e, "Malformed JSON on Unix socket");
117                let resp =
118                    RpcResponse::error(RpcId::Null, RpcError::parse_error(e.to_string()));
119                write_json_line(&mut write_half, &resp).await?;
120                continue;
121            }
122        };
123
124        let request: RpcRequest = match serde_json::from_value(raw_value) {
125            Ok(r) => r,
126            Err(e) => {
127                warn!(error = %e, "Invalid JSON-RPC request envelope on Unix socket");
128                let resp =
129                    RpcResponse::error(RpcId::Null, RpcError::invalid_request(e.to_string()));
130                write_json_line(&mut write_half, &resp).await?;
131                continue;
132            }
133        };
134
135        match request.into_client_message() {
136            Ok(client_msg) => {
137                let daemon_msg = engine.dispatch(client_msg).await;
138                if let Some(id) = request.id {
139                    let resp = RpcResponse::from_daemon_message(id, daemon_msg);
140                    write_json_line(&mut write_half, &resp).await?;
141                }
142            }
143            Err(rpc_err) => {
144                if let Some(id) = request.id {
145                    let resp = RpcResponse::error(id, rpc_err);
146                    write_json_line(&mut write_half, &resp).await?;
147                } else {
148                    debug!(error = %rpc_err.message, "Ignoring invalid JSON-RPC notification");
149                }
150            }
151        }
152    }
153
154    Ok(())
155}
156
157/// Async JSON-RPC 2.0 NDJSON client for communicating with the daemon over a Unix Domain Socket.
158pub struct UnixSocketClient {
159    reader: BufReader<OwnedReadHalf>,
160    writer: OwnedWriteHalf,
161    next_id: i64,
162}
163
164impl UnixSocketClient {
165    /// Connects to the daemon at `socket_path`.
166    pub async fn connect<P: AsRef<Path>>(socket_path: P) -> io::Result<Self> {
167        let stream = UnixStream::connect(socket_path).await?;
168        let (read_half, write_half) = stream.into_split();
169        Ok(Self {
170            reader: BufReader::new(read_half),
171            writer: write_half,
172            next_id: 1,
173        })
174    }
175
176    /// Sends a JSON-RPC 2.0 request with an auto-incremented numeric `id` and awaits the response.
177    pub async fn call(
178        &mut self,
179        method: impl Into<String>,
180        params: Option<serde_json::Value>,
181    ) -> io::Result<RpcResponse> {
182        let id = self.next_id;
183        self.next_id += 1;
184
185        let req = RpcRequest::new(RpcId::Number(id), method, params);
186        write_json_line(&mut self.writer, &req).await?;
187
188        let resp_line = read_json_line(&mut self.reader).await?.ok_or_else(|| {
189            io::Error::new(
190                io::ErrorKind::UnexpectedEof,
191                "Daemon closed connection before sending response",
192            )
193        })?;
194
195        serde_json::from_str(resp_line.trim()).map_err(io::Error::other)
196    }
197
198    /// Sends a JSON-RPC 2.0 notification (no `id`; daemon does not send a reply).
199    pub async fn notify(
200        &mut self,
201        method: impl Into<String>,
202        params: Option<serde_json::Value>,
203    ) -> io::Result<()> {
204        let req = RpcRequest::notification(method, params);
205        write_json_line(&mut self.writer, &req).await
206    }
207
208    /// Sends a raw NDJSON line and reads back one `RpcResponse` line (handy for testing protocol errors).
209    pub async fn send_raw_line(&mut self, raw: &str) -> io::Result<RpcResponse> {
210        let mut line = raw.to_string();
211        if !line.ends_with('\n') {
212            line.push('\n');
213        }
214        self.writer.write_all(line.as_bytes()).await?;
215        self.writer.flush().await?;
216
217        let resp_line = read_json_line(&mut self.reader).await?.ok_or_else(|| {
218            io::Error::new(
219                io::ErrorKind::UnexpectedEof,
220                "Daemon closed connection before sending response",
221            )
222        })?;
223
224        serde_json::from_str(resp_line.trim()).map_err(io::Error::other)
225    }
226
227    /// Sends a `"ping"` request and verifies the daemon responds with `"pong"`.
228    pub async fn ping(&mut self) -> io::Result<()> {
229        let resp = self.call("ping", None).await?;
230        let val = unwrap_rpc_result(resp)?;
231        if val.as_str() == Some("pong") {
232            Ok(())
233        } else {
234            Err(io::Error::other(format!("Unexpected ping result: {val}")))
235        }
236    }
237
238    /// Queries the daemon for up to `limit` fuzzy matches.
239    pub async fn search(
240        &mut self,
241        query: impl Into<String>,
242        limit: u32,
243    ) -> io::Result<SearchResultPayload> {
244        let params = serde_json::to_value(SearchParams {
245            query: query.into(),
246            limit,
247        })
248        .map_err(io::Error::other)?;
249        let resp = self.call("search", Some(params)).await?;
250        let val = unwrap_rpc_result(resp)?;
251        serde_json::from_value(val).map_err(io::Error::other)
252    }
253
254    /// Triggers execution (or frecency-only recording) for an entry ID.
255    pub async fn exec(
256        &mut self,
257        id: impl Into<String>,
258        execute: bool,
259    ) -> io::Result<ExecResultPayload> {
260        let params = serde_json::to_value(ExecParams {
261            id: id.into(),
262            execute,
263        })
264        .map_err(io::Error::other)?;
265        let resp = self.call("exec", Some(params)).await?;
266        let val = unwrap_rpc_result(resp)?;
267        serde_json::from_value(val).map_err(io::Error::other)
268    }
269
270    /// Triggers an index reload on the daemon and returns the new entry count.
271    pub async fn reload(&mut self) -> io::Result<ReloadResultPayload> {
272        let resp = self.call("reload", None).await?;
273        let val = unwrap_rpc_result(resp)?;
274        serde_json::from_value(val).map_err(io::Error::other)
275    }
276}
277
278fn unwrap_rpc_result(resp: RpcResponse) -> io::Result<serde_json::Value> {
279    if let Some(err) = resp.error {
280        return Err(io::Error::other(format!(
281            "JSON-RPC error {}: {}",
282            err.code, err.message
283        )));
284    }
285    resp.result
286        .ok_or_else(|| io::Error::other("JSON-RPC response missing both result and error"))
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use crate::protocol::{
293        ERR_EXEC_FAILED, ERR_INVALID_PARAMS, ERR_INVALID_REQUEST, ERR_METHOD_NOT_FOUND,
294        ERR_PARSE_ERROR,
295    };
296    use fount_core::{FrecencyStore, IndexCatalog};
297    use std::fs;
298    use tempfile::tempdir;
299
300    #[tokio::test]
301    async fn test_unix_socket_jsonrpc_streaming_and_errors() {
302        let temp = tempdir().unwrap();
303        let apps_dir = temp.path().join("applications");
304        let frecency_path = temp.path().join("frecency.bin");
305        let sock_path = temp.path().join("fount-test.sock");
306        fs::create_dir_all(&apps_dir).unwrap();
307
308        fs::write(
309            apps_dir.join("firefox.desktop"),
310            r#"
311[Desktop Entry]
312Type=Application
313Name=Firefox Web Browser
314Exec=firefox
315Icon=firefox
316"#,
317        )
318        .unwrap();
319
320        fs::write(
321            apps_dir.join("files.desktop"),
322            r#"
323[Desktop Entry]
324Type=Application
325Name=Files
326Exec=nautilus
327Icon=system-file-manager
328"#,
329        )
330        .unwrap();
331
332        let mut catalog = IndexCatalog::with_dirs(vec![apps_dir]);
333        catalog.set_frecency_store(FrecencyStore::open_or_create(frecency_path));
334        catalog.set_include_system_actions(true);
335
336        let engine = EngineHandle::spawn_with_catalog(catalog);
337        let listener = bind_unix_listener(&sock_path).unwrap();
338
339        let server_engine = engine.clone();
340        let server_task = tokio::spawn(async move {
341            let _ = serve_unix_listener(listener, server_engine).await;
342        });
343
344        // Connect client
345        let mut client = UnixSocketClient::connect(&sock_path).await.unwrap();
346
347        // 1. Ping -> Pong
348        client.ping().await.unwrap();
349
350        // 2. Simulate rapid keystroke streaming verifying JSON-RPC ID correlation
351        for (expected_id, keystroke) in [(2, "f"), (3, "fi"), (4, "fir"), (5, "fire")] {
352            let params = serde_json::to_value(SearchParams {
353                query: keystroke.into(),
354                limit: 5,
355            })
356            .unwrap();
357            let resp = client.call("search", Some(params)).await.unwrap();
358            assert_eq!(resp.id, RpcId::Number(expected_id));
359            assert!(resp.error.is_none());
360
361            let payload: SearchResultPayload =
362                serde_json::from_value(resp.result.unwrap()).unwrap();
363            assert_eq!(payload.query, keystroke);
364            assert!(!payload.items.is_empty());
365        }
366
367        // 3. Exec "files.desktop" (record frecency without spawning process)
368        let exec_res = client.exec("files.desktop", false).await.unwrap();
369        assert_eq!(exec_res.id, "files.desktop");
370        assert!(exec_res.success);
371
372        // 4. Search "fi" -> "files.desktop" should now rank #1 due to frecency
373        let search_res = client.search("fi", 5).await.unwrap();
374        assert_eq!(search_res.items[0].id, "files.desktop");
375
376        // 5. Notification (omitted id) executes with no reply, followed immediately by ping()
377        client
378            .notify(
379                "exec",
380                Some(serde_json::json!({ "id": "files.desktop", "execute": false })),
381            )
382            .await
383            .unwrap();
384        client.ping().await.unwrap();
385
386        // 6. Reload
387        let reload_res = client.reload().await.unwrap();
388        assert_eq!(reload_res.count, 7); // 2 desktop apps + 5 system actions
389
390        // 7. JSON-RPC 2.0 spec error codes
391        let parse_err = client.send_raw_line("{not valid json").await.unwrap();
392        assert_eq!(parse_err.id, RpcId::Null);
393        assert_eq!(parse_err.error.unwrap().code, ERR_PARSE_ERROR);
394
395        let bad_ver = client
396            .send_raw_line(r#"{"jsonrpc":"1.0","id":10,"method":"ping"}"#)
397            .await
398            .unwrap();
399        assert_eq!(bad_ver.id, RpcId::Number(10));
400        assert_eq!(bad_ver.error.unwrap().code, ERR_INVALID_REQUEST);
401
402        let unknown_method = client
403            .send_raw_line(r#"{"jsonrpc":"2.0","id":11,"method":"unknown"}"#)
404            .await
405            .unwrap();
406        assert_eq!(unknown_method.id, RpcId::Number(11));
407        assert_eq!(unknown_method.error.unwrap().code, ERR_METHOD_NOT_FOUND);
408
409        let invalid_params = client
410            .send_raw_line(r#"{"jsonrpc":"2.0","id":12,"method":"search"}"#)
411            .await
412            .unwrap();
413        assert_eq!(invalid_params.id, RpcId::Number(12));
414        assert_eq!(invalid_params.error.unwrap().code, ERR_INVALID_PARAMS);
415
416        let missing_entry = client
417            .send_raw_line(
418                r#"{"jsonrpc":"2.0","id":13,"method":"exec","params":{"id":"nope.desktop","execute":false}}"#,
419            )
420            .await
421            .unwrap();
422        assert_eq!(missing_entry.id, RpcId::Number(13));
423        assert_eq!(missing_entry.error.unwrap().code, ERR_EXEC_FAILED);
424
425        server_task.abort();
426        engine.shutdown().await.unwrap();
427    }
428}