Skip to main content

paper/daemon/
ipc.rs

1//! IPC server for the paperscope daemon.
2//!
3//! JSON lines over a Unix socket (Linux/macOS). Each line is a JSON-encoded
4//! [`DaemonRequest`] or [`DaemonResponse`].
5
6use crate::core::index::IndexStats;
7#[cfg(unix)]
8use anyhow::Context;
9use anyhow::Result;
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14#[cfg(unix)]
15use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
16
17/// Requests sent from clients to the daemon.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19#[serde(tag = "type", rename_all = "snake_case")]
20pub enum DaemonRequest {
21    /// Index the given roots (empty = all configured roots).
22    IndexRoots { roots: Vec<PathBuf> },
23    /// Add a new root to watch and index.
24    AddRoot { path: PathBuf },
25    /// Remove a root from watching and indexing.
26    RemoveRoot { path: PathBuf },
27    /// Get current daemon status.
28    GetStatus,
29    /// Pause indexing (respects resource guard).
30    Pause,
31    /// Resume indexing.
32    Resume,
33    /// Shutdown the daemon gracefully.
34    Shutdown,
35}
36
37/// Responses sent from the daemon to clients.
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(tag = "type", rename_all = "snake_case")]
40pub enum DaemonResponse {
41    /// Indexing completed with statistics.
42    IndexRoots { stats: IndexStats },
43    /// Current daemon status.
44    Status {
45        indexed_files: usize,
46        queued: usize,
47        paused: bool,
48        model: Option<String>,
49    },
50    /// Generic success.
51    Ok,
52    /// Error with message.
53    Error { msg: String },
54}
55
56/// Trait for handling daemon requests. Implement this to provide custom behavior.
57#[async_trait]
58pub trait DaemonHandler: Send + Sync {
59    /// Handle a daemon request and return a response.
60    async fn handle(&self, request: DaemonRequest) -> DaemonResponse;
61}
62
63/// Run the IPC server on the given socket path.
64///
65/// Binds to the Unix socket and serves requests until the task is aborted.
66/// Each connection is handled in its own task with a shared handler.
67#[cfg(unix)]
68pub async fn run_ipc_server(socket_path: &Path, handler: Arc<dyn DaemonHandler>) -> Result<()> {
69    use tokio::net::UnixListener;
70
71    // Remove any stale socket file
72    let _ = tokio::fs::remove_file(socket_path).await;
73    if let Some(parent) = socket_path.parent() {
74        tokio::fs::create_dir_all(parent).await?;
75    }
76
77    let listener = UnixListener::bind(socket_path)
78        .with_context(|| format!("binding to {}", socket_path.display()))?;
79
80    tracing::info!("Daemon IPC server listening on {}", socket_path.display());
81
82    loop {
83        let (stream, _) = listener.accept().await?;
84        let handler = handler.clone();
85        tokio::spawn(async move {
86            if let Err(e) = handle_connection(stream, handler).await {
87                tracing::warn!("IPC connection error: {e}");
88            }
89        });
90    }
91}
92
93/// Windows named-pipe support is not implemented yet.
94#[cfg(windows)]
95pub async fn run_ipc_server(_socket_path: &Path, _handler: Arc<dyn DaemonHandler>) -> Result<()> {
96    anyhow::bail!("daemon IPC is not yet supported on Windows")
97}
98
99#[cfg(unix)]
100async fn handle_connection(
101    stream: tokio::net::UnixStream,
102    handler: Arc<dyn DaemonHandler>,
103) -> Result<()> {
104    let (reader, mut writer) = stream.into_split();
105    let mut reader = BufReader::new(reader);
106    let mut line = String::new();
107
108    loop {
109        line.clear();
110        let bytes_read = reader.read_line(&mut line).await?;
111        if bytes_read == 0 {
112            break; // Client disconnected
113        }
114
115        let request: DaemonRequest = match serde_json::from_str(line.trim()) {
116            Ok(req) => req,
117            Err(e) => {
118                let response = DaemonResponse::Error {
119                    msg: format!("Invalid request: {e}"),
120                };
121                let json = serde_json::to_string(&response)?;
122                writer.write_all(json.as_bytes()).await?;
123                writer.write_all(b"\n").await?;
124                writer.flush().await?;
125                continue;
126            }
127        };
128
129        let response = handler.handle(request).await;
130
131        let json = serde_json::to_string(&response)?;
132        writer.write_all(json.as_bytes()).await?;
133        writer.write_all(b"\n").await?;
134        writer.flush().await?;
135    }
136
137    Ok(())
138}
139
140/// Client for connecting to the daemon IPC server.
141pub struct IpcClient {
142    #[cfg(unix)]
143    reader: BufReader<tokio::net::unix::OwnedReadHalf>,
144    #[cfg(unix)]
145    writer: tokio::net::unix::OwnedWriteHalf,
146}
147
148impl IpcClient {
149    /// Connect to the daemon IPC server.
150    #[cfg(unix)]
151    pub async fn connect(socket_path: &Path) -> Result<Self> {
152        let stream = tokio::net::UnixStream::connect(socket_path)
153            .await
154            .with_context(|| format!("connecting to {}", socket_path.display()))?;
155        let (reader, writer) = stream.into_split();
156        Ok(Self {
157            reader: BufReader::new(reader),
158            writer,
159        })
160    }
161
162    /// Windows named-pipe support is not implemented yet.
163    #[cfg(windows)]
164    pub async fn connect(_socket_path: &Path) -> Result<Self> {
165        anyhow::bail!("daemon IPC is not yet supported on Windows")
166    }
167
168    /// Send a request and wait for the response.
169    #[cfg(unix)]
170    pub async fn send(&mut self, request: DaemonRequest) -> Result<DaemonResponse> {
171        let json = serde_json::to_string(&request)?;
172        self.writer.write_all(json.as_bytes()).await?;
173        self.writer.write_all(b"\n").await?;
174        self.writer.flush().await?;
175
176        let mut line = String::new();
177        self.reader.read_line(&mut line).await?;
178        let response: DaemonResponse = serde_json::from_str(line.trim())?;
179        Ok(response)
180    }
181}