Skip to main content

krait/daemon/
mod.rs

1pub mod lifecycle;
2pub mod server;
3
4use std::path::Path;
5use std::time::Duration;
6
7use tracing::info;
8
9use crate::detect;
10
11/// Default idle timeout: 30 minutes
12const DEFAULT_IDLE_TIMEOUT_SECS: u64 = 30 * 60;
13
14/// Run the daemon for the given project root. Handles full lifecycle:
15/// PID file, socket server, cleanup on exit.
16///
17/// # Errors
18/// Returns an error if the daemon fails to start (PID conflict, socket bind failure).
19pub async fn run_daemon(project_root: &Path) -> anyhow::Result<()> {
20    let socket_path = detect::socket_path(project_root);
21    let pid_path = lifecycle::pid_path(&socket_path);
22
23    lifecycle::acquire_pid_file(&pid_path)?;
24    info!("daemon starting for {}", project_root.display());
25
26    let idle_timeout = Duration::from_secs(
27        std::env::var("KRAIT_IDLE_TIMEOUT")
28            .ok()
29            .and_then(|v| v.parse().ok())
30            .unwrap_or(DEFAULT_IDLE_TIMEOUT_SECS),
31    );
32
33    let result = server::run_server(&socket_path, idle_timeout, project_root).await;
34
35    lifecycle::cleanup(&socket_path, &pid_path);
36    info!("daemon stopped");
37
38    result
39}