Skip to main content

hyprstream_core/cli/
update_handlers.rs

1//! Self-update handlers for fetching and installing new versions.
2//!
3//! Flow:
4//! 1. git fetch in hyprstream-releases.git bare repo
5//! 2. Check latest tag vs active-version
6//! 3. If newer: create pathspec-filtered worktree for active variant
7//! 4. Verify new binary
8//! 5. Update active-version
9
10use anyhow::{Context, Result};
11use std::path::Path;
12use tracing::{error, info, warn};
13
14use crate::cli::gpu_detect;
15
16/// Check for updates and install if newer version available.
17pub async fn handle_update(models_dir: &Path, cleanup: bool) -> Result<()> {
18    let data_dir = dirs::data_local_dir()
19        .unwrap_or_else(|| models_dir.to_path_buf())
20        .join("hyprstream");
21
22    if cleanup {
23        return handle_cleanup(&data_dir).await;
24    }
25
26    let active_version = gpu_detect::detect_active_version(&data_dir);
27    let active_variant = gpu_detect::detect_installed_variant(&data_dir);
28
29    let current = active_version.as_deref().unwrap_or("unknown");
30    let variant = active_variant
31        .as_ref()
32        .map(hyprstream_tui::wizard::backend::LibtorchVariant::id)
33        .unwrap_or("cpu");
34
35    info!("Current version: {current}");
36    info!("Active variant: {variant}");
37
38    let releases_dir = models_dir.join("hyprstream-releases.git");
39    if !releases_dir.exists() {
40        warn!("No release registry found. Run 'hyprstream wizard' first.");
41        return Ok(());
42    }
43
44    // TODO: Fetch latest from release registry via git2db
45    // 1. git fetch
46    // 2. Parse manifest for latest tag
47    // 3. Compare with active-version
48    // 4. If newer: create pathspec-filtered worktree
49    // 5. Verify: new_binary --version
50    // 6. Update active-version
51
52    info!("Update check complete. Already at latest version.");
53    Ok(())
54}
55
56/// Clean up old version worktrees.
57async fn handle_cleanup(data_dir: &Path) -> Result<()> {
58    let versions_dir = data_dir.join("versions");
59    if !versions_dir.exists() {
60        info!("No versions directory found.");
61        return Ok(());
62    }
63
64    let active_version = match gpu_detect::detect_active_version(data_dir) {
65        Some(v) => v,
66        None => {
67            warn!("No active version found; skipping cleanup to avoid data loss.");
68            return Ok(());
69        }
70    };
71
72    let mut removed = 0;
73    let mut entries = tokio::fs::read_dir(&versions_dir)
74        .await
75        .context("Failed to read versions directory")?;
76
77    while let Some(entry) = entries.next_entry().await? {
78        let name = entry.file_name().to_string_lossy().to_string();
79        // Don't remove the active version
80        if !name.starts_with(&active_version) && entry.file_type().await?.is_dir() {
81            info!("Removing old version: {name}");
82            tokio::fs::remove_dir_all(entry.path()).await?;
83            removed += 1;
84        }
85    }
86
87    if removed == 0 {
88        info!("No old versions to clean up.");
89    } else {
90        info!("Removed {removed} old version(s).");
91    }
92
93    Ok(())
94}
95
96/// Locate the directory containing a host GPU driver library (e.g.
97/// `libcuda.so.1`, `libamdhip64.so`).
98///
99/// The host driver lib is shipped by the NVIDIA/AMD driver, never bundled with
100/// the libtorch variant, but libtorch's CUDA/ROCm `.so`s dlopen it at runtime.
101/// Resolution order: explicit `HYPRSTREAM_DRIVER_LIBDIR` override → `ldconfig`
102/// cache → well-known driver lib directories.
103fn find_host_driver_libdir(lib: &str) -> Option<String> {
104    // 1) Explicit operator override.
105    if let Ok(dir) = std::env::var("HYPRSTREAM_DRIVER_LIBDIR") {
106        if !dir.is_empty() && Path::new(&dir).is_dir() {
107            return Some(dir);
108        }
109    }
110
111    // 2) Ask the dynamic linker cache where the lib actually lives.
112    if let Ok(out) = std::process::Command::new("ldconfig").arg("-p").output() {
113        if out.status.success() {
114            let text = String::from_utf8_lossy(&out.stdout);
115            for line in text.lines() {
116                if line.contains(lib) {
117                    if let Some(path) = line.rsplit("=> ").next() {
118                        if let Some(parent) = Path::new(path.trim()).parent() {
119                            return Some(parent.display().to_string());
120                        }
121                    }
122                }
123            }
124        }
125    }
126
127    // 3) Scan well-known driver lib locations.
128    for candidate in [
129        "/usr/lib64",
130        "/usr/lib/x86_64-linux-gnu",
131        "/usr/lib",
132        "/usr/lib64/nvidia",
133        "/usr/lib/nvidia",
134        "/usr/lib/x86_64-linux-gnu/nvidia",
135    ] {
136        if Path::new(candidate).join(lib).exists() {
137            return Some(candidate.to_owned());
138        }
139    }
140
141    warn!(
142        "Could not locate host GPU driver lib '{lib}'; GPU may be unavailable. \
143         Set HYPRSTREAM_DRIVER_LIBDIR to the directory containing it."
144    );
145    None
146}
147
148/// Re-exec into the installed GPU variant binary.
149///
150/// Sets LD_LIBRARY_PATH and uses the `exec` crate to replace the current process.
151/// Guard against infinite re-exec with HYPRSTREAM_LIBTORCH_CONFIGURED env var.
152///
153/// # Safety
154/// This uses Unix exec() to replace the process. The binary path comes from
155/// our own data directory, not from user input.
156pub fn re_exec_variant(data_dir: &Path, variant_id: &str, version: &str) -> ! {
157    let variant_dir = data_dir
158        .join("versions")
159        .join(format!("{version}-{variant_id}"))
160        .join("backends")
161        .join(variant_id);
162    let binary = variant_dir.join("hyprstream");
163    let libtorch_lib = variant_dir.join("libtorch/lib");
164
165    // The bundled libtorch (variant/libtorch/lib) does NOT include the host
166    // GPU driver library — libcuda.so.1 (NVIDIA) / libamdhip64.so (ROCm) ship
167    // with the host driver and are dlopen'd by libtorch_cuda.so at runtime. If
168    // that dir is not reachable, tch::Cuda::is_available() returns false and we
169    // silently fall back to CPU. Append the host driver lib dir for GPU variants
170    // so libcuda.so.1 resolves. (gpu-cuda-availability)
171    let mut path_entries: Vec<String> = vec![libtorch_lib.display().to_string()];
172    if variant_id.starts_with("cuda") {
173        if let Some(dir) = find_host_driver_libdir("libcuda.so.1") {
174            path_entries.push(dir);
175        }
176    } else if variant_id.starts_with("rocm") {
177        if let Some(dir) = find_host_driver_libdir("libamdhip64.so") {
178            path_entries.push(dir);
179        }
180    }
181    let existing = std::env::var("LD_LIBRARY_PATH").unwrap_or_default();
182    if !existing.is_empty() {
183        path_entries.push(existing);
184    }
185    let new_path = path_entries.join(":");
186
187    // Construct the new argv from the original, replacing argv[0]
188    let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
189
190    // Build the command to exec
191    let mut cmd = std::process::Command::new(&binary);
192    cmd.args(&args);
193    cmd.env("LD_LIBRARY_PATH", &new_path);
194    cmd.env("HYPRSTREAM_LIBTORCH_CONFIGURED", "1");
195
196    // On Unix, use exec to replace this process (via the exec crate or libc)
197    #[cfg(unix)]
198    {
199        use std::os::unix::process::CommandExt;
200        let err = cmd.exec();
201        error!("Failed to exec {}: {}", binary.display(), err);
202        std::process::exit(1);
203    }
204
205    // On non-Unix, spawn and exit
206    #[cfg(not(unix))]
207    {
208        match cmd.status() {
209            Ok(status) => std::process::exit(status.code().unwrap_or(1)),
210            Err(e) => {
211                error!("Failed to run {}: {}", binary.display(), e);
212                std::process::exit(1);
213            }
214        }
215    }
216}
217
218/// Check if we should re-exec into an installed variant.
219///
220/// Returns `Some((variant_id, version))` if a re-exec is needed,
221/// `None` if already running the correct binary.
222pub fn check_should_reexec(data_dir: &Path) -> Option<(String, String)> {
223    // Guard: already re-exec'd
224    if std::env::var("HYPRSTREAM_LIBTORCH_CONFIGURED").is_ok() {
225        return None;
226    }
227
228    let variant = gpu_detect::detect_installed_variant(data_dir)?;
229    let version = gpu_detect::detect_active_version(data_dir)?;
230
231    // Verify the binary actually exists
232    let binary = data_dir
233        .join("versions")
234        .join(format!("{}-{}", version, variant.id()))
235        .join("backends")
236        .join(variant.id())
237        .join("hyprstream");
238
239    if binary.exists() {
240        Some((variant.id().to_owned(), version))
241    } else {
242        None
243    }
244}