Skip to main content

hyprstream_service/service/spawner/
process.rs

1//! Unified process spawner with auto-detection.
2//!
3//! Provides a single API for spawning processes, automatically selecting
4//! the best backend (systemd if available, otherwise standalone).
5
6use std::sync::Arc;
7
8use super::{
9    ProcessBackend, ProcessConfig, SpawnedProcess, SpawnerBackend, StandaloneBackend,
10    SystemdBackend,
11};
12use hyprstream_rpc::error::Result;
13
14/// Unified process spawner.
15///
16/// Automatically detects the best backend (systemd if available, otherwise standalone)
17/// and provides a consistent API for spawning and managing processes.
18///
19/// # Example
20///
21/// ```ignore
22/// use hyprstream_rpc::service::spawner::{ProcessSpawner, ProcessConfig};
23///
24/// // Auto-detect best backend
25/// let spawner = ProcessSpawner::new();
26///
27/// // Spawn a daemon
28/// let config = ProcessConfig::new("nydusd", "/usr/bin/nydusd")
29///     .args(["--config", "/etc/nydusd.json"]);
30///
31/// let process = spawner.spawn(config).await?;
32/// println!("Spawned: {}", process.id());
33///
34/// // Later, stop it
35/// spawner.stop(&process).await?;
36/// ```
37pub struct ProcessSpawner {
38    /// The backend implementation.
39    backend: Arc<dyn SpawnerBackend>,
40
41    /// The backend type (for reporting).
42    backend_type: ProcessBackend,
43}
44
45impl ProcessSpawner {
46    /// Create a new process spawner with auto-detection.
47    ///
48    /// Uses systemd if available, otherwise falls back to standalone spawning.
49    pub fn new() -> Self {
50        if SystemdBackend::is_available() {
51            tracing::info!("Using systemd backend for process spawning");
52            Self {
53                backend: Arc::new(SystemdBackend::new()),
54                backend_type: ProcessBackend::Systemd {
55                    user_mode: !nix::unistd::geteuid().is_root(),
56                },
57            }
58        } else {
59            tracing::info!("Systemd not available, using standalone backend");
60            Self {
61                backend: Arc::new(StandaloneBackend::new()),
62                backend_type: ProcessBackend::Standalone,
63            }
64        }
65    }
66
67    /// Create a spawner with explicit backend selection.
68    ///
69    /// If systemd is requested but not available, falls back to standalone.
70    pub fn with_backend(backend: ProcessBackend) -> Self {
71        match backend {
72            ProcessBackend::Systemd { user_mode } => {
73                if SystemdBackend::is_available() {
74                    Self {
75                        backend: Arc::new(SystemdBackend::with_user_mode(user_mode)),
76                        backend_type: ProcessBackend::Systemd { user_mode },
77                    }
78                } else {
79                    tracing::warn!(
80                        "Systemd requested but not available, falling back to standalone"
81                    );
82                    Self {
83                        backend: Arc::new(StandaloneBackend::new()),
84                        backend_type: ProcessBackend::Standalone,
85                    }
86                }
87            }
88            ProcessBackend::Standalone => Self {
89                backend: Arc::new(StandaloneBackend::new()),
90                backend_type: ProcessBackend::Standalone,
91            },
92        }
93    }
94
95    /// Create a spawner that always uses standalone spawning.
96    pub fn standalone() -> Self {
97        Self {
98            backend: Arc::new(StandaloneBackend::new()),
99            backend_type: ProcessBackend::Standalone,
100        }
101    }
102
103    /// Create a spawner that uses systemd if available.
104    pub fn systemd() -> Self {
105        Self::with_backend(ProcessBackend::Systemd {
106            user_mode: !nix::unistd::geteuid().is_root(),
107        })
108    }
109
110    /// Get the backend type being used.
111    pub fn backend_type(&self) -> &ProcessBackend {
112        &self.backend_type
113    }
114
115    /// Check if systemd is available on this system.
116    pub fn is_systemd_available() -> bool {
117        SystemdBackend::is_available()
118    }
119
120    /// Spawn a daemon process.
121    ///
122    /// # Arguments
123    /// * `config` - Configuration for the daemon
124    ///
125    /// # Returns
126    /// A handle to the spawned process.
127    pub async fn spawn(&self, config: ProcessConfig) -> Result<SpawnedProcess> {
128        self.backend.spawn(config).await
129    }
130
131    /// Stop a spawned process.
132    ///
133    /// # Arguments
134    /// * `process` - The process to stop
135    pub async fn stop(&self, process: &SpawnedProcess) -> Result<()> {
136        self.backend.stop(process).await
137    }
138
139    /// Check if a process is still running.
140    ///
141    /// # Arguments
142    /// * `process` - The process to check
143    ///
144    /// # Returns
145    /// `true` if the process is still running.
146    pub async fn is_running(&self, process: &SpawnedProcess) -> Result<bool> {
147        self.backend.is_running(process).await
148    }
149
150    /// Synchronous bounded stop of a TRACKED direct child, used only by the
151    /// launch-transaction guard's `Drop` for cancellation cleanup where no
152    /// async runtime work is guaranteed (#1585). Delegates to the backend,
153    /// which stops through its retained child handle — never a blind by-PID
154    /// signal; unsupported backends fail honestly.
155    pub fn stop_tracked_child_sync(&self, process: &SpawnedProcess) -> Result<()> {
156        self.backend.stop_tracked_child_sync(process)
157    }
158}
159
160impl Default for ProcessSpawner {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166impl Clone for ProcessSpawner {
167    fn clone(&self) -> Self {
168        Self {
169            backend: Arc::clone(&self.backend),
170            backend_type: self.backend_type.clone(),
171        }
172    }
173}
174
175#[cfg(test)]
176#[allow(clippy::print_stdout, clippy::print_stderr)]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn test_auto_detection() {
182        let spawner = ProcessSpawner::new();
183        let backend_type = spawner.backend_type();
184
185        // Should be either Standalone or Systemd
186        match backend_type {
187            ProcessBackend::Standalone => println!("Using standalone backend"),
188            ProcessBackend::Systemd { user_mode } => {
189                println!("Using systemd backend (user_mode: {user_mode})");
190            }
191        }
192    }
193
194    #[test]
195    fn test_explicit_standalone() {
196        let spawner = ProcessSpawner::standalone();
197        assert!(matches!(spawner.backend_type(), ProcessBackend::Standalone));
198    }
199
200    #[tokio::test]
201    async fn test_spawn_and_stop() -> hyprstream_rpc::Result<()> {
202        let spawner = ProcessSpawner::new();
203
204        let config = ProcessConfig::new("test-sleep", "sleep").args(["100"]);
205
206        match spawner.spawn(config).await {
207            Ok(process) => {
208                // Check it's running
209                let running = spawner.is_running(&process).await?;
210                assert!(running, "Process should be running");
211
212                // Stop it
213                spawner.stop(&process).await?;
214
215                // Give it a moment
216                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
217
218                // Check it's stopped
219                let running = spawner.is_running(&process).await?;
220                assert!(!running, "Process should be stopped");
221            }
222            Err(e) => {
223                eprintln!("Could not spawn test process: {e}");
224            }
225        }
226        Ok(())
227    }
228}