fount-daemon 0.2.1

A lightweight application launcher backend for Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::engine_actor::EngineHandle;
use crate::protocol::{
    ExecParams, ExecResultPayload, ReloadResultPayload, RpcError, RpcId, RpcRequest, RpcResponse,
    SearchParams, SearchResultPayload,
};
use serde::Serialize;
use std::env;
use std::io;
use std::path::{Path, PathBuf};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::{UnixListener, UnixStream};
use tracing::{debug, info, warn};

/// Maximum allowed NDJSON line length (1 MiB) to prevent unbounded memory growth.
const MAX_LINE_SIZE: usize = 1024 * 1024;

/// Resolves the default Unix Domain Socket path:
/// `$XDG_RUNTIME_DIR/fount.sock` (fallback `/tmp/fount.sock`).
pub fn default_socket_path() -> PathBuf {
    if let Ok(runtime_dir) = env::var("XDG_RUNTIME_DIR")
        && !runtime_dir.is_empty()
    {
        return PathBuf::from(runtime_dir).join("fount.sock");
    }
    PathBuf::from("/tmp/fount.sock")
}

/// Reads a single newline-delimited JSON line up to `MAX_LINE_SIZE` bytes.
/// Returns `Ok(None)` on clean EOF.
pub async fn read_json_line<R: AsyncBufReadExt + Unpin>(
    reader: &mut R,
) -> io::Result<Option<String>> {
    let mut line = String::new();
    let bytes_read = reader
        .take((MAX_LINE_SIZE + 1) as u64)
        .read_line(&mut line)
        .await?;

    if bytes_read == 0 {
        return Ok(None);
    }

    if bytes_read > MAX_LINE_SIZE {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("Line exceeds maximum allowed size ({MAX_LINE_SIZE} bytes)"),
        ));
    }

    Ok(Some(line))
}

/// Serializes `payload` as compact single-line JSON terminated by `\n` and flushes.
pub async fn write_json_line<W: AsyncWriteExt + Unpin>(
    writer: &mut W,
    payload: &impl Serialize,
) -> io::Result<()> {
    let mut serialized = serde_json::to_string(payload).map_err(io::Error::other)?;
    serialized.push('\n');
    writer.write_all(serialized.as_bytes()).await?;
    writer.flush().await
}

/// Binds a `UnixListener` to `socket_path` (cleaning up any stale socket file first).
pub fn bind_unix_listener(socket_path: &Path) -> io::Result<UnixListener> {
    if let Some(parent) = socket_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    if socket_path.exists() {
        let _ = std::fs::remove_file(socket_path);
    }

    UnixListener::bind(socket_path)
}

/// Runs the Unix Domain Socket IPC server loop using an already-bound `UnixListener`.
pub async fn serve_unix_listener(listener: UnixListener, engine: EngineHandle) -> io::Result<()> {
    loop {
        let (stream, _addr) = listener.accept().await?;
        let engine_clone = engine.clone();

        tokio::spawn(async move {
            if let Err(e) = handle_client_connection(stream, engine_clone).await {
                debug!(error = %e, "Unix socket client connection ended with error");
            }
        });
    }
}

/// Binds and runs the Unix Domain Socket IPC server at `socket_path`.
pub async fn run_unix_socket_server(
    socket_path: PathBuf,
    engine: EngineHandle,
) -> io::Result<()> {
    let listener = bind_unix_listener(&socket_path)?;
    info!(path = %socket_path.display(), "Unix domain socket server listening (JSON-RPC 2.0 NDJSON)");
    serve_unix_listener(listener, engine).await
}

/// Handles a single persistent client connection, processing NDJSON JSON-RPC 2.0 requests.
async fn handle_client_connection(stream: UnixStream, engine: EngineHandle) -> io::Result<()> {
    let (read_half, mut write_half) = stream.into_split();
    let mut reader = BufReader::new(read_half);

    while let Some(line) = read_json_line(&mut reader).await? {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let raw_value: serde_json::Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                warn!(error = %e, "Malformed JSON on Unix socket");
                let resp =
                    RpcResponse::error(RpcId::Null, RpcError::parse_error(e.to_string()));
                write_json_line(&mut write_half, &resp).await?;
                continue;
            }
        };

        let request: RpcRequest = match serde_json::from_value(raw_value) {
            Ok(r) => r,
            Err(e) => {
                warn!(error = %e, "Invalid JSON-RPC request envelope on Unix socket");
                let resp =
                    RpcResponse::error(RpcId::Null, RpcError::invalid_request(e.to_string()));
                write_json_line(&mut write_half, &resp).await?;
                continue;
            }
        };

        match request.into_client_message() {
            Ok(client_msg) => {
                let daemon_msg = engine.dispatch(client_msg).await;
                if let Some(id) = request.id {
                    let resp = RpcResponse::from_daemon_message(id, daemon_msg);
                    write_json_line(&mut write_half, &resp).await?;
                }
            }
            Err(rpc_err) => {
                if let Some(id) = request.id {
                    let resp = RpcResponse::error(id, rpc_err);
                    write_json_line(&mut write_half, &resp).await?;
                } else {
                    debug!(error = %rpc_err.message, "Ignoring invalid JSON-RPC notification");
                }
            }
        }
    }

    Ok(())
}

