Skip to main content

paper/cli/
daemon.rs

1//! CLI control and OS service integration for the Paper daemon.
2
3use crate::core::paths::Paths;
4#[cfg(unix)]
5use crate::daemon::ipc::IpcClient;
6use crate::daemon::ipc::{DaemonRequest, DaemonResponse};
7#[cfg(unix)]
8use anyhow::Context;
9use anyhow::{bail, Result};
10use clap::{Args, Subcommand};
11#[cfg(any(target_os = "linux", target_os = "macos"))]
12use std::fs;
13#[cfg(any(target_os = "linux", target_os = "macos"))]
14use std::io::Write;
15use std::path::{Path, PathBuf};
16#[cfg(any(target_os = "linux", target_os = "macos"))]
17use std::process::Command;
18#[cfg(unix)]
19use std::time::Duration;
20
21#[cfg(unix)]
22const IPC_TIMEOUT: Duration = Duration::from_secs(5);
23const LAUNCHD_LABEL: &str = "tools.kintsugi.paper";
24#[cfg(target_os = "linux")]
25const SYSTEMD_SERVICE_NAME: &str = "paper.service";
26
27/// Control a running daemon or manage its OS service.
28#[derive(Args, Debug)]
29pub struct DaemonControlArgs {
30    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock).
31    #[arg(long, global = true)]
32    pub socket: Option<PathBuf>,
33
34    #[command(subcommand)]
35    pub command: DaemonControlCommand,
36}
37
38#[derive(Subcommand, Debug)]
39pub enum DaemonControlCommand {
40    /// Show daemon status.
41    Status {
42        /// Emit the status response as JSON.
43        #[arg(long)]
44        json: bool,
45    },
46    /// Pause indexing.
47    Pause,
48    /// Resume indexing.
49    Resume,
50    /// Index roots now (no roots = the daemon's configured roots).
51    Index {
52        #[arg(long)]
53        root: Vec<PathBuf>,
54    },
55    /// Add a root to watch and index.
56    AddRoot { path: PathBuf },
57    /// Remove a root from watching and indexing.
58    RemoveRoot { path: PathBuf },
59    /// Ask the daemon to shut down gracefully.
60    Stop,
61    /// Install and start Paper as a user service.
62    Install {
63        /// Overwrite an existing, different service definition.
64        #[arg(long)]
65        force: bool,
66    },
67    /// Stop and remove the Paper user service.
68    Uninstall,
69    /// Start the installed Paper user service.
70    Start,
71    /// Restart the installed Paper user service.
72    Restart,
73}
74
75pub async fn run(args: DaemonControlArgs) -> Result<i32> {
76    let DaemonControlArgs { socket, command } = args;
77    let socket_path = socket.unwrap_or_else(|| Paths::new().base_dir().join("daemon.sock"));
78
79    match command {
80        DaemonControlCommand::Status { json } => {
81            let response = send_request(&socket_path, DaemonRequest::GetStatus).await?;
82            print_status(&response, json)?;
83        }
84        DaemonControlCommand::Pause => {
85            expect_ok(send_request(&socket_path, DaemonRequest::Pause).await?)?;
86            println!("Daemon indexing paused.");
87        }
88        DaemonControlCommand::Resume => {
89            expect_ok(send_request(&socket_path, DaemonRequest::Resume).await?)?;
90            println!("Daemon indexing resumed.");
91        }
92        DaemonControlCommand::Index { root } => {
93            let response =
94                send_request(&socket_path, DaemonRequest::IndexRoots { roots: root }).await?;
95            match response {
96                DaemonResponse::IndexRoots { stats } => {
97                    println!(
98                        "Indexed {} file(s) ({} chunks); {} scanned, {} unchanged, {} skipped, {} warning(s).",
99                        stats.indexed,
100                        stats.chunks,
101                        stats.scanned,
102                        stats.unchanged,
103                        stats.skipped,
104                        stats.warnings
105                    );
106                    if stats.denied > 0 || stats.backed_off > 0 {
107                        println!(
108                            "  {} unreadable (permission denied), {} deferred by the backoff",
109                            stats.denied, stats.backed_off
110                        );
111                    }
112                }
113                DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
114                other => bail!("unexpected daemon response to index request: {other:?}"),
115            }
116        }
117        DaemonControlCommand::AddRoot { path } => {
118            let path = canonical_or_original(&path);
119            persist_root(Some(&path), None)?;
120            expect_ok(
121                send_request(&socket_path, DaemonRequest::AddRoot { path: path.clone() }).await?,
122            )?;
123            println!("Added indexing root: {}", path.display());
124        }
125        DaemonControlCommand::RemoveRoot { path } => {
126            let path = canonical_or_original(&path);
127            persist_root(None, Some(&path))?;
128            expect_ok(
129                send_request(
130                    &socket_path,
131                    DaemonRequest::RemoveRoot { path: path.clone() },
132                )
133                .await?,
134            )?;
135            println!("Removed indexing root: {}", path.display());
136        }
137        DaemonControlCommand::Stop => {
138            expect_ok(send_request(&socket_path, DaemonRequest::Shutdown).await?)?;
139            println!("Daemon shutdown requested.");
140        }
141        DaemonControlCommand::Install { force } => {
142            let path = install_service(force)?;
143            println!("Installed and started Paper service: {}", path.display());
144        }
145        DaemonControlCommand::Uninstall => {
146            let path = uninstall_service()?;
147            println!("Uninstalled Paper service: {}", path.display());
148        }
149        DaemonControlCommand::Start => {
150            start_service()?;
151            println!("Started Paper service.");
152        }
153        DaemonControlCommand::Restart => {
154            restart_service()?;
155            println!("Restarted Paper service.");
156        }
157    }
158
159    Ok(super::EXIT_FOUND)
160}
161
162fn print_status(response: &DaemonResponse, json: bool) -> Result<()> {
163    match response {
164        DaemonResponse::Status {
165            indexed_files,
166            queued,
167            paused,
168            model,
169        } => {
170            if json {
171                println!("{}", serde_json::to_string(response)?);
172            } else {
173                println!("Indexed files: {indexed_files}");
174                println!("Queued: {queued}");
175                println!("Paused: {paused}");
176                println!("Model: {}", model.as_deref().unwrap_or("none"));
177            }
178            Ok(())
179        }
180        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
181        other => bail!("unexpected daemon response to status request: {other:?}"),
182    }
183}
184
185fn expect_ok(response: DaemonResponse) -> Result<()> {
186    match response {
187        DaemonResponse::Ok => Ok(()),
188        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
189        other => bail!("unexpected daemon response: {other:?}"),
190    }
191}
192
193#[cfg(unix)]
194async fn send_request(socket_path: &Path, request: DaemonRequest) -> Result<DaemonResponse> {
195    let operation = async {
196        let mut client = IpcClient::connect(socket_path).await.with_context(|| {
197            format!(
198                "could not connect to paper daemon at {}; start it with `paper daemon --foreground` or run `paper daemon-control install`",
199                socket_path.display()
200            )
201        })?;
202        client.send(request).await.with_context(|| {
203            format!(
204                "communicating with paper daemon at {}",
205                socket_path.display()
206            )
207        })
208    };
209
210    tokio::time::timeout(IPC_TIMEOUT, operation)
211        .await
212        .map_err(|_| {
213            anyhow::anyhow!(
214                "paper daemon at {} did not respond within {} seconds",
215                socket_path.display(),
216                IPC_TIMEOUT.as_secs()
217            )
218        })?
219}
220
221#[cfg(not(unix))]
222async fn send_request(_socket_path: &Path, _request: DaemonRequest) -> Result<DaemonResponse> {
223    bail!("daemon IPC is not yet supported on Windows")
224}
225
226/// Render a systemd user unit without touching the host service manager.
227pub fn render_systemd_unit(exe_path: &Path) -> String {
228    let exe = systemd_argument(&exe_path.to_string_lossy());
229    format!(
230        "# Managed by `paper daemon-control`.\n\
231         [Unit]\n\
232         Description=Paper local document index daemon\n\n\
233         [Service]\n\
234         Type=simple\n\
235         ExecStart={exe} daemon --foreground\n\
236         Restart=on-failure\n\n\
237         [Install]\n\
238         WantedBy=default.target\n"
239    )
240}
241
242fn systemd_argument(value: &str) -> String {
243    let escaped = value
244        .replace('\\', "\\\\")
245        .replace('"', "\\\"")
246        .replace('%', "%%");
247    format!("\"{escaped}\"")
248}
249
250/// Render a launchd user agent without touching the host service manager.
251pub fn render_launchd_plist(exe_path: &Path, cache_dir: &Path) -> String {
252    let exe = xml_escape(&exe_path.to_string_lossy());
253    let stdout = xml_escape(&format!(
254        "{}/daemon.stdout.log",
255        cache_dir.to_string_lossy().replace('\\', "/")
256    ));
257    let stderr = xml_escape(&format!(
258        "{}/daemon.stderr.log",
259        cache_dir.to_string_lossy().replace('\\', "/")
260    ));
261    format!(
262        r#"<?xml version="1.0" encoding="UTF-8"?>
263<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
264<!-- Managed by `paper daemon-control`. -->
265<plist version="1.0">
266  <dict>
267    <key>Label</key>
268    <string>{LAUNCHD_LABEL}</string>
269    <key>ProgramArguments</key>
270    <array>
271      <string>{exe}</string>
272      <string>daemon</string>
273      <string>--foreground</string>
274    </array>
275    <key>RunAtLoad</key>
276    <true/>
277    <key>KeepAlive</key>
278    <false/>
279    <key>StandardOutPath</key>
280    <string>{stdout}</string>
281    <key>StandardErrorPath</key>
282    <string>{stderr}</string>
283  </dict>
284</plist>
285"#
286    )
287}
288
289fn xml_escape(value: &str) -> String {
290    value
291        .replace('&', "&amp;")
292        .replace('<', "&lt;")
293        .replace('>', "&gt;")
294        .replace('"', "&quot;")
295        .replace('\'', "&apos;")
296}
297
298#[cfg(any(target_os = "linux", target_os = "macos"))]
299fn install_service_file(path: &Path, contents: &str, force: bool) -> Result<()> {
300    if !force && path.exists() {
301        let existing = fs::read_to_string(path)
302            .with_context(|| format!("reading existing service file {}", path.display()))?;
303        if existing != contents {
304            bail!(
305                "service file {} already exists with different contents; use `paper daemon-control install --force` to replace it",
306                path.display()
307            );
308        }
309    }
310    atomic_write(path, contents)
311}
312
313#[cfg(any(target_os = "linux", target_os = "macos"))]
314fn atomic_write(path: &Path, contents: &str) -> Result<()> {
315    let parent = path
316        .parent()
317        .with_context(|| format!("service path has no parent: {}", path.display()))?;
318    fs::create_dir_all(parent)
319        .with_context(|| format!("creating service directory {}", parent.display()))?;
320    let file_name = path
321        .file_name()
322        .with_context(|| format!("service path has no file name: {}", path.display()))?;
323    let temp_path = parent.join(format!(
324        ".{}.{}.tmp",
325        file_name.to_string_lossy(),
326        std::process::id()
327    ));
328
329    let result = (|| -> Result<()> {
330        let mut file = fs::OpenOptions::new()
331            .write(true)
332            .create_new(true)
333            .open(&temp_path)
334            .with_context(|| format!("creating temporary service file {}", temp_path.display()))?;
335        file.write_all(contents.as_bytes())
336            .with_context(|| format!("writing temporary service file {}", temp_path.display()))?;
337        file.sync_all()
338            .with_context(|| format!("syncing temporary service file {}", temp_path.display()))?;
339        fs::rename(&temp_path, path).with_context(|| {
340            format!(
341                "renaming temporary service file {} to {}",
342                temp_path.display(),
343                path.display()
344            )
345        })?;
346        Ok(())
347    })();
348
349    if result.is_err() {
350        let _ = fs::remove_file(&temp_path);
351    }
352    result
353}
354
355#[cfg(any(target_os = "linux", target_os = "macos"))]
356fn remove_service_file(path: &Path) -> Result<()> {
357    match fs::remove_file(path) {
358        Ok(()) => Ok(()),
359        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
360        Err(error) => {
361            Err(error).with_context(|| format!("removing service file {}", path.display()))
362        }
363    }
364}
365
366#[cfg(any(target_os = "linux", target_os = "macos"))]
367fn require_service_installed(path: &Path) -> Result<()> {
368    if !path.is_file() {
369        bail!("Paper service is not installed; run `paper daemon-control install` first");
370    }
371    Ok(())
372}
373
374#[cfg(any(target_os = "linux", target_os = "macos"))]
375fn run_checked(command: &mut Command) -> Result<()> {
376    let display = format!("{command:?}");
377    let output = command
378        .output()
379        .with_context(|| format!("running {display}"))?;
380    if output.status.success() {
381        return Ok(());
382    }
383
384    let stderr = String::from_utf8_lossy(&output.stderr);
385    let stdout = String::from_utf8_lossy(&output.stdout);
386    let details = if stderr.trim().is_empty() {
387        stdout.trim()
388    } else {
389        stderr.trim()
390    };
391    bail!("{display} failed with {}: {details}", output.status)
392}
393
394#[cfg(target_os = "linux")]
395fn systemd_unit_path() -> Result<PathBuf> {
396    let config = dirs::config_dir().context("could not determine the user config directory")?;
397    Ok(config.join("systemd/user").join(SYSTEMD_SERVICE_NAME))
398}
399
400#[cfg(target_os = "linux")]
401fn install_service(force: bool) -> Result<PathBuf> {
402    let path = systemd_unit_path()?;
403    let exe = std::env::current_exe().context("locating the current paper executable")?;
404    let unit = render_systemd_unit(&exe);
405    install_service_file(&path, &unit, force)?;
406
407    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
408    run_checked(Command::new("systemctl").args([
409        "--user",
410        "enable",
411        "--now",
412        SYSTEMD_SERVICE_NAME,
413    ]))?;
414    Ok(path)
415}
416
417#[cfg(target_os = "linux")]
418fn uninstall_service() -> Result<PathBuf> {
419    let path = systemd_unit_path()?;
420    if let Err(error) = run_checked(Command::new("systemctl").args([
421        "--user",
422        "disable",
423        "--now",
424        SYSTEMD_SERVICE_NAME,
425    ])) {
426        tracing::warn!("Could not disable the Paper service cleanly: {error:#}");
427    }
428    remove_service_file(&path)?;
429    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
430    Ok(path)
431}
432
433#[cfg(target_os = "linux")]
434fn start_service() -> Result<()> {
435    require_service_installed(&systemd_unit_path()?)?;
436    run_checked(Command::new("systemctl").args(["--user", "start", SYSTEMD_SERVICE_NAME]))
437}
438
439#[cfg(target_os = "linux")]
440fn restart_service() -> Result<()> {
441    require_service_installed(&systemd_unit_path()?)?;
442    run_checked(Command::new("systemctl").args(["--user", "restart", SYSTEMD_SERVICE_NAME]))
443}
444
445#[cfg(target_os = "macos")]
446fn launchd_plist_path() -> Result<PathBuf> {
447    let home = dirs::home_dir().context("could not determine the user home directory")?;
448    Ok(home
449        .join("Library/LaunchAgents")
450        .join(format!("{LAUNCHD_LABEL}.plist")))
451}
452
453#[cfg(target_os = "macos")]
454fn current_uid() -> Result<String> {
455    let output = Command::new("id")
456        .arg("-u")
457        .output()
458        .context("running `id -u` for launchd")?;
459    if !output.status.success() {
460        bail!("`id -u` failed with {}", output.status);
461    }
462    let uid = String::from_utf8(output.stdout).context("decoding `id -u` output")?;
463    let uid = uid.trim();
464    if uid.is_empty() {
465        bail!("`id -u` returned an empty user ID");
466    }
467    Ok(uid.to_string())
468}
469
470#[cfg(target_os = "macos")]
471fn load_launchd_service(domain: &str, path: &Path) -> Result<()> {
472    // Boot out any already-loaded copy first. `bootstrap` refuses to replace an
473    // existing job, so without this a reinstall that changes the binary path
474    // leaves launchd running the old, possibly deleted, executable forever
475    // (spawning it fails and the job exits 78, EX_CONFIG).
476    let service = format!("{domain}/{LAUNCHD_LABEL}");
477    let _ = run_checked(Command::new("launchctl").args(["bootout", &service]));
478
479    let bootstrap = run_checked(
480        Command::new("launchctl")
481            .args(["bootstrap", domain])
482            .arg(path),
483    );
484    if let Err(bootstrap_error) = bootstrap {
485        run_checked(Command::new("launchctl").arg("load").arg(path)).with_context(|| {
486            format!("launchctl bootstrap failed ({bootstrap_error:#}); `launchctl load` fallback also failed")
487        })?;
488    }
489    Ok(())
490}
491
492#[cfg(target_os = "macos")]
493fn install_service(force: bool) -> Result<PathBuf> {
494    let path = launchd_plist_path()?;
495    let exe = std::env::current_exe().context("locating the current paper executable")?;
496    let cache_dir = Paths::new().base_dir();
497    crate::core::paths::create_private_dir(&cache_dir)
498        .with_context(|| format!("creating Paper cache directory {}", cache_dir.display()))?;
499    let plist = render_launchd_plist(&exe, &cache_dir);
500    install_service_file(&path, &plist, force)?;
501
502    let domain = format!("gui/{}", current_uid()?);
503    load_launchd_service(&domain, &path)?;
504    Ok(path)
505}
506
507#[cfg(target_os = "macos")]
508fn uninstall_service() -> Result<PathBuf> {
509    let path = launchd_plist_path()?;
510    let domain = format!("gui/{}", current_uid()?);
511    let bootout = run_checked(
512        Command::new("launchctl")
513            .args(["bootout", &domain])
514            .arg(&path),
515    );
516    if let Err(bootout_error) = bootout {
517        if let Err(unload_error) = run_checked(Command::new("launchctl").arg("unload").arg(&path)) {
518            tracing::warn!(
519                "Could not unload the Paper launchd agent cleanly (bootout: {bootout_error:#}; unload: {unload_error:#})"
520            );
521        }
522    }
523    remove_service_file(&path)?;
524    Ok(path)
525}
526
527#[cfg(target_os = "macos")]
528fn start_service() -> Result<()> {
529    let path = launchd_plist_path()?;
530    require_service_installed(&path)?;
531    let domain = format!("gui/{}", current_uid()?);
532    let service = format!("{domain}/{LAUNCHD_LABEL}");
533    if run_checked(Command::new("launchctl").args(["kickstart", &service])).is_err() {
534        load_launchd_service(&domain, &path)?;
535    }
536    Ok(())
537}
538
539#[cfg(target_os = "macos")]
540fn restart_service() -> Result<()> {
541    let path = launchd_plist_path()?;
542    require_service_installed(&path)?;
543    let domain = format!("gui/{}", current_uid()?);
544    let service = format!("{domain}/{LAUNCHD_LABEL}");
545    if run_checked(Command::new("launchctl").args(["kickstart", "-k", &service])).is_err() {
546        load_launchd_service(&domain, &path)?;
547    }
548    Ok(())
549}
550
551#[cfg(not(any(target_os = "linux", target_os = "macos")))]
552fn install_service(_force: bool) -> Result<PathBuf> {
553    bail!("OS service installation is not yet supported on Windows; use Linux or macOS")
554}
555
556#[cfg(not(any(target_os = "linux", target_os = "macos")))]
557fn uninstall_service() -> Result<PathBuf> {
558    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
559}
560
561#[cfg(not(any(target_os = "linux", target_os = "macos")))]
562fn start_service() -> Result<()> {
563    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
564}
565
566#[cfg(not(any(target_os = "linux", target_os = "macos")))]
567fn restart_service() -> Result<()> {
568    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
569}
570
571/// Install the background service, or start it when its file already exists
572/// (for example after a binary upgrade). Used by first-run automation, so it
573/// must be idempotent and must not fail because the service was already
574/// registered.
575pub(crate) fn ensure_service() -> Result<()> {
576    match install_service(false) {
577        Ok(_) => Ok(()),
578        Err(install_error) => start_service().map_err(|start_error| {
579            anyhow::anyhow!("install failed ({install_error:#}); start failed ({start_error:#})")
580        }),
581    }
582}
583
584fn canonical_or_original(path: &Path) -> PathBuf {
585    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
586}
587
588/// Persist a root change in the config so it survives daemon restarts and
589/// reboots. Without this, `add-root` only lived until the daemon exited.
590fn persist_root(add: Option<&Path>, remove: Option<&Path>) -> Result<()> {
591    let mut config = crate::core::config::Config::load().unwrap_or_default();
592    if let Some(add) = add {
593        if !add.exists() {
594            bail!("{} does not exist", add.display());
595        }
596        if !config.roots.iter().any(|root| root == add) {
597            config.roots.push(add.to_path_buf());
598        }
599    }
600    if let Some(remove) = remove {
601        config.roots.retain(|root| root != remove);
602    }
603    config.save()
604}