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};
const MAX_LINE_SIZE: usize = 1024 * 1024;
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")
}
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))
}
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
}
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)
}
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");
}
});
}
}
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
}
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(())
}
pub struct UnixSocketClient {
reader: BufReader<OwnedReadHalf>,
writer: OwnedWriteHalf,
next_id: i64,
}
impl UnixSocketClient {
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,
})
}
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)
}
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
}
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)
}
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}")))
}
}
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)
}
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)
}
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;
});
let mut client = UnixSocketClient::connect(&sock_path).await.unwrap();
client.ping().await.unwrap();
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());
}
let exec_res = client.exec("files.desktop", false).await.unwrap();
assert_eq!(exec_res.id, "files.desktop");
assert!(exec_res.success);
let search_res = client.search("fi", 5).await.unwrap();
assert_eq!(search_res.items[0].id, "files.desktop");
client
.notify(
"exec",
Some(serde_json::json!({ "id": "files.desktop", "execute": false })),
)
.await
.unwrap();
client.ping().await.unwrap();
let reload_res = client.reload().await.unwrap();
assert_eq!(reload_res.count, 7);
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();
}
}