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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use fount_core::{LauncherAction, SearchResult};
use serde::{Deserialize, Serialize};

/// JSON-RPC protocol version string required by spec.
pub const JSONRPC_VERSION: &str = "2.0";

/// JSON-RPC 2.0 standard error codes and application-specific execution error code.
pub const ERR_PARSE_ERROR: i32 = -32700;
pub const ERR_INVALID_REQUEST: i32 = -32600;
pub const ERR_METHOD_NOT_FOUND: i32 = -32601;
pub const ERR_INVALID_PARAMS: i32 = -32602;
pub const ERR_INTERNAL_ERROR: i32 = -32603;
pub const ERR_EXEC_FAILED: i32 = -32000;

/// Requests sent from an IPC client (Unix socket or internal bridge) to the daemon.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClientMessage {
    /// Query the fuzzy search engine for up to `limit` results.
    Search { query: String, limit: u32 },
    /// Trigger execution of an entry by its ID and record usage in the frecency store.
    Exec {
        id: String,
        /// If true, the daemon directly executes the entry's action; if false, only records frecency and assumes the client will handle execution.
        execute: bool,
    },
    /// Rescan desktop directories and reload configuration.
    Reload,
    /// Health check ping.
    Ping,
}

/// Responses sent from the daemon back to an IPC client.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DaemonMessage {
    /// Ranked search results matching `query`.
    Results {
        query: String,
        items: Vec<SearchResultWire>,
    },
    /// Outcome of a `Launch` / `Exec` request.
    Launched {
        id: String,
        success: bool,
        error: Option<String>,
    },
    /// Outcome of a `Reload` request with the total number of indexed entries.
    Reloaded { count: u32 },
    /// Health check response.
    Pong,
    /// Error response if a request could not be processed.
    Error { message: String },
}

/// Compact wire representation of a ranked search result for IPC transport.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchResultWire {
    /// Unique identifier of the entry (e.g. `firefox.desktop` or `action:poweroff`).
    pub id: String,
    /// Display title.
    pub name: String,
    /// Secondary subtitle / generic name / comment.
    pub description: Option<String>,
    /// Icon name or file path.
    pub icon: Option<String>,
    /// Executable command or action summary string.
    pub exec: String,
    /// Whether this entry is a custom action rather than a standard application.
    pub is_custom_action: bool,
    /// Blended fuzzy + frecency score.
    pub score: u32,
    /// Matched character indices for UI highlighting.
    pub matched_indices: Vec<u32>,
}

impl From<SearchResult> for SearchResultWire {
    fn from(res: SearchResult) -> Self {
        let exec = match &res.entry.action {
            LauncherAction::Exec { command, .. } => command.clone(),
            LauncherAction::Command { program, args, .. } => {
                if args.is_empty() {
                    program.clone()
                } else {
                    format!("{} {}", program, args.join(" "))
                }
            }
            LauncherAction::Shell(script) => script.clone(),
            LauncherAction::Custom(custom_id) => custom_id.clone(),
        };

        let is_custom_action = res.entry.is_custom_action();

        Self {
            id: res.entry.id,
            name: res.entry.name,
            description: res.entry.description,
            icon: res.entry.icon,
            exec,
            is_custom_action,
            score: res.score,
            matched_indices: res.matched_indices,
        }
    }
}

/// JSON-RPC 2.0 request/response correlation identifier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RpcId {
    Number(i64),
    String(String),
    Null,
}

/// Preserves the distinction between an omitted `"id"` field (`None`, notification)
/// and an explicit `"id": null` (`Some(RpcId::Null)`, request expecting `"id": null`).
fn deserialize_some<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
    T: Deserialize<'de>,
    D: serde::Deserializer<'de>,
{
    Deserialize::deserialize(deserializer).map(Some)
}

