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                }
107                DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
108                other => bail!("unexpected daemon response to index request: {other:?}"),
109            }
110        }
111        DaemonControlCommand::AddRoot { path } => {
112            expect_ok(
113                send_request(&socket_path, DaemonRequest::AddRoot { path: path.clone() }).await?,
114            )?;
115            println!("Added indexing root: {}", path.display());
116        }
117        DaemonControlCommand::RemoveRoot { path } => {
118            expect_ok(
119                send_request(
120                    &socket_path,
121                    DaemonRequest::RemoveRoot { path: path.clone() },
122                )
123                .await?,
124            )?;
125            println!("Removed indexing root: {}", path.display());
126        }
127        DaemonControlCommand::Stop => {
128            expect_ok(send_request(&socket_path, DaemonRequest::Shutdown).await?)?;
129            println!("Daemon shutdown requested.");
130        }
131        DaemonControlCommand::Install { force } => {
132            let path = install_service(force)?;
133            println!("Installed and started Paper service: {}", path.display());
134        }
135        DaemonControlCommand::Uninstall => {
136            let path = uninstall_service()?;
137            println!("Uninstalled Paper service: {}", path.display());
138        }
139        DaemonControlCommand::Start => {
140            start_service()?;
141            println!("Started Paper service.");
142        }
143        DaemonControlCommand::Restart => {
144            restart_service()?;
145            println!("Restarted Paper service.");
146        }
147    }
148
149    Ok(super::EXIT_FOUND)
150}
151
152fn print_status(response: &DaemonResponse, json: bool) -> Result<()> {
153    match response {
154        DaemonResponse::Status {
155            indexed_files,
156            queued,
157            paused,
158            model,
159        } => {
160            if json {
161                println!("{}", serde_json::to_string(response)?);
162            } else {
163                println!("Indexed files: {indexed_files}");
164                println!("Queued: {queued}");
165                println!("Paused: {paused}");
166                println!("Model: {}", model.as_deref().unwrap_or("none"));
167            }
168            Ok(())
169        }
170        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
171        other => bail!("unexpected daemon response to status request: {other:?}"),
172    }
173}
174
175fn expect_ok(response: DaemonResponse) -> Result<()> {
176    match response {
177        DaemonResponse::Ok => Ok(()),
178        DaemonResponse::Error { msg } => bail!("daemon error: {msg}"),
179        other => bail!("unexpected daemon response: {other:?}"),
180    }
181}
182
183#[cfg(unix)]
184async fn send_request(socket_path: &Path, request: DaemonRequest) -> Result<DaemonResponse> {
185    let operation = async {
186        let mut client = IpcClient::connect(socket_path).await.with_context(|| {
187            format!(
188                "could not connect to paper daemon at {}; start it with `paper daemon --foreground` or run `paper daemon-control install`",
189                socket_path.display()
190            )
191        })?;
192        client.send(request).await.with_context(|| {
193            format!(
194                "communicating with paper daemon at {}",
195                socket_path.display()
196            )
197        })
198    };
199
200    tokio::time::timeout(IPC_TIMEOUT, operation)
201        .await
202        .map_err(|_| {
203            anyhow::anyhow!(
204                "paper daemon at {} did not respond within {} seconds",
205                socket_path.display(),
206                IPC_TIMEOUT.as_secs()
207            )
208        })?
209}
210
211#[cfg(not(unix))]
212async fn send_request(_socket_path: &Path, _request: DaemonRequest) -> Result<DaemonResponse> {
213    bail!("daemon IPC is not yet supported on Windows")
214}
215
216/// Render a systemd user unit without touching the host service manager.
217pub fn render_systemd_unit(exe_path: &Path) -> String {
218    let exe = systemd_argument(&exe_path.to_string_lossy());
219    format!(
220        "# Managed by `paper daemon-control`.\n\
221         [Unit]\n\
222         Description=Paper local document index daemon\n\n\
223         [Service]\n\
224         Type=simple\n\
225         ExecStart={exe} daemon --foreground\n\
226         Restart=on-failure\n\n\
227         [Install]\n\
228         WantedBy=default.target\n"
229    )
230}
231
232fn systemd_argument(value: &str) -> String {
233    let escaped = value
234        .replace('\\', "\\\\")
235        .replace('"', "\\\"")
236        .replace('%', "%%");
237    format!("\"{escaped}\"")
238}
239
240/// Render a launchd user agent without touching the host service manager.
241pub fn render_launchd_plist(exe_path: &Path, cache_dir: &Path) -> String {
242    let exe = xml_escape(&exe_path.to_string_lossy());
243    let stdout = xml_escape(&cache_dir.join("daemon.stdout.log").to_string_lossy());
244    let stderr = xml_escape(&cache_dir.join("daemon.stderr.log").to_string_lossy());
245    format!(
246        r#"<?xml version="1.0" encoding="UTF-8"?>
247<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
248<!-- Managed by `paper daemon-control`. -->
249<plist version="1.0">
250  <dict>
251    <key>Label</key>
252    <string>{LAUNCHD_LABEL}</string>
253    <key>ProgramArguments</key>
254    <array>
255      <string>{exe}</string>
256      <string>daemon</string>
257      <string>--foreground</string>
258    </array>
259    <key>RunAtLoad</key>
260    <true/>
261    <key>KeepAlive</key>
262    <false/>
263    <key>StandardOutPath</key>
264    <string>{stdout}</string>
265    <key>StandardErrorPath</key>
266    <string>{stderr}</string>
267  </dict>
268</plist>
269"#
270    )
271}
272
273fn xml_escape(value: &str) -> String {
274    value
275        .replace('&', "&amp;")
276        .replace('<', "&lt;")
277        .replace('>', "&gt;")
278        .replace('"', "&quot;")
279        .replace('\'', "&apos;")
280}
281
282#[cfg(any(target_os = "linux", target_os = "macos"))]
283fn install_service_file(path: &Path, contents: &str, force: bool) -> Result<()> {
284    if !force && path.exists() {
285        let existing = fs::read_to_string(path)
286            .with_context(|| format!("reading existing service file {}", path.display()))?;
287        if existing != contents {
288            bail!(
289                "service file {} already exists with different contents; use `paper daemon-control install --force` to replace it",
290                path.display()
291            );
292        }
293    }
294    atomic_write(path, contents)
295}
296
297#[cfg(any(target_os = "linux", target_os = "macos"))]
298fn atomic_write(path: &Path, contents: &str) -> Result<()> {
299    let parent = path
300        .parent()
301        .with_context(|| format!("service path has no parent: {}", path.display()))?;
302    fs::create_dir_all(parent)
303        .with_context(|| format!("creating service directory {}", parent.display()))?;
304    let file_name = path
305        .file_name()
306        .with_context(|| format!("service path has no file name: {}", path.display()))?;
307    let temp_path = parent.join(format!(
308        ".{}.{}.tmp",
309        file_name.to_string_lossy(),
310        std::process::id()
311    ));
312
313    let result = (|| -> Result<()> {
314        let mut file = fs::OpenOptions::new()
315            .write(true)
316            .create_new(true)
317            .open(&temp_path)
318            .with_context(|| format!("creating temporary service file {}", temp_path.display()))?;
319        file.write_all(contents.as_bytes())
320            .with_context(|| format!("writing temporary service file {}", temp_path.display()))?;
321        file.sync_all()
322            .with_context(|| format!("syncing temporary service file {}", temp_path.display()))?;
323        fs::rename(&temp_path, path).with_context(|| {
324            format!(
325                "renaming temporary service file {} to {}",
326                temp_path.display(),
327                path.display()
328            )
329        })?;
330        Ok(())
331    })();
332
333    if result.is_err() {
334        let _ = fs::remove_file(&temp_path);
335    }
336    result
337}
338
339#[cfg(any(target_os = "linux", target_os = "macos"))]
340fn remove_service_file(path: &Path) -> Result<()> {
341    match fs::remove_file(path) {
342        Ok(()) => Ok(()),
343        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
344        Err(error) => {
345            Err(error).with_context(|| format!("removing service file {}", path.display()))
346        }
347    }
348}
349
350#[cfg(any(target_os = "linux", target_os = "macos"))]
351fn require_service_installed(path: &Path) -> Result<()> {
352    if !path.is_file() {
353        bail!("Paper service is not installed; run `paper daemon-control install` first");
354    }
355    Ok(())
356}
357
358#[cfg(any(target_os = "linux", target_os = "macos"))]
359fn run_checked(command: &mut Command) -> Result<()> {
360    let display = format!("{command:?}");
361    let output = command
362        .output()
363        .with_context(|| format!("running {display}"))?;
364    if output.status.success() {
365        return Ok(());
366    }
367
368    let stderr = String::from_utf8_lossy(&output.stderr);
369    let stdout = String::from_utf8_lossy(&output.stdout);
370    let details = if stderr.trim().is_empty() {
371        stdout.trim()
372    } else {
373        stderr.trim()
374    };
375    bail!("{display} failed with {}: {details}", output.status)
376}
377
378#[cfg(target_os = "linux")]
379fn systemd_unit_path() -> Result<PathBuf> {
380    let config = dirs::config_dir().context("could not determine the user config directory")?;
381    Ok(config.join("systemd/user").join(SYSTEMD_SERVICE_NAME))
382}
383
384#[cfg(target_os = "linux")]
385fn install_service(force: bool) -> Result<PathBuf> {
386    let path = systemd_unit_path()?;
387    let exe = std::env::current_exe().context("locating the current paper executable")?;
388    let unit = render_systemd_unit(&exe);
389    install_service_file(&path, &unit, force)?;
390
391    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
392    run_checked(Command::new("systemctl").args([
393        "--user",
394        "enable",
395        "--now",
396        SYSTEMD_SERVICE_NAME,
397    ]))?;
398    Ok(path)
399}
400
401#[cfg(target_os = "linux")]
402fn uninstall_service() -> Result<PathBuf> {
403    let path = systemd_unit_path()?;
404    if let Err(error) = run_checked(Command::new("systemctl").args([
405        "--user",
406        "disable",
407        "--now",
408        SYSTEMD_SERVICE_NAME,
409    ])) {
410        tracing::warn!("Could not disable the Paper service cleanly: {error:#}");
411    }
412    remove_service_file(&path)?;
413    run_checked(Command::new("systemctl").args(["--user", "daemon-reload"]))?;
414    Ok(path)
415}
416
417#[cfg(target_os = "linux")]
418fn start_service() -> Result<()> {
419    require_service_installed(&systemd_unit_path()?)?;
420    run_checked(Command::new("systemctl").args(["--user", "start", SYSTEMD_SERVICE_NAME]))
421}
422
423#[cfg(target_os = "linux")]
424fn restart_service() -> Result<()> {
425    require_service_installed(&systemd_unit_path()?)?;
426    run_checked(Command::new("systemctl").args(["--user", "restart", SYSTEMD_SERVICE_NAME]))
427}
428
429#[cfg(target_os = "macos")]
430fn launchd_plist_path() -> Result<PathBuf> {
431    let home = dirs::home_dir().context("could not determine the user home directory")?;
432    Ok(home
433        .join("Library/LaunchAgents")
434        .join(format!("{LAUNCHD_LABEL}.plist")))
435}
436
437#[cfg(target_os = "macos")]
438fn current_uid() -> Result<String> {
439    let output = Command::new("id")
440        .arg("-u")
441        .output()
442        .context("running `id -u` for launchd")?;
443    if !output.status.success() {
444        bail!("`id -u` failed with {}", output.status);
445    }
446    let uid = String::from_utf8(output.stdout).context("decoding `id -u` output")?;
447    let uid = uid.trim();
448    if uid.is_empty() {
449        bail!("`id -u` returned an empty user ID");
450    }
451    Ok(uid.to_string())
452}
453
454#[cfg(target_os = "macos")]
455fn load_launchd_service(domain: &str, path: &Path) -> Result<()> {
456    let bootstrap = run_checked(
457        Command::new("launchctl")
458            .args(["bootstrap", domain])
459            .arg(path),
460    );
461    if let Err(bootstrap_error) = bootstrap {
462        run_checked(Command::new("launchctl").arg("load").arg(path)).with_context(|| {
463            format!("launchctl bootstrap failed ({bootstrap_error:#}); `launchctl load` fallback also failed")
464        })?;
465    }
466    Ok(())
467}
468
469#[cfg(target_os = "macos")]
470fn install_service(force: bool) -> Result<PathBuf> {
471    let path = launchd_plist_path()?;
472    let exe = std::env::current_exe().context("locating the current paper executable")?;
473    let cache_dir = Paths::new().base_dir();
474    fs::create_dir_all(&cache_dir)
475        .with_context(|| format!("creating Paper cache directory {}", cache_dir.display()))?;
476    let plist = render_launchd_plist(&exe, &cache_dir);
477    install_service_file(&path, &plist, force)?;
478
479    let domain = format!("gui/{}", current_uid()?);
480    load_launchd_service(&domain, &path)?;
481    Ok(path)
482}
483
484#[cfg(target_os = "macos")]
485fn uninstall_service() -> Result<PathBuf> {
486    let path = launchd_plist_path()?;
487    let domain = format!("gui/{}", current_uid()?);
488    let bootout = run_checked(
489        Command::new("launchctl")
490            .args(["bootout", &domain])
491            .arg(&path),
492    );
493    if let Err(bootout_error) = bootout {
494        if let Err(unload_error) = run_checked(Command::new("launchctl").arg("unload").arg(&path)) {
495            tracing::warn!(
496                "Could not unload the Paper launchd agent cleanly (bootout: {bootout_error:#}; unload: {unload_error:#})"
497            );
498        }
499    }
500    remove_service_file(&path)?;
501    Ok(path)
502}
503
504#[cfg(target_os = "macos")]
505fn start_service() -> Result<()> {
506    let path = launchd_plist_path()?;
507    require_service_installed(&path)?;
508    let domain = format!("gui/{}", current_uid()?);
509    let service = format!("{domain}/{LAUNCHD_LABEL}");
510    if run_checked(Command::new("launchctl").args(["kickstart", &service])).is_err() {
511        load_launchd_service(&domain, &path)?;
512    }
513    Ok(())
514}
515
516#[cfg(target_os = "macos")]
517fn restart_service() -> Result<()> {
518    let path = launchd_plist_path()?;
519    require_service_installed(&path)?;
520    let domain = format!("gui/{}", current_uid()?);
521    let service = format!("{domain}/{LAUNCHD_LABEL}");
522    if run_checked(Command::new("launchctl").args(["kickstart", "-k", &service])).is_err() {
523        load_launchd_service(&domain, &path)?;
524    }
525    Ok(())
526}
527
528#[cfg(not(any(target_os = "linux", target_os = "macos")))]
529fn install_service(_force: bool) -> Result<PathBuf> {
530    bail!("OS service installation is not yet supported on Windows; use Linux or macOS")
531}
532
533#[cfg(not(any(target_os = "linux", target_os = "macos")))]
534fn uninstall_service() -> Result<PathBuf> {
535    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
536}
537
538#[cfg(not(any(target_os = "linux", target_os = "macos")))]
539fn start_service() -> Result<()> {
540    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
541}
542
543#[cfg(not(any(target_os = "linux", target_os = "macos")))]
544fn restart_service() -> Result<()> {
545    bail!("OS service management is not yet supported on Windows; use Linux or macOS")
546}