/// Async JSON-RPC 2.0 NDJSON client for communicating with the daemon over a Unix Domain Socket.
pub struct UnixSocketClient {
    reader: BufReader<OwnedReadHalf>,
    writer: OwnedWriteHalf,
    next_id: i64,
}

impl UnixSocketClient {
    /// Connects to the daemon at `socket_path`.
    pub async fn connect<P: AsRef<Path>>(socket_path: P) -> io::Result<Self> {
        let stream = UnixStream::connect(socket_path).await?;
        let (read_half, write_half) = stream.into_split();
        Ok(Self {
            reader: BufReader::new(read_half),
            writer: write_half,
            next_id: 1,
        })
    }

    /// Sends a JSON-RPC 2.0 request with an auto-incremented numeric `id` and awaits the response.
    pub async fn call(
        &mut self,
        method: impl Into<String>,
        params: Option<serde_json::Value>,
    ) -> io::Result<RpcResponse> {
        let id = self.next_id;
        self.next_id += 1;

        let req = RpcRequest::new(RpcId::Number(id), method, params);
        write_json_line(&mut self.writer, &req).await?;

        let resp_line = read_json_line(&mut self.reader).await?.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Daemon closed connection before sending response",
            )
        })?;

        serde_json::from_str(resp_line.trim()).map_err(io::Error::other)
    }

    /// Sends a JSON-RPC 2.0 notification (no `id`; daemon does not send a reply).
    pub async fn notify(
        &mut self,
        method: impl Into<String>,
        params: Option<serde_json::Value>,
    ) -> io::Result<()> {
        let req = RpcRequest::notification(method, params);
        write_json_line(&mut self.writer, &req).await
    }

    /// Sends a raw NDJSON line and reads back one `RpcResponse` line (handy for testing protocol errors).
    pub async fn send_raw_line(&mut self, raw: &str) -> io::Result<RpcResponse> {
        let mut line = raw.to_string();
        if !line.ends_with('\n') {
            line.push('\n');
        }
        self.writer.write_all(line.as_bytes()).await?;
        self.writer.flush().await?;

        let resp_line = read_json_line(&mut self.reader).await?.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "Daemon closed connection before sending response",
            )
        })?;

        serde_json::from_str(resp_line.trim()).map_err(io::Error::other)
    }

    /// Sends a `"ping"` request and verifies the daemon responds with `"pong"`.
    pub async fn ping(&mut self) -> io::Result<()> {
        let resp = self.call("ping", None).await?;
        let val = unwrap_rpc_result(resp)?;
        if val.as_str() == Some("pong") {
            Ok(())
        } else {
            Err(io::Error::other(format!("Unexpected ping result: {val}")))
        }
    }

    /// Queries the daemon for up to `limit` fuzzy matches.
    pub async fn search(
        &mut self,
        query: impl Into<String>,
        limit: u32,
    ) -> io::Result<SearchResultPayload> {
        let params = serde_json::to_value(SearchParams {
            query: query.into(),
            limit,
        })
        .map_err(io::Error::other)?;
        let resp = self.call("search", Some(params)).await?;
        let val = unwrap_rpc_result(resp)?;
        serde_json::from_value(val).map_err(io::Error::other)
    }

    /// Triggers execution (or frecency-only recording) for an entry ID.
    pub async fn exec(
        &mut self,
        id: impl Into<String>,
        execute: bool,
    ) -> io::Result<ExecResultPayload> {
        let params = serde_json::to_value(ExecParams {
            id: id.into(),
            execute,
        })
        .map_err(io::Error::other)?;
        let resp = self.call("exec", Some(params)).await?;
        let val = unwrap_rpc_result(resp)?;
        serde_json::from_value(val).map_err(io::Error::other)
    }

    /// Triggers an index reload on the daemon and returns the new entry count.
    pub async fn reload(&mut self) -> io::Result<ReloadResultPayload> {
        let resp = self.call("reload", None).await?;
        let val = unwrap_rpc_result(resp)?;
        serde_json::from_value(val).map_err(io::Error::other)
    }
}

