hyprstream_service/service/spawner/mod.rs
1//! Process and service spawner abstraction.
2//!
3//! Provides unified interfaces for spawning:
4//! - Raw processes via `ProcessSpawner` (Standalone or Systemd backends)
5//! - RPC services via `ServiceSpawner` (Tokio, Thread, or Subprocess modes)
6//!
7//! # Architecture
8//!
9//! ```text
10//! ProcessSpawner (raw process management)
11//! ├── StandaloneBackend (tokio::process::Command)
12//! │ └── .kill_on_drop(false): adopted daemons outlive the launcher
13//! │
14//! └── SystemdBackend (systemd-run)
15//! └── Transient units in hyprstream-workers.slice
16//!
17//! ServiceSpawner (RequestService hosting)
18//! ├── Tokio mode (tokio::spawn)
19//! ├── Thread mode (std::thread + runtime)
20//! └── Subprocess mode (ProcessSpawner)
21//! ```
22//!
23//! # Usage
24//!
25//! ```ignore
26//! use hyprstream_rpc::service::spawner::{ProcessSpawner, ProcessConfig};
27//!
28//! // Auto-detect best backend (systemd if available)
29//! let spawner = ProcessSpawner::new();
30//!
31//! // Spawn a daemon
32//! let config = ProcessConfig::new("nydusd", "/usr/bin/nydusd")
33//! .args(["--config", "/etc/nydusd.json"])
34//! .working_dir("/var/run/hyprstream");
35//!
36//! let process = spawner.spawn(config).await?;
37//! println!("Spawned: {:?}", process.id());
38//!
39//! // Later, stop the daemon
40//! spawner.stop(&process).await?;
41//! ```
42
43mod process;
44mod service;
45mod standalone;
46mod systemd;
47
48pub use process::ProcessSpawner;
49pub use service::{
50 DualSpawnable, InprocManager, ServiceKind, ServiceMode, ServiceSpawner, Spawnable,
51 SpawnedService, UnifiedServiceConfig,
52};
53pub use standalone::StandaloneBackend;
54pub use systemd::SystemdBackend;
55
56use std::ffi::OsString;
57use std::path::PathBuf;
58
59use hyprstream_rpc::error::{Result, RpcError};
60
61/// Readiness policy for a spawned child process (#1585).
62///
63/// The policy gates when a spawn is reported as successful. It is a
64/// lifecycle gate, not application authentication.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum ProcessReadiness {
67 /// Report success as soon as the child is spawned (legacy behavior).
68 Immediate,
69 /// Wait for the child's own `READY=1` sd_notify datagram on a per-child
70 /// notification endpoint before reporting success. The sender PID must
71 /// match the spawned child; a child exit or the hard timeout fails the
72 /// spawn, and the child is terminated/reaped and its artifacts cleaned up.
73 ///
74 /// Platform support: the credential-authenticated receiver
75 /// (`SO_PASSCRED`/`SCM_CREDENTIALS`, exact child-PID matching) is
76 /// implemented for Linux/Android only. On other targets a Notify request
77 /// is refused with an explicit error BEFORE the child is spawned and
78 /// before any launch side effect; it is never silently downgraded to
79 /// [`ProcessReadiness::Immediate`], and no unauthenticated receiver
80 /// exists. This is a launcher lifecycle boundary: the Required
81 /// networking profile itself predates this readiness policy and is a
82 /// distinct concern.
83 Notify {
84 /// Hard bound on how long the child has to report readiness.
85 timeout: std::time::Duration,
86 },
87}
88
89/// Configuration for spawning a daemon process.
90#[derive(Debug, Clone)]
91pub struct ProcessConfig {
92 /// Human-readable name for the daemon (used in unit names).
93 pub name: String,
94
95 /// Path to the executable.
96 pub executable: PathBuf,
97
98 /// Command-line arguments.
99 pub args: Vec<OsString>,
100
101 /// Working directory.
102 pub working_dir: Option<PathBuf>,
103
104 /// Environment variables (key=value).
105 pub env: Vec<(String, String)>,
106
107 /// Memory limit (systemd only, e.g., "1G", "512M").
108 pub memory_limit: Option<String>,
109
110 /// CPU quota percentage (systemd only, e.g., 200 for 2 cores).
111 pub cpu_quota: Option<u32>,
112
113 /// Custom unit properties (systemd only).
114 pub unit_properties: Vec<(String, String)>,
115
116 /// Whether to restart on failure (systemd only).
117 pub restart_on_failure: bool,
118
119 /// When the spawn may be reported as started (#1585).
120 pub readiness: ProcessReadiness,
121}
122
123impl ProcessConfig {
124 /// Create a new process configuration.
125 pub fn new(name: impl Into<String>, executable: impl Into<PathBuf>) -> Self {
126 Self {
127 name: name.into(),
128 executable: executable.into(),
129 args: Vec::new(),
130 working_dir: None,
131 env: Vec::new(),
132 memory_limit: None,
133 cpu_quota: None,
134 unit_properties: Vec::new(),
135 restart_on_failure: false,
136 readiness: ProcessReadiness::Immediate,
137 }
138 }
139
140 /// Require the child's own `READY=1` notification within `timeout`
141 /// before the spawn reports success (#1585).
142 pub fn with_notify_ready(mut self, timeout: std::time::Duration) -> Self {
143 self.readiness = ProcessReadiness::Notify { timeout };
144 self
145 }
146
147 /// Set command-line arguments.
148 pub fn args<I, S>(mut self, args: I) -> Self
149 where
150 I: IntoIterator<Item = S>,
151 S: Into<OsString>,
152 {
153 self.args = args.into_iter().map(Into::into).collect();
154 self
155 }
156
157 /// Set working directory.
158 pub fn working_dir(mut self, dir: impl Into<PathBuf>) -> Self {
159 self.working_dir = Some(dir.into());
160 self
161 }
162
163 /// Add an environment variable.
164 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
165 self.env.push((key.into(), value.into()));
166 self
167 }
168
169 /// Set memory limit (e.g., "1G", "512M").
170 pub fn memory_limit(mut self, limit: impl Into<String>) -> Self {
171 self.memory_limit = Some(limit.into());
172 self
173 }
174
175 /// Set CPU quota percentage (e.g., 200 for 2 cores).
176 pub fn cpu_quota(mut self, quota: u32) -> Self {
177 self.cpu_quota = Some(quota);
178 self
179 }
180
181 /// Add a custom systemd unit property.
182 pub fn unit_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
183 self.unit_properties.push((key.into(), value.into()));
184 self
185 }
186
187 /// Enable restart on failure.
188 pub fn restart_on_failure(mut self) -> Self {
189 self.restart_on_failure = true;
190 self
191 }
192}
193
194/// Represents a spawned process.
195#[derive(Debug, Clone)]
196pub struct SpawnedProcess {
197 /// Unique identifier for the process.
198 pub id: String,
199
200 /// Process kind (direct or systemd).
201 pub kind: ProcessKind,
202
203 /// The PID file this spawn published, if any; `stop` removes it so a
204 /// stopped child leaves no stale artifact (#1585).
205 pub pid_file: Option<PathBuf>,
206}
207
208impl SpawnedProcess {
209 /// Create a new spawned process reference.
210 pub fn new(id: impl Into<String>, kind: ProcessKind) -> Self {
211 Self {
212 id: id.into(),
213 kind,
214 pid_file: None,
215 }
216 }
217
218 /// Attach the PID file this spawn published, for cleanup on stop (#1585).
219 pub fn with_pid_file(mut self, path: impl Into<PathBuf>) -> Self {
220 self.pid_file = Some(path.into());
221 self
222 }
223
224 /// Get the process ID.
225 pub fn id(&self) -> &str {
226 &self.id
227 }
228
229 /// Check if this is a direct process.
230 pub fn is_direct(&self) -> bool {
231 matches!(self.kind, ProcessKind::Direct(_))
232 }
233
234 /// Check if this is a systemd unit.
235 pub fn is_systemd(&self) -> bool {
236 matches!(self.kind, ProcessKind::SystemdUnit(_))
237 }
238
239 /// Get the PID if this is a direct process.
240 pub fn pid(&self) -> Option<u32> {
241 match &self.kind {
242 ProcessKind::Direct(pid) => Some(*pid),
243 ProcessKind::SystemdUnit(_) => None,
244 }
245 }
246
247 /// Get the unit name if this is a systemd unit.
248 pub fn unit_name(&self) -> Option<&str> {
249 match &self.kind {
250 ProcessKind::Direct(_) => None,
251 ProcessKind::SystemdUnit(name) => Some(name),
252 }
253 }
254}
255
256/// Type of spawned process.
257#[derive(Debug, Clone)]
258pub enum ProcessKind {
259 /// Direct process (tracked by PID).
260 Direct(u32),
261
262 /// Systemd transient unit (tracked by unit name).
263 SystemdUnit(String),
264}
265
266/// Backend type for process spawning.
267#[derive(Debug, Clone)]
268pub enum ProcessBackend {
269 /// Standalone process spawning via tokio::process::Command.
270 Standalone,
271
272 /// Systemd transient units via systemd-run.
273 Systemd {
274 /// Whether to use user mode (--user flag).
275 user_mode: bool,
276 },
277}
278
279/// Trait for process spawning backends.
280#[async_trait::async_trait]
281pub trait SpawnerBackend: Send + Sync {
282 /// Spawn a daemon process.
283 async fn spawn(&self, config: ProcessConfig) -> Result<SpawnedProcess>;
284
285 /// Stop a spawned process.
286 async fn stop(&self, process: &SpawnedProcess) -> Result<()>;
287
288 /// Check if a process is still running.
289 async fn is_running(&self, process: &SpawnedProcess) -> Result<bool>;
290
291 /// Synchronous bounded stop of a TRACKED direct child, used only by the
292 /// launch-transaction guard's `Drop` for cancellation cleanup where no
293 /// async runtime work is guaranteed (#1585). Backends that retain child
294 /// handles override this to stop through the retained handle — never a
295 /// blind by-PID signal; the default fails honestly.
296 fn stop_tracked_child_sync(&self, process: &SpawnedProcess) -> Result<()> {
297 let _ = process;
298 Err(RpcError::InvalidOperation(
299 "backend does not support synchronous tracked-child stop".to_owned(),
300 ))
301 }
302
303 /// Get the backend type name.
304 fn backend_type(&self) -> &'static str;
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 #[test]
312 fn test_process_config_builder() {
313 let config = ProcessConfig::new("test", "/usr/bin/test")
314 .args(["--foo", "bar"])
315 .working_dir("/tmp")
316 .env("KEY", "VALUE")
317 .memory_limit("1G")
318 .cpu_quota(200)
319 .restart_on_failure();
320
321 assert_eq!(config.name, "test");
322 assert_eq!(config.executable.to_str(), Some("/usr/bin/test"));
323 assert_eq!(config.args, vec!["--foo", "bar"]);
324 if let Some(ref wd) = config.working_dir {
325 assert_eq!(wd.to_str(), Some("/tmp"));
326 } else {
327 panic!("working_dir should be set");
328 }
329 assert_eq!(config.env, vec![("KEY".to_owned(), "VALUE".to_owned())]);
330 assert_eq!(config.memory_limit, Some("1G".to_owned()));
331 assert_eq!(config.cpu_quota, Some(200));
332 assert!(config.restart_on_failure);
333 }
334
335 #[test]
336 fn test_spawned_process() {
337 let direct = SpawnedProcess::new("test-1", ProcessKind::Direct(1234));
338 assert!(direct.is_direct());
339 assert!(!direct.is_systemd());
340 assert_eq!(direct.pid(), Some(1234));
341 assert_eq!(direct.unit_name(), None);
342
343 let systemd = SpawnedProcess::new(
344 "test-2",
345 ProcessKind::SystemdUnit("test.service".to_owned()),
346 );
347 assert!(!systemd.is_direct());
348 assert!(systemd.is_systemd());
349 assert_eq!(systemd.pid(), None);
350 assert_eq!(systemd.unit_name(), Some("test.service"));
351 }
352}