Skip to main content

paper/daemon/
mod.rs

1//! Daemon core: IPC server, scheduler, watcher, resource guard, and auto-discovery.
2
3pub mod auto_discover;
4pub mod ipc;
5pub mod resource_guard;
6pub mod scheduler;
7pub mod watcher;
8
9pub use ipc::DaemonHandler;
10
11use crate::cli::Workspace;
12use crate::core::index::{init_db, Connection, Indexer};
13use crate::core::search::SharedEmbedder;
14use crate::daemon::auto_discover::discover_default_roots;
15use crate::daemon::ipc::{run_ipc_server, DaemonRequest, DaemonResponse};
16use crate::daemon::resource_guard::{PauseReason, ResourceGuard, ResourceGuardConfig};
17use crate::daemon::scheduler::RootAwareScheduler;
18use crate::daemon::watcher::Watcher;
19use anyhow::Result;
20use clap::Args;
21use std::path::PathBuf;
22use std::sync::Arc;
23use tokio::signal;
24use tokio::sync::{mpsc, RwLock};
25
26/// Arguments for the daemon subcommand.
27#[derive(Args, Debug, Clone)]
28pub struct DaemonArgs {
29    /// Run in foreground (don't daemonize)
30    #[arg(long)]
31    pub foreground: bool,
32
33    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock)
34    #[arg(long)]
35    pub socket: Option<PathBuf>,
36
37    /// Roots to index (default: auto-discover Documents, Downloads, Desktop)
38    #[arg(long, short)]
39    pub root: Vec<PathBuf>,
40
41    /// Disable file system watcher
42    #[arg(long)]
43    pub no_watch: bool,
44
45    /// Disable scheduler
46    #[arg(long)]
47    pub no_schedule: bool,
48
49    /// Disable resource guard (battery/CPU monitoring)
50    #[arg(long)]
51    pub no_resource_guard: bool,
52
53    /// Full reindex cron expression (default: "0 0 3 * * *" = daily 3 AM)
54    #[arg(long)]
55    pub full_cron: Option<String>,
56
57    /// Incremental index interval in seconds (default: 300 = 5 min)
58    #[arg(long)]
59    pub incremental_interval: Option<u64>,
60
61    /// Debounce time for file watcher in milliseconds (default: 250)
62    #[arg(long)]
63    pub debounce_ms: Option<u64>,
64
65    /// Battery threshold percentage (default: 20)
66    #[arg(long)]
67    pub battery_threshold: Option<u8>,
68
69    /// CPU threshold percentage (default: 80)
70    #[arg(long)]
71    pub cpu_threshold: Option<u8>,
72}
73
74/// Shared daemon state.
75///
76/// Deliberately does NOT hold an `Indexer` or `Connection`: rusqlite
77/// connections are not `Sync`, so each indexing request opens a fresh
78/// connection inside `spawn_blocking` (the same pattern the CLI uses).
79struct DaemonState {
80    roots: RwLock<Vec<PathBuf>>,
81    paused: RwLock<bool>,
82    db_path: PathBuf,
83    embedder: Option<SharedEmbedder>,
84}
85
86/// Daemon request handler.
87struct DaemonHandlerImpl {
88    state: Arc<DaemonState>,
89    scheduler: Arc<RootAwareScheduler>,
90    watcher: Arc<RwLock<Option<Watcher>>>,
91    request_tx: mpsc::Sender<DaemonRequest>,
92}
93
94#[async_trait::async_trait]
95impl DaemonHandler for DaemonHandlerImpl {
96    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
97        match request {
98            DaemonRequest::IndexRoots { roots } => {
99                let roots_to_index = if roots.is_empty() {
100                    self.state.roots.read().await.clone()
101                } else {
102                    roots
103                };
104
105                if roots_to_index.is_empty() {
106                    return DaemonResponse::Error {
107                        msg: "No roots configured for indexing".to_string(),
108                    };
109                }
110
111                if *self.state.paused.read().await {
112                    return DaemonResponse::Error {
113                        msg: "Indexing paused by resource guard".to_string(),
114                    };
115                }
116
117                let db_path = self.state.db_path.clone();
118                let embedder = self.state.embedder.clone();
119
120                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
121                // create it inside the blocking task and run it there.
122                match tokio::task::spawn_blocking(
123                    move || -> Result<crate::core::index::IndexStats> {
124                        let conn = Connection::open(&db_path)?;
125                        init_db(&conn)?;
126                        let indexer = Indexer::new(conn, embedder)?;
127                        indexer.index_roots(&roots_to_index)
128                    },
129                )
130                .await
131                {
132                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
133                    Ok(Err(e)) => DaemonResponse::Error {
134                        msg: format!("Indexing failed: {e}"),
135                    },
136                    Err(e) => DaemonResponse::Error {
137                        msg: format!("Indexing task failed: {e}"),
138                    },
139                }
140            }
141            DaemonRequest::AddRoot { path } => {
142                if !path.exists() {
143                    return DaemonResponse::Error {
144                        msg: format!("Path does not exist: {}", path.display()),
145                    };
146                }
147
148                let mut roots = self.state.roots.write().await;
149                if !roots.contains(&path) {
150                    roots.push(path.clone());
151                    drop(roots);
152
153                    if let Some(watcher) = self.watcher.write().await.as_mut() {
154                        let _ = watcher.add_root(path.clone()).await;
155                    }
156                    self.scheduler.add_root(path).await;
157                }
158                DaemonResponse::Ok
159            }
160            DaemonRequest::RemoveRoot { path } => {
161                self.state.roots.write().await.retain(|r| r != &path);
162
163                if let Some(watcher) = self.watcher.write().await.as_mut() {
164                    let _ = watcher.remove_root(&path).await;
165                }
166                self.scheduler.remove_root(&path).await;
167                DaemonResponse::Ok
168            }
169            DaemonRequest::GetStatus => {
170                let indexed_files = self.count_indexed_files();
171                let paused = *self.state.paused.read().await;
172                let model = self.stored_embedding_model();
173
174                DaemonResponse::Status {
175                    indexed_files,
176                    queued: 0,
177                    paused,
178                    model,
179                }
180            }
181            DaemonRequest::Pause => {
182                *self.state.paused.write().await = true;
183                DaemonResponse::Ok
184            }
185            DaemonRequest::Resume => {
186                *self.state.paused.write().await = false;
187                DaemonResponse::Ok
188            }
189            DaemonRequest::Shutdown => {
190                if self.request_tx.send(DaemonRequest::Shutdown).await.is_err() {
191                    return DaemonResponse::Error {
192                        msg: "Daemon dispatch loop is not running".to_string(),
193                    };
194                }
195                DaemonResponse::Ok
196            }
197        }
198    }
199}
200
201impl DaemonHandlerImpl {
202    fn count_indexed_files(&self) -> usize {
203        let Ok(conn) = Connection::open(&self.state.db_path) else {
204            return 0;
205        };
206        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
207            .unwrap_or(0) as usize
208    }
209
210    fn stored_embedding_model(&self) -> Option<String> {
211        let Ok(conn) = Connection::open(&self.state.db_path) else {
212            return None;
213        };
214        conn.stored_embedding_model().ok().flatten()
215    }
216}
217
218/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
219pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
220    let workspace = Workspace::new();
221
222    // Determine socket path
223    let socket_path = args
224        .socket
225        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
226
227    // Ensure parent directory exists
228    if let Some(parent) = socket_path.parent() {
229        tokio::fs::create_dir_all(parent).await?;
230    }
231
232    // Determine roots to index
233    let roots = if args.root.is_empty() {
234        discover_default_roots()
235    } else {
236        args.root.clone()
237    };
238
239    if roots.is_empty() {
240        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
241    } else {
242        tracing::info!("Daemon will index: {:?}", roots);
243    }
244
245    // Load the embedder once (only if already on disk — never download here).
246    let embedder = workspace.embedder();
247    let db_path = workspace.paths.db_path();
248
249    // Create channels
250    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
251
252    // Create shared state
253    let state = Arc::new(DaemonState {
254        roots: RwLock::new(roots.clone()),
255        paused: RwLock::new(false),
256        db_path,
257        embedder,
258    });
259
260    // Create scheduler
261    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
262    let incremental_interval = args
263        .incremental_interval
264        .map(std::time::Duration::from_secs)
265        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
266    let scheduler = Arc::new(RootAwareScheduler::new(
267        &full_cron,
268        incremental_interval,
269        request_tx.clone(),
270    )?);
271    scheduler.set_roots(roots.clone()).await;
272
273    // Create watcher
274    let debounce_ms = args.debounce_ms.unwrap_or(250);
275    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
276    for root in &roots {
277        watcher.add_root(root.clone()).await?;
278    }
279    let watcher = Arc::new(RwLock::new(Some(watcher)));
280
281    // Create resource guard
282    let mut resource_config = ResourceGuardConfig::default();
283    if let Some(b) = args.battery_threshold {
284        resource_config.battery_threshold = b;
285    }
286    if let Some(c) = args.cpu_threshold {
287        resource_config.cpu_threshold = c;
288    }
289    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
290
291    // Create handler
292    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
293        state: state.clone(),
294        scheduler: scheduler.clone(),
295        watcher: watcher.clone(),
296        request_tx: request_tx.clone(),
297    });
298
299    // Start components
300    if !args.no_schedule {
301        scheduler.start().await;
302    }
303
304    if !args.no_watch {
305        if let Some(w) = watcher.write().await.as_mut() {
306            w.start().await?;
307        }
308    }
309
310    if !args.no_resource_guard {
311        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
312        resource_guard.start_monitoring(pause_tx);
313        let state = state.clone();
314        tokio::spawn(async move {
315            while let Some(reason) = pause_rx.recv().await {
316                match reason {
317                    PauseReason::Resumed => {
318                        *state.paused.write().await = false;
319                        tracing::info!("Resource guard: resuming indexing");
320                    }
321                    other => {
322                        *state.paused.write().await = true;
323                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
324                    }
325                }
326            }
327        });
328    }
329
330    // Start IPC server task
331    let socket_path_clone = socket_path.clone();
332    let handler_clone = handler.clone();
333    let ipc_handle = tokio::spawn(async move {
334        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
335            tracing::error!("IPC server error: {e}");
336        }
337    });
338
339    // Handle shutdown signals
340    let shutdown = async {
341        #[cfg(unix)]
342        {
343            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
344            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
345            tokio::select! {
346                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
347                _ = sigint.recv() => tracing::info!("Received SIGINT"),
348            }
349        }
350        #[cfg(windows)]
351        {
352            signal::ctrl_c().await?;
353            tracing::info!("Received Ctrl+C");
354        }
355        Ok::<(), anyhow::Error>(())
356    };
357
358    // Dispatch loop: requests from the scheduler and watcher are handled here;
359    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
360    let dispatch = async {
361        while let Some(request) = request_rx.recv().await {
362            if matches!(request, DaemonRequest::Shutdown) {
363                break;
364            }
365            let handler = handler.clone();
366            tokio::spawn(async move {
367                let _ = handler.handle(request).await;
368            });
369        }
370    };
371
372    // Run until shutdown signal or shutdown request
373    tokio::select! {
374        _ = shutdown => {
375            tracing::info!("Shutting down daemon...");
376        }
377        _ = dispatch => {
378            tracing::info!("Shutdown requested via IPC...");
379        }
380    }
381
382    // Graceful shutdown
383    scheduler.stop().await;
384
385    if let Some(w) = watcher.write().await.as_mut() {
386        w.stop().await;
387    }
388
389    ipc_handle.abort();
390    let _ = ipc_handle.await;
391
392    // Clean up socket file
393    let _ = tokio::fs::remove_file(&socket_path).await;
394
395    tracing::info!("Daemon stopped");
396    Ok(0)
397}