/// JSON-RPC 2.0 request or notification envelope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RpcRequest {
    pub jsonrpc: String,
    #[serde(
        default,
        deserialize_with = "deserialize_some",
        skip_serializing_if = "Option::is_none"
    )]
    pub id: Option<RpcId>,
    pub method: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

impl RpcRequest {
    /// Creates a JSON-RPC 2.0 request expecting a response with matching `id`.
    pub fn new(id: RpcId, method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.into(),
            id: Some(id),
            method: method.into(),
            params,
        }
    }

    /// Creates a JSON-RPC 2.0 notification (no `id`, no response expected).
    pub fn notification(method: impl Into<String>, params: Option<serde_json::Value>) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.into(),
            id: None,
            method: method.into(),
            params,
        }
    }

    /// Validates this JSON-RPC 2.0 request and translates it into a `ClientMessage`.
    pub fn into_client_message(&self) -> Result<ClientMessage, RpcError> {
        if self.jsonrpc != JSONRPC_VERSION {
            return Err(RpcError::invalid_request(format!(
                "Unsupported jsonrpc version '{}'; expected '{}'",
                self.jsonrpc, JSONRPC_VERSION
            )));
        }

        match self.method.as_str() {
            "search" => {
                let raw_params = self
                    .params
                    .as_ref()
                    .ok_or_else(|| RpcError::invalid_params("Missing 'params' for 'search'"))?;
                let params: SearchParams = serde_json::from_value(raw_params.clone())
                    .map_err(|e| RpcError::invalid_params(format!("Invalid search params: {e}")))?;
                Ok(ClientMessage::Search {
                    query: params.query,
                    limit: params.limit,
                })
            }
            "exec" => {
                let raw_params = self
                    .params
                    .as_ref()
                    .ok_or_else(|| RpcError::invalid_params("Missing 'params' for 'exec'"))?;
                let params: ExecParams = serde_json::from_value(raw_params.clone())
                    .map_err(|e| RpcError::invalid_params(format!("Invalid exec params: {e}")))?;
                Ok(ClientMessage::Exec {
                    id: params.id,
                    execute: params.execute,
                })
            }
            "reload" => {
                validate_empty_params(self.params.as_ref(), "reload")?;
                Ok(ClientMessage::Reload)
            }
            "ping" => {
                validate_empty_params(self.params.as_ref(), "ping")?;
                Ok(ClientMessage::Ping)
            }
            other => Err(RpcError::method_not_found(format!(
                "Method not found: '{other}'"
            ))),
        }
    }
}

fn validate_empty_params(
    params: Option<&serde_json::Value>,
    method: &str,
) -> Result<(), RpcError> {
    match params {
        None | Some(serde_json::Value::Null) => Ok(()),
        Some(serde_json::Value::Object(map)) if map.is_empty() => Ok(()),
        Some(_) => Err(RpcError::invalid_params(format!(
            "Method '{method}' does not accept parameters"
        ))),
    }
}

/// JSON-RPC 2.0 error object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RpcError {
    pub code: i32,
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

impl RpcError {
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            data: None,
        }
    }

    pub fn parse_error(message: impl Into<String>) -> Self {
        Self::new(ERR_PARSE_ERROR, message)
    }

    pub fn invalid_request(message: impl Into<String>) -> Self {
        Self::new(ERR_INVALID_REQUEST, message)
    }

    pub fn method_not_found(message: impl Into<String>) -> Self {
        Self::new(ERR_METHOD_NOT_FOUND, message)
    }

    pub fn invalid_params(message: impl Into<String>) -> Self {
        Self::new(ERR_INVALID_PARAMS, message)
    }

    pub fn internal_error(message: impl Into<String>) -> Self {
        Self::new(ERR_INTERNAL_ERROR, message)
    }

    pub fn exec_failed(message: impl Into<String>) -> Self {
        Self::new(ERR_EXEC_FAILED, message)
    }
}

