Skip to main content

fount_daemon/
protocol.rs

1use fount_core::{LauncherAction, SearchResult};
2use serde::{Deserialize, Serialize};
3
4/// JSON-RPC protocol version string required by spec.
5pub const JSONRPC_VERSION: &str = "2.0";
6
7/// JSON-RPC 2.0 standard error codes and application-specific execution error code.
8pub const ERR_PARSE_ERROR: i32 = -32700;
9pub const ERR_INVALID_REQUEST: i32 = -32600;
10pub const ERR_METHOD_NOT_FOUND: i32 = -32601;
11pub const ERR_INVALID_PARAMS: i32 = -32602;
12pub const ERR_INTERNAL_ERROR: i32 = -32603;
13pub const ERR_EXEC_FAILED: i32 = -32000;
14
15/// Requests sent from an IPC client (Unix socket or internal bridge) to the daemon.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub enum ClientMessage {
18    /// Query the fuzzy search engine for up to `limit` results.
19    Search { query: String, limit: u32 },
20    /// Trigger execution of an entry by its ID and record usage in the frecency store.
21    Exec {
22        id: String,
23        /// If true, the daemon directly executes the entry's action; if false, only records frecency and assumes the client will handle execution.
24        execute: bool,
25    },
26    /// Rescan desktop directories and reload configuration.
27    Reload,
28    /// Health check ping.
29    Ping,
30}
31
32/// Responses sent from the daemon back to an IPC client.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub enum DaemonMessage {
35    /// Ranked search results matching `query`.
36    Results {
37        query: String,
38        items: Vec<SearchResultWire>,
39    },
40    /// Outcome of a `Launch` / `Exec` request.
41    Launched {
42        id: String,
43        success: bool,
44        error: Option<String>,
45    },
46    /// Outcome of a `Reload` request with the total number of indexed entries.
47    Reloaded { count: u32 },
48    /// Health check response.
49    Pong,
50    /// Error response if a request could not be processed.
51    Error { message: String },
52}
53
54/// Compact wire representation of a ranked search result for IPC transport.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct SearchResultWire {
57    /// Unique identifier of the entry (e.g. `firefox.desktop` or `action:poweroff`).
58    pub id: String,
59    /// Display title.
60    pub name: String,
61    /// Secondary subtitle / generic name / comment.
62    pub description: Option<String>,
63    /// Icon name or file path.
64    pub icon: Option<String>,
65    /// Executable command or action summary string.
66    pub exec: String,
67    /// Whether this entry is a custom action rather than a standard application.
68    pub is_custom_action: bool,
69    /// Blended fuzzy + frecency score.
70    pub score: u32,
71    /// Matched character indices for UI highlighting.
72    pub matched_indices: Vec<u32>,
73}
74
75impl From<SearchResult> for SearchResultWire {
76    fn from(res: SearchResult) -> Self {
77        let exec = match &res.entry.action {
78            LauncherAction::Exec { command, .. } => command.clone(),
79            LauncherAction::Command { program, args, .. } => {
80                if args.is_empty() {
81                    program.clone()
82                } else {
83                    format!("{} {}", program, args.join(" "))
84                }
85            }
86            LauncherAction::Shell(script) => script.clone(),
87            LauncherAction::Custom(custom_id) => custom_id.clone(),
88        };
89
90        let is_custom_action = res.entry.is_custom_action();
91
92        Self {
93            id: res.entry.id,
94            name: res.entry.name,
95            description: res.entry.description,
96            icon: res.entry.icon,
97            exec,
98            is_custom_action,
99            score: res.score,
100            matched_indices: res.matched_indices,
101        }
102    }
103}
104
105/// JSON-RPC 2.0 request/response correlation identifier.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(untagged)]
108pub enum RpcId {
109    Number(i64),
110    String(String),
111    Null,
112}
113
114/// Preserves the distinction between an omitted `"id"` field (`None`, notification)
115/// and an explicit `"id": null` (`Some(RpcId::Null)`, request expecting `"id": null`).
116fn deserialize_some<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
117where
118    T: Deserialize<'de>,
119    D: serde::Deserializer<'de>,
120{
121    Deserialize::deserialize(deserializer).map(Some)
122}
123
124/// JSON-RPC 2.0 request or notification envelope.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct RpcRequest {
127    pub jsonrpc: String,
128    #[serde(
129        default,
130        deserialize_with = "deserialize_some",
131        skip_serializing_if = "Option::is_none"
132    )]
133    pub id: Option<RpcId>,
134    pub method: String,
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub params: Option<serde_json::Value>,
137}
138
139impl RpcRequest {
140    /// Creates a JSON-RPC 2.0 request expecting a response with matching `id`.
141    pub fn new(id: RpcId, method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
142        Self {
143            jsonrpc: JSONRPC_VERSION.into(),
144            id: Some(id),
145            method: method.into(),
146            params,
147        }
148    }
149
150    /// Creates a JSON-RPC 2.0 notification (no `id`, no response expected).
151    pub fn notification(method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
152        Self {
153            jsonrpc: JSONRPC_VERSION.into(),
154            id: None,
155            method: method.into(),
156            params,
157        }
158    }
159
160    /// Validates this JSON-RPC 2.0 request and translates it into a `ClientMessage`.
161    pub fn into_client_message(&self) -> Result<ClientMessage, RpcError> {
162        if self.jsonrpc != JSONRPC_VERSION {
163            return Err(RpcError::invalid_request(format!(
164                "Unsupported jsonrpc version '{}'; expected '{}'",
165                self.jsonrpc, JSONRPC_VERSION
166            )));
167        }
168
169        match self.method.as_str() {
170            "search" => {
171                let raw_params = self
172                    .params
173                    .as_ref()
174                    .ok_or_else(|| RpcError::invalid_params("Missing 'params' for 'search'"))?;
175                let params: SearchParams = serde_json::from_value(raw_params.clone())
176                    .map_err(|e| RpcError::invalid_params(format!("Invalid search params: {e}")))?;
177                Ok(ClientMessage::Search {
178                    query: params.query,
179                    limit: params.limit,
180                })
181            }
182            "exec" => {
183                let raw_params = self
184                    .params
185                    .as_ref()
186                    .ok_or_else(|| RpcError::invalid_params("Missing 'params' for 'exec'"))?;
187                let params: ExecParams = serde_json::from_value(raw_params.clone())
188                    .map_err(|e| RpcError::invalid_params(format!("Invalid exec params: {e}")))?;
189                Ok(ClientMessage::Exec {
190                    id: params.id,
191                    execute: params.execute,
192                })
193            }
194            "reload" => {
195                validate_empty_params(self.params.as_ref(), "reload")?;
196                Ok(ClientMessage::Reload)
197            }
198            "ping" => {
199                validate_empty_params(self.params.as_ref(), "ping")?;
200                Ok(ClientMessage::Ping)
201            }
202            other => Err(RpcError::method_not_found(format!(
203                "Method not found: '{other}'"
204            ))),
205        }
206    }
207}
208
209fn validate_empty_params(
210    params: Option<&serde_json::Value>,
211    method: &str,
212) -> Result<(), RpcError> {
213    match params {
214        None | Some(serde_json::Value::Null) => Ok(()),
215        Some(serde_json::Value::Object(map)) if map.is_empty() => Ok(()),
216        Some(_) => Err(RpcError::invalid_params(format!(
217            "Method '{method}' does not accept parameters"
218        ))),
219    }
220}
221
222/// JSON-RPC 2.0 error object.
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct RpcError {
225    pub code: i32,
226    pub message: String,
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub data: Option<serde_json::Value>,
229}
230
231impl RpcError {
232    pub fn new(code: i32, message: impl Into<String>) -> Self {
233        Self {
234            code,
235            message: message.into(),
236            data: None,
237        }
238    }
239
240    pub fn parse_error(message: impl Into<String>) -> Self {
241        Self::new(ERR_PARSE_ERROR, message)
242    }
243
244    pub fn invalid_request(message: impl Into<String>) -> Self {
245        Self::new(ERR_INVALID_REQUEST, message)
246    }
247
248    pub fn method_not_found(message: impl Into<String>) -> Self {
249        Self::new(ERR_METHOD_NOT_FOUND, message)
250    }
251
252    pub fn invalid_params(message: impl Into<String>) -> Self {
253        Self::new(ERR_INVALID_PARAMS, message)
254    }
255
256    pub fn internal_error(message: impl Into<String>) -> Self {
257        Self::new(ERR_INTERNAL_ERROR, message)
258    }
259
260    pub fn exec_failed(message: impl Into<String>) -> Self {
261        Self::new(ERR_EXEC_FAILED, message)
262    }
263}
264
265/// JSON-RPC 2.0 response envelope.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct RpcResponse {
268    pub jsonrpc: String,
269    pub id: RpcId,
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub result: Option<serde_json::Value>,
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub error: Option<RpcError>,
274}
275
276impl RpcResponse {
277    /// Constructs a successful JSON-RPC 2.0 response.
278    pub fn success(id: RpcId, result: serde_json::Value) -> Self {
279        Self {
280            jsonrpc: JSONRPC_VERSION.into(),
281            id,
282            result: Some(result),
283            error: None,
284        }
285    }
286
287    /// Constructs a JSON-RPC 2.0 error response.
288    pub fn error(id: RpcId, error: RpcError) -> Self {
289        Self {
290            jsonrpc: JSONRPC_VERSION.into(),
291            id,
292            result: None,
293            error: Some(error),
294        }
295    }
296
297    /// Converts an internal `DaemonMessage` into a JSON-RPC 2.0 response envelope.
298    pub fn from_daemon_message(id: RpcId, msg: DaemonMessage) -> Self {
299        match msg {
300            DaemonMessage::Results { query, items } => {
301                let payload = SearchResultPayload { query, items };
302                Self::success(
303                    id,
304                    serde_json::to_value(payload).expect("SearchResultPayload is serializable"),
305                )
306            }
307            DaemonMessage::Launched {
308                id: entry_id,
309                success: true,
310                ..
311            } => {
312                let payload = ExecResultPayload {
313                    id: entry_id,
314                    success: true,
315                };
316                Self::success(
317                    id,
318                    serde_json::to_value(payload).expect("ExecResultPayload is serializable"),
319                )
320            }
321            DaemonMessage::Launched {
322                success: false,
323                error,
324                ..
325            } => Self::error(
326                id,
327                RpcError::exec_failed(error.unwrap_or_else(|| "Execution failed".into())),
328            ),
329            DaemonMessage::Reloaded { count } => {
330                let payload = ReloadResultPayload { count };
331                Self::success(
332                    id,
333                    serde_json::to_value(payload).expect("ReloadResultPayload is serializable"),
334                )
335            }
336            DaemonMessage::Pong => Self::success(id, serde_json::Value::String("pong".into())),
337            DaemonMessage::Error { message } => {
338                Self::error(id, RpcError::internal_error(message))
339            }
340        }
341    }
342}
343
344fn default_search_limit() -> u32 {
345    10
346}
347
348fn default_execute_true() -> bool {
349    true
350}
351
352/// Parameters for the `"search"` JSON-RPC method.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354pub struct SearchParams {
355    pub query: String,
356    #[serde(default = "default_search_limit")]
357    pub limit: u32,
358}
359
360/// Result payload returned by the `"search"` JSON-RPC method.
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct SearchResultPayload {
363    pub query: String,
364    pub items: Vec<SearchResultWire>,
365}
366
367/// Parameters for the `"exec"` JSON-RPC method.
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369pub struct ExecParams {
370    pub id: String,
371    #[serde(default = "default_execute_true")]
372    pub execute: bool,
373}
374
375/// Result payload returned by the `"exec"` JSON-RPC method.
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
377pub struct ExecResultPayload {
378    pub id: String,
379    pub success: bool,
380}
381
382/// Result payload returned by the `"reload"` JSON-RPC method.
383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
384pub struct ReloadResultPayload {
385    pub count: u32,
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use fount_core::LauncherEntry;
392
393    #[test]
394    fn test_jsonrpc_request_parsing_and_defaults() {
395        // search with default limit
396        let req: RpcRequest = serde_json::from_str(
397            r#"{"jsonrpc":"2.0","id":1,"method":"search","params":{"query":"fire"}}"#,
398        )
399        .unwrap();
400        assert_eq!(req.id, Some(RpcId::Number(1)));
401        assert_eq!(
402            req.into_client_message().unwrap(),
403            ClientMessage::Search {
404                query: "fire".into(),
405                limit: 10,
406            }
407        );
408
409        // exec with default execute=true
410        let req: RpcRequest = serde_json::from_str(
411            r#"{"jsonrpc":"2.0","id":"req-2","method":"exec","params":{"id":"firefox.desktop"}}"#,
412        )
413        .unwrap();
414        assert_eq!(req.id, Some(RpcId::String("req-2".into())));
415        assert_eq!(
416            req.into_client_message().unwrap(),
417            ClientMessage::Exec {
418                id: "firefox.desktop".into(),
419                execute: true,
420            }
421        );
422
423        // reload with empty object params and ping with omitted params
424        let reload_req: RpcRequest =
425            serde_json::from_str(r#"{"jsonrpc":"2.0","id":3,"method":"reload","params":{}}"#)
426                .unwrap();
427        assert_eq!(reload_req.into_client_message().unwrap(), ClientMessage::Reload);
428
429        let ping_req: RpcRequest =
430            serde_json::from_str(r#"{"jsonrpc":"2.0","id":4,"method":"ping"}"#).unwrap();
431        assert_eq!(ping_req.into_client_message().unwrap(), ClientMessage::Ping);
432    }
433
434    #[test]
435    fn test_jsonrpc_id_notification_vs_null() {
436        // Omitted id -> None (notification)
437        let notif: RpcRequest =
438            serde_json::from_str(r#"{"jsonrpc":"2.0","method":"ping"}"#).unwrap();
439        assert_eq!(notif.id, None);
440
441        // Explicit "id": null -> Some(RpcId::Null) (request expecting response)
442        let null_id: RpcRequest =
443            serde_json::from_str(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#).unwrap();
444        assert_eq!(null_id.id, Some(RpcId::Null));
445    }
446
447    #[test]
448    fn test_jsonrpc_error_codes() {
449        // Wrong jsonrpc version -> -32600
450        let bad_ver: RpcRequest =
451            serde_json::from_str(r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#).unwrap();
452        assert_eq!(
453            bad_ver.into_client_message().unwrap_err().code,
454            ERR_INVALID_REQUEST
455        );
456
457        // Unknown method -> -32601
458        let unknown: RpcRequest =
459            serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"method":"does_not_exist"}"#).unwrap();
460        assert_eq!(
461            unknown.into_client_message().unwrap_err().code,
462            ERR_METHOD_NOT_FOUND
463        );
464
465        // Invalid params (missing params for search) -> -32602
466        let missing_params: RpcRequest =
467            serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"method":"search"}"#).unwrap();
468        assert_eq!(
469            missing_params.into_client_message().unwrap_err().code,
470            ERR_INVALID_PARAMS
471        );
472
473        // Invalid params (wrong type for limit) -> -32602
474        let wrong_type: RpcRequest = serde_json::from_str(
475            r#"{"jsonrpc":"2.0","id":1,"method":"search","params":{"query":"a","limit":"many"}}"#,
476        )
477        .unwrap();
478        assert_eq!(
479            wrong_type.into_client_message().unwrap_err().code,
480            ERR_INVALID_PARAMS
481        );
482
483        // Exec failure in DaemonMessage -> -32000
484        let failed_exec = RpcResponse::from_daemon_message(
485            RpcId::Number(7),
486            DaemonMessage::Launched {
487                id: "missing.desktop".into(),
488                success: false,
489                error: Some("Entry not found".into()),
490            },
491        );
492        assert_eq!(failed_exec.id, RpcId::Number(7));
493        assert_eq!(failed_exec.error.unwrap().code, ERR_EXEC_FAILED);
494    }
495
496    #[test]
497    fn test_jsonrpc_response_from_daemon_message() {
498        let pong = RpcResponse::from_daemon_message(RpcId::Number(1), DaemonMessage::Pong);
499        assert_eq!(pong.jsonrpc, "2.0");
500        assert_eq!(pong.result, Some(serde_json::Value::String("pong".into())));
501        assert!(pong.error.is_none());
502
503        let reloaded =
504            RpcResponse::from_daemon_message(RpcId::Number(2), DaemonMessage::Reloaded { count: 42 });
505        let payload: ReloadResultPayload = serde_json::from_value(reloaded.result.unwrap()).unwrap();
506        assert_eq!(payload.count, 42);
507    }
508
509    #[test]
510    fn test_search_result_wire_conversion() {
511        let entry = LauncherEntry::custom_action(
512            "action:poweroff",
513            "Power Off",
514            Some("system-shutdown".into()),
515            Some("Shut down the system".into()),
516            vec!["shutdown".into()],
517            LauncherAction::Command {
518                program: "systemctl".into(),
519                args: vec!["poweroff".into()],
520                terminal: false,
521            },
522        );
523        let res = SearchResult {
524            entry,
525            score: 140,
526            matched_indices: vec![0, 1, 2],
527        };
528
529        let wire = SearchResultWire::from(res);
530        assert_eq!(wire.id, "action:poweroff");
531        assert_eq!(wire.name, "Power Off");
532        assert_eq!(wire.exec, "systemctl poweroff");
533        assert!(wire.is_custom_action);
534        assert_eq!(wire.score, 140);
535        assert_eq!(wire.matched_indices, vec![0, 1, 2]);
536    }
537}