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