Skip to main content

hyprstream_service/service/manager/
standalone.rs

1//! Standalone service manager implementation
2//!
3//! Manages services by spawning processes via ProcessSpawner.
4//! Uses systemd-run when available, otherwise direct process spawning.
5
6use super::ServiceManager;
7use crate::service::spawner::{
8    ProcessConfig, ProcessSpawner, Spawnable, SpawnedProcess, SpawnedService,
9};
10use anyhow::Result;
11use async_trait::async_trait;
12use std::collections::HashMap;
13use tokio::sync::Mutex;
14use tracing::{debug, info};
15
16/// Resolve the executable path to use when spawning subprocess services.
17///
18/// Prefers `$APPIMAGE` (the stable AppImage file) over `current_exe()` (which
19/// returns the ephemeral `/tmp/.mount_hyprst*/usr/bin/hyprstream` path inside
20/// the AppImage mount). Systemd exec'ing the mount path directly bypasses
21/// `AppRun`, so libtorch and other bundled libraries are not found.
22fn spawnable_exe() -> Result<std::path::PathBuf> {
23    hyprstream_rpc::paths::executable_path().map_err(Into::into)
24}
25
26/// Standalone service manager
27///
28/// Spawns services via ProcessSpawner, which auto-detects systemd-run availability.
29/// Used when systemd socket activation is not available or not desired.
30pub struct StandaloneManager {
31    spawner: ProcessSpawner,
32    processes: Mutex<HashMap<String, SpawnedProcess>>,
33}
34
35impl StandaloneManager {
36    /// Create a new StandaloneManager
37    pub fn new() -> Self {
38        Self {
39            spawner: ProcessSpawner::new(),
40            processes: Mutex::new(HashMap::new()),
41        }
42    }
43
44    /// Create with explicit ProcessSpawner
45    pub fn with_spawner(spawner: ProcessSpawner) -> Self {
46        Self {
47            spawner,
48            processes: Mutex::new(HashMap::new()),
49        }
50    }
51}
52
53impl Default for StandaloneManager {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59#[async_trait]
60impl ServiceManager for StandaloneManager {
61    async fn install(&self, _service: &str) -> Result<()> {
62        // No persistent units for standalone mode
63        Ok(())
64    }
65
66    async fn start(&self, service: &str) -> Result<()> {
67        let exe = spawnable_exe()?;
68
69        let config =
70            ProcessConfig::new(service, exe).args(["service", "start", service, "--foreground"]);
71
72        let process = self.spawner.spawn(config).await?;
73
74        info!(
75            "Started service {} (id: {}, backend: {})",
76            service,
77            process.id(),
78            self.spawner.backend_type().backend_name()
79        );
80
81        self.processes
82            .lock()
83            .await
84            .insert(service.to_owned(), process);
85
86        Ok(())
87    }
88
89    async fn stop(&self, service: &str) -> Result<()> {
90        if let Some(process) = self.processes.lock().await.remove(service) {
91            self.spawner.stop(&process).await?;
92            info!("Stopped service {} (id: {})", service, process.id());
93        } else {
94            debug!("Service {} not running", service);
95        }
96        Ok(())
97    }
98
99    async fn is_active(&self, service: &str) -> Result<bool> {
100        let processes = self.processes.lock().await;
101        if let Some(process) = processes.get(service) {
102            Ok(self.spawner.is_running(process).await?)
103        } else {
104            Ok(false)
105        }
106    }
107
108    async fn reload(&self) -> Result<()> {
109        // No-op for standalone mode
110        Ok(())
111    }
112
113    async fn uninstall(&self, service: &str) -> Result<()> {
114        self.stop(service).await
115    }
116
117    async fn spawn(&self, service: Box<dyn Spawnable>) -> Result<SpawnedService> {
118        // For standalone mode, spawn as subprocess
119        let exe = spawnable_exe()?;
120
121        let config = ProcessConfig::new(service.name(), exe).args([
122            "service",
123            "start",
124            service.name(),
125            "--foreground",
126        ]);
127
128        let process = self.spawner.spawn(config).await?;
129
130        info!(
131            "Spawned service {} (id: {}, backend: {})",
132            service.name(),
133            process.id(),
134            self.spawner.backend_type().backend_name()
135        );
136
137        self.processes
138            .lock()
139            .await
140            .insert(service.name().to_owned(), process.clone());
141
142        Ok(SpawnedService::subprocess(
143            process.id.clone(),
144            process,
145            hyprstream_rpc::paths::service_pid_file(service.name()),
146        ))
147    }
148}
149
150/// Extension trait for ProcessBackend to get display name
151trait ProcessBackendExt {
152    fn backend_name(&self) -> &'static str;
153}
154
155impl ProcessBackendExt for crate::service::spawner::ProcessBackend {
156    fn backend_name(&self) -> &'static str {
157        match self {
158            Self::Standalone => "standalone",
159            Self::Systemd { .. } => "systemd-run",
160        }
161    }
162}