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, Notify, 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    shutdown: RwLock<bool>,
83    shutdown_notify: Arc<Notify>,
84    db_path: PathBuf,
85    embedder: Option<SharedEmbedder>,
86}
87
88/// Daemon request handler.
89struct DaemonHandlerImpl {
90    state: Arc<DaemonState>,
91    scheduler: Arc<RootAwareScheduler>,
92    watcher: Arc<RwLock<Option<Watcher>>>,
93}
94
95#[async_trait::async_trait]
96impl DaemonHandler for DaemonHandlerImpl {
97    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
98        match request {
99            DaemonRequest::IndexRoots { roots } => {
100                let roots_to_index = if roots.is_empty() {
101                    self.state.roots.read().await.clone()
102                } else {
103                    roots
104                };
105
106                if roots_to_index.is_empty() {
107                    return DaemonResponse::Error {
108                        msg: "No roots configured for indexing".to_string(),
109                    };
110                }
111
112                if *self.state.paused.read().await {
113                    return DaemonResponse::Error {
114                        msg: "Indexing paused by resource guard".to_string(),
115                    };
116                }
117
118                let db_path = self.state.db_path.clone();
119                let embedder = self.state.embedder.clone();
120
121                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
122                // create it inside the blocking task and run it there.
123                match tokio::task::spawn_blocking(
124                    move || -> Result<crate::core::index::IndexStats> {
125                        let conn = Connection::open(&db_path)?;
126                        init_db(&conn)?;
127                        let indexer = Indexer::new(conn, embedder)?;
128                        indexer.index_roots(&roots_to_index)
129                    },
130                )
131                .await
132                {
133                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
134                    Ok(Err(e)) => DaemonResponse::Error {
135                        msg: format!("Indexing failed: {e}"),
136                    },
137                    Err(e) => DaemonResponse::Error {
138                        msg: format!("Indexing task failed: {e}"),
139                    },
140                }
141            }
142            DaemonRequest::AddRoot { path } => {
143                if !path.exists() {
144                    return DaemonResponse::Error {
145                        msg: format!("Path does not exist: {}", path.display()),
146                    };
147                }
148
149                let mut roots = self.state.roots.write().await;
150                if !roots.contains(&path) {
151                    roots.push(path.clone());
152                    drop(roots);
153
154                    if let Some(watcher) = self.watcher.write().await.as_mut() {
155                        let _ = watcher.add_root(path.clone()).await;
156                    }
157                    self.scheduler.add_root(path).await;
158                }
159                DaemonResponse::Ok
160            }
161            DaemonRequest::RemoveRoot { path } => {
162                self.state.roots.write().await.retain(|r| r != &path);
163
164                if let Some(watcher) = self.watcher.write().await.as_mut() {
165                    let _ = watcher.remove_root(&path).await;
166                }
167                self.scheduler.remove_root(&path).await;
168                DaemonResponse::Ok
169            }
170            DaemonRequest::GetStatus => {
171                let paused = *self.state.paused.read().await;
172                // Open one connection and reuse it for both status queries
173                // instead of opening two separate connections (M15).
174                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
175                    Ok(conn) => (
176                        Self::count_indexed_files(&conn),
177                        Self::stored_embedding_model(&conn),
178                    ),
179                    Err(_) => (0, None),
180                };
181
182                DaemonResponse::Status {
183                    indexed_files,
184                    queued: 0,
185                    paused,
186                    model,
187                }
188            }
189            DaemonRequest::Pause => {
190                *self.state.paused.write().await = true;
191                DaemonResponse::Ok
192            }
193            DaemonRequest::Resume => {
194                *self.state.paused.write().await = false;
195                DaemonResponse::Ok
196            }
197            DaemonRequest::Shutdown => {
198                // Signal shutdown via a flag and wake the dispatch loop; do not
199                // re-enqueue Shutdown on the same channel (IK).
200                *self.state.shutdown.write().await = true;
201                self.state.shutdown_notify.notify_waiters();
202                DaemonResponse::Ok
203            }
204        }
205    }
206}
207
208impl DaemonHandlerImpl {
209    fn count_indexed_files(conn: &Connection) -> usize {
210        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
211            .unwrap_or(0) as usize
212    }
213
214    fn stored_embedding_model(conn: &Connection) -> Option<String> {
215        conn.stored_embedding_model().ok().flatten()
216    }
217}
218
219/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
220pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
221    let workspace = Workspace::new();
222
223    // Determine socket path
224    let socket_path = args
225        .socket
226        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
227
228    // Ensure parent directory exists
229    if let Some(parent) = socket_path.parent() {
230        tokio::fs::create_dir_all(parent).await?;
231    }
232
233    // Determine roots to index
234    let roots = if args.root.is_empty() {
235        discover_default_roots()
236    } else {
237        args.root.clone()
238    };
239
240    if roots.is_empty() {
241        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
242    } else {
243        tracing::info!("Daemon will index: {:?}", roots);
244    }
245
246    // Load the embedder once (only if already on disk — never download here).
247    let embedder = workspace.embedder();
248    let db_path = workspace.paths.db_path();
249
250    // Create channels
251    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
252
253    // Create shared state
254    let state = Arc::new(DaemonState {
255        roots: RwLock::new(roots.clone()),
256        paused: RwLock::new(false),
257        shutdown: RwLock::new(false),
258        shutdown_notify: Arc::new(Notify::new()),
259        db_path,
260        embedder,
261    });
262
263    // Create scheduler
264    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
265    let incremental_interval = args
266        .incremental_interval
267        .map(std::time::Duration::from_secs)
268        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
269    let scheduler = Arc::new(RootAwareScheduler::new(
270        &full_cron,
271        incremental_interval,
272        request_tx.clone(),
273    )?);
274    scheduler.set_roots(roots.clone()).await;
275
276    // Create watcher
277    let debounce_ms = args.debounce_ms.unwrap_or(250);
278    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
279    for root in &roots {
280        watcher.add_root(root.clone()).await?;
281    }
282    let watcher = Arc::new(RwLock::new(Some(watcher)));
283
284    // Create resource guard
285    let mut resource_config = ResourceGuardConfig::default();
286    if let Some(b) = args.battery_threshold {
287        resource_config.battery_threshold = b;
288    }
289    if let Some(c) = args.cpu_threshold {
290        resource_config.cpu_threshold = c;
291    }
292    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
293
294    // Create handler
295    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
296        state: state.clone(),
297        scheduler: scheduler.clone(),
298        watcher: watcher.clone(),
299    });
300
301    // Start components
302    if !args.no_schedule {
303        scheduler.start().await;
304    }
305
306    if !args.no_watch {
307        if let Some(w) = watcher.write().await.as_mut() {
308            w.start().await?;
309        }
310    }
311
312    if !args.no_resource_guard {
313        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
314        resource_guard.start_monitoring(pause_tx);
315        let state = state.clone();
316        tokio::spawn(async move {
317            while let Some(reason) = pause_rx.recv().await {
318                match reason {
319                    PauseReason::Resumed => {
320                        *state.paused.write().await = false;
321                        tracing::info!("Resource guard: resuming indexing");
322                    }
323                    other => {
324                        *state.paused.write().await = true;
325                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
326                    }
327                }
328            }
329        });
330    }
331
332    // Start IPC server task
333    let socket_path_clone = socket_path.clone();
334    let handler_clone = handler.clone();
335    let ipc_handle = tokio::spawn(async move {
336        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
337            tracing::error!("IPC server error: {e}");
338        }
339    });
340
341    // Handle shutdown signals
342    let shutdown = async {
343        #[cfg(unix)]
344        {
345            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
346            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
347            tokio::select! {
348                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
349                _ = sigint.recv() => tracing::info!("Received SIGINT"),
350            }
351        }
352        #[cfg(windows)]
353        {
354            signal::ctrl_c().await?;
355            tracing::info!("Received Ctrl+C");
356        }
357        Ok::<(), anyhow::Error>(())
358    };
359
360    // Dispatch loop: requests from the scheduler and watcher are handled here;
361    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
362    let dispatch = async {
363        let state = state.clone();
364        loop {
365            tokio::select! {
366                // A request from the scheduler, watcher, or a directly-enqueued
367                // Shutdown.
368                request = request_rx.recv() => {
369                    match request {
370                        Some(request) => {
371                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
372                                break;
373                            }
374                            let handler = handler.clone();
375                            tokio::spawn(async move {
376                                let _ = handler.handle(request).await;
377                            });
378                        }
379                        None => break, // channel closed
380                    }
381                }
382                // Woken by the Shutdown handler (IK) so we can check the flag.
383                _ = state.shutdown_notify.notified() => {
384                    if *state.shutdown.read().await {
385                        break;
386                    }
387                }
388            }
389        }
390    };
391
392    // Run until shutdown signal or shutdown request
393    tokio::select! {
394        _ = shutdown => {
395            tracing::info!("Shutting down daemon...");
396        }
397        _ = dispatch => {
398            tracing::info!("Shutdown requested via IPC...");
399        }
400    }
401
402    // Graceful shutdown
403    scheduler.stop().await;
404
405    if let Some(w) = watcher.write().await.as_mut() {
406        w.stop().await;
407    }
408
409    ipc_handle.abort();
410    let _ = ipc_handle.await;
411
412    // Clean up socket file
413    let _ = tokio::fs::remove_file(&socket_path).await;
414
415    tracing::info!("Daemon stopped");
416    Ok(0)
417}