fn unwrap_rpc_result(resp: RpcResponse) -> io::Result<serde_json::Value> {
    if let Some(err) = resp.error {
        return Err(io::Error::other(format!(
            "JSON-RPC error {}: {}",
            err.code, err.message
        )));
    }
    resp.result
        .ok_or_else(|| io::Error::other("JSON-RPC response missing both result and error"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::{
        ERR_EXEC_FAILED, ERR_INVALID_PARAMS, ERR_INVALID_REQUEST, ERR_METHOD_NOT_FOUND,
        ERR_PARSE_ERROR,
    };
    use fount_core::{FrecencyStore, IndexCatalog};
    use std::fs;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_unix_socket_jsonrpc_streaming_and_errors() {
        let temp = tempdir().unwrap();
        let apps_dir = temp.path().join("applications");
        let frecency_path = temp.path().join("frecency.bin");
        let sock_path = temp.path().join("fount-test.sock");
        fs::create_dir_all(&apps_dir).unwrap();

        fs::write(
            apps_dir.join("firefox.desktop"),
            r#"
[Desktop Entry]
Type=Application
Name=Firefox Web Browser
Exec=firefox
Icon=firefox
"#,
        )
        .unwrap();

        fs::write(
            apps_dir.join("files.desktop"),
            r#"
[Desktop Entry]
Type=Application
Name=Files
Exec=nautilus
Icon=system-file-manager
"#,
        )
        .unwrap();

        let mut catalog = IndexCatalog::with_dirs(vec![apps_dir]);
        catalog.set_frecency_store(FrecencyStore::open_or_create(frecency_path));
        catalog.set_include_system_actions(true);

        let engine = EngineHandle::spawn_with_catalog(catalog);
        let listener = bind_unix_listener(&sock_path).unwrap();

        let server_engine = engine.clone();
        let server_task = tokio::spawn(async move {
            let _ = serve_unix_listener(listener, server_engine).await;
        });

        // Connect client
        let mut client = UnixSocketClient::connect(&sock_path).await.unwrap();

        // 1. Ping -> Pong
        client.ping().await.unwrap();

        // 2. Simulate rapid keystroke streaming verifying JSON-RPC ID correlation
        for (expected_id, keystroke) in [(2, "f"), (3, "fi"), (4, "fir"), (5, "fire")] {
            let params = serde_json::to_value(SearchParams {
                query: keystroke.into(),
                limit: 5,
            })
            .unwrap();
            let resp = client.call("search", Some(params)).await.unwrap();
            assert_eq!(resp.id, RpcId::Number(expected_id));
            assert!(resp.error.is_none());

            let payload: SearchResultPayload =
                serde_json::from_value(resp.result.unwrap()).unwrap();
            assert_eq!(payload.query, keystroke);
            assert!(!payload.items.is_empty());
        }

        // 3. Exec "files.desktop" (record frecency without spawning process)
        let exec_res = client.exec("files.desktop", false).await.unwrap();
        assert_eq!(exec_res.id, "files.desktop");
        assert!(exec_res.success);

        // 4. Search "fi" -> "files.desktop" should now rank #1 due to frecency
        let search_res = client.search("fi", 5).await.unwrap();
        assert_eq!(search_res.items[0].id, "files.desktop");

        // 5. Notification (omitted id) executes with no reply, followed immediately by ping()
        client
            .notify(
                "exec",
                Some(serde_json::json!({ "id": "files.desktop", "execute": false })),
            )
            .await
            .unwrap();
        client.ping().await.unwrap();

        // 6. Reload
        let reload_res = client.reload().await.unwrap();
        assert_eq!(reload_res.count, 7); // 2 desktop apps + 5 system actions

        // 7. JSON-RPC 2.0 spec error codes
        let parse_err = client.send_raw_line("{not valid json").await.unwrap();
        assert_eq!(parse_err.id, RpcId::Null);
        assert_eq!(parse_err.error.unwrap().code, ERR_PARSE_ERROR);

        let bad_ver = client
            .send_raw_line(r#"{"jsonrpc":"1.0","id":10,"method":"ping"}"#)
            .await
            .unwrap();
        assert_eq!(bad_ver.id, RpcId::Number(10));
        assert_eq!(bad_ver.error.unwrap().code, ERR_INVALID_REQUEST);

        let unknown_method = client
            .send_raw_line(r#"{"jsonrpc":"2.0","id":11,"method":"unknown"}"#)
            .await
            .unwrap();
        assert_eq!(unknown_method.id, RpcId::Number(11));
        assert_eq!(unknown_method.error.unwrap().code, ERR_METHOD_NOT_FOUND);

        let invalid_params = client
            .send_raw_line(r#"{"jsonrpc":"2.0","id":12,"method":"search"}"#)
            .await
            .unwrap();
        assert_eq!(invalid_params.id, RpcId::Number(12));
        assert_eq!(invalid_params.error.unwrap().code, ERR_INVALID_PARAMS);

        let missing_entry = client
            .send_raw_line(
                r#"{"jsonrpc":"2.0","id":13,"method":"exec","params":{"id":"nope.desktop","execute":false}}"#,
            )
            .await
            .unwrap();
        assert_eq!(missing_entry.id, RpcId::Number(13));
        assert_eq!(missing_entry.error.unwrap().code, ERR_EXEC_FAILED);

        server_task.abort();
        engine.shutdown().await.unwrap();
    }
}