/// JSON-RPC 2.0 response envelope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RpcResponse {
    pub jsonrpc: String,
    pub id: RpcId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<RpcError>,
}

impl RpcResponse {
    /// Constructs a successful JSON-RPC 2.0 response.
    pub fn success(id: RpcId, result: serde_json::Value) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.into(),
            id,
            result: Some(result),
            error: None,
        }
    }

    /// Constructs a JSON-RPC 2.0 error response.
    pub fn error(id: RpcId, error: RpcError) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.into(),
            id,
            result: None,
            error: Some(error),
        }
    }

    /// Converts an internal `DaemonMessage` into a JSON-RPC 2.0 response envelope.
    pub fn from_daemon_message(id: RpcId, msg: DaemonMessage) -> Self {
        match msg {
            DaemonMessage::Results { query, items } => {
                let payload = SearchResultPayload { query, items };
                Self::success(
                    id,
                    serde_json::to_value(payload).expect("SearchResultPayload is serializable"),
                )
            }
            DaemonMessage::Launched {
                id: entry_id,
                success: true,
                ..
            } => {
                let payload = ExecResultPayload {
                    id: entry_id,
                    success: true,
                };
                Self::success(
                    id,
                    serde_json::to_value(payload).expect("ExecResultPayload is serializable"),
                )
            }
            DaemonMessage::Launched {
                success: false,
                error,
                ..
            } => Self::error(
                id,
                RpcError::exec_failed(error.unwrap_or_else(|| "Execution failed".into())),
            ),
            DaemonMessage::Reloaded { count } => {
                let payload = ReloadResultPayload { count };
                Self::success(
                    id,
                    serde_json::to_value(payload).expect("ReloadResultPayload is serializable"),
                )
            }
            DaemonMessage::Pong => Self::success(id, serde_json::Value::String("pong".into())),
            DaemonMessage::Error { message } => {
                Self::error(id, RpcError::internal_error(message))
            }
        }
    }
}

fn default_search_limit() -> u32 {
    10
}

fn default_execute_true() -> bool {
    true
}

/// Parameters for the `"search"` JSON-RPC method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchParams {
    pub query: String,
    #[serde(default = "default_search_limit")]
    pub limit: u32,
}

/// Result payload returned by the `"search"` JSON-RPC method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchResultPayload {
    pub query: String,
    pub items: Vec<SearchResultWire>,
}

/// Parameters for the `"exec"` JSON-RPC method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecParams {
    pub id: String,
    #[serde(default = "default_execute_true")]
    pub execute: bool,
}

/// Result payload returned by the `"exec"` JSON-RPC method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecResultPayload {
    pub id: String,
    pub success: bool,
}

