1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
19#[serde(tag = "type", rename_all = "snake_case")]
20pub enum DaemonRequest {
21 IndexRoots { roots: Vec<PathBuf> },
23 AddRoot { path: PathBuf },
25 RemoveRoot { path: PathBuf },
27 GetStatus,
29 Pause,
31 Resume,
33 Shutdown,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(tag = "type", rename_all = "snake_case")]
40pub enum DaemonResponse {
41 IndexRoots { stats: IndexStats },
43 Status {
45 indexed_files: usize,
46 queued: usize,
47 paused: bool,
48 model: Option<String>,
49 },
50 Ok,
52 Error { msg: String },
54}
55
56#[async_trait]
58pub trait DaemonHandler: Send + Sync {
59 async fn handle(&self, request: DaemonRequest) -> DaemonResponse;
61}
62
63#[cfg(unix)]
68pub async fn run_ipc_server(socket_path: &Path, handler: Arc<dyn DaemonHandler>) -> Result<()> {
69 use tokio::net::UnixListener;
70
71 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#[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; }
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
140pub 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 #[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 #[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 #[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}