/// Result payload returned by the `"reload"` JSON-RPC method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReloadResultPayload {
    pub count: u32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use fount_core::LauncherEntry;

    #[test]
    fn test_jsonrpc_request_parsing_and_defaults() {
        // search with default limit
        let req: RpcRequest = serde_json::from_str(
            r#"{"jsonrpc":"2.0","id":1,"method":"search","params":{"query":"fire"}}"#,
        )
        .unwrap();
        assert_eq!(req.id, Some(RpcId::Number(1)));
        assert_eq!(
            req.into_client_message().unwrap(),
            ClientMessage::Search {
                query: "fire".into(),
                limit: 10,
            }
        );

        // exec with default execute=true
        let req: RpcRequest = serde_json::from_str(
            r#"{"jsonrpc":"2.0","id":"req-2","method":"exec","params":{"id":"firefox.desktop"}}"#,
        )
        .unwrap();
        assert_eq!(req.id, Some(RpcId::String("req-2".into())));
        assert_eq!(
            req.into_client_message().unwrap(),
            ClientMessage::Exec {
                id: "firefox.desktop".into(),
                execute: true,
            }
        );

        // reload with empty object params and ping with omitted params
        let reload_req: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","id":3,"method":"reload","params":{}}"#)
                .unwrap();
        assert_eq!(reload_req.into_client_message().unwrap(), ClientMessage::Reload);

        let ping_req: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","id":4,"method":"ping"}"#).unwrap();
        assert_eq!(ping_req.into_client_message().unwrap(), ClientMessage::Ping);
    }

    #[test]
    fn test_jsonrpc_id_notification_vs_null() {
        // Omitted id -> None (notification)
        let notif: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","method":"ping"}"#).unwrap();
        assert_eq!(notif.id, None);

        // Explicit "id": null -> Some(RpcId::Null) (request expecting response)
        let null_id: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#).unwrap();
        assert_eq!(null_id.id, Some(RpcId::Null));
    }

    #[test]
    fn test_jsonrpc_error_codes() {
        // Wrong jsonrpc version -> -32600
        let bad_ver: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#).unwrap();
        assert_eq!(
            bad_ver.into_client_message().unwrap_err().code,
            ERR_INVALID_REQUEST
        );

        // Unknown method -> -32601
        let unknown: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"method":"does_not_exist"}"#).unwrap();
        assert_eq!(
            unknown.into_client_message().unwrap_err().code,
            ERR_METHOD_NOT_FOUND
        );

        // Invalid params (missing params for search) -> -32602
        let missing_params: RpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"method":"search"}"#).unwrap();
        assert_eq!(
            missing_params.into_client_message().unwrap_err().code,
            ERR_INVALID_PARAMS
        );

        // Invalid params (wrong type for limit) -> -32602
        let wrong_type: RpcRequest = serde_json::from_str(
            r#"{"jsonrpc":"2.0","id":1,"method":"search","params":{"query":"a","limit":"many"}}"#,
        )
        .unwrap();
        assert_eq!(
            wrong_type.into_client_message().unwrap_err().code,
            ERR_INVALID_PARAMS
        );

        // Exec failure in DaemonMessage -> -32000
        let failed_exec = RpcResponse::from_daemon_message(
            RpcId::Number(7),
            DaemonMessage::Launched {
                id: "missing.desktop".into(),
                success: false,
                error: Some("Entry not found".into()),
            },
        );
        assert_eq!(failed_exec.id, RpcId::Number(7));
        assert_eq!(failed_exec.error.unwrap().code, ERR_EXEC_FAILED);
    }

    #[test]
    fn test_jsonrpc_response_from_daemon_message() {
        let pong = RpcResponse::from_daemon_message(RpcId::Number(1), DaemonMessage::Pong);
        assert_eq!(pong.jsonrpc, "2.0");
        assert_eq!(pong.result, Some(serde_json::Value::String("pong".into())));
        assert!(pong.error.is_none());

        let reloaded =
            RpcResponse::from_daemon_message(RpcId::Number(2), DaemonMessage::Reloaded { count: 42 });
        let payload: ReloadResultPayload = serde_json::from_value(reloaded.result.unwrap()).unwrap();
        assert_eq!(payload.count, 42);
    }

    #[test]
    fn test_search_result_wire_conversion() {
        let entry = LauncherEntry::custom_action(
            "action:poweroff",
            "Power Off",
            Some("system-shutdown".into()),
            Some("Shut down the system".into()),
            vec!["shutdown".into()],
            LauncherAction::Command {
                program: "systemctl".into(),
                args: vec!["poweroff".into()],
                terminal: false,
            },
        );
        let res = SearchResult {
            entry,
            score: 140,
            matched_indices: vec![0, 1, 2],
        };

        let wire = SearchResultWire::from(res);
        assert_eq!(wire.id, "action:poweroff");
        assert_eq!(wire.name, "Power Off");
        assert_eq!(wire.exec, "systemctl poweroff");
        assert!(wire.is_custom_action);
        assert_eq!(wire.score, 140);
        assert_eq!(wire.matched_indices, vec![0, 1, 2]);
    }
}