Skip to main content

hyprstream_core/storage/
paths.rs

1//! Storage path management using XDG Base Directory specification
2//!
3//! This module provides standardized paths for storing models, LoRAs, and other data
4//! following the XDG Base Directory specification.
5
6use anyhow::{anyhow, Result};
7use std::path::{Path, PathBuf};
8use xdg::BaseDirectories;
9
10/// Application name for XDG directories
11const APP_NAME: &str = "hyprstream";
12
13/// Storage manager for organizing models, LoRAs, and other data
14pub struct StoragePaths {
15    base_dirs: BaseDirectories,
16}
17
18impl StoragePaths {
19    /// Create a new storage paths manager.
20    ///
21    /// Respects `HYPRSTREAM_INSTANCE`: when set, uses
22    /// `hyprstream/instances/{value}` as the XDG prefix so that credentials,
23    /// registry state, and models are isolated between concurrent instances on
24    /// the same host (mirrors the socket-path isolation in hyprstream-rpc/paths.rs).
25    pub fn new() -> Result<Self> {
26        let prefix = match std::env::var("HYPRSTREAM_INSTANCE") {
27            Ok(inst) if !inst.is_empty() => {
28                if inst.contains('/') || inst.contains("..") {
29                    return Err(anyhow!(
30                        "HYPRSTREAM_INSTANCE must not contain '/' or '..': {:?}",
31                        inst
32                    ));
33                }
34                format!("{APP_NAME}/instances/{inst}")
35            }
36            _ => APP_NAME.to_owned(),
37        };
38        let base_dirs = BaseDirectories::with_prefix(&prefix)
39            .map_err(|e| anyhow!("Failed to create XDG base directories: {}", e))?;
40
41        Ok(Self { base_dirs })
42    }
43
44    /// Get the models directory path
45    pub fn models_dir(&self) -> Result<PathBuf> {
46        let models_dir = self.base_dirs.get_data_home().join("models");
47        self.ensure_dir_exists(&models_dir)?;
48        Ok(models_dir)
49    }
50
51    /// Get the LoRAs directory path
52    pub fn loras_dir(&self) -> Result<PathBuf> {
53        let loras_dir = self.base_dirs.get_data_home().join("loras");
54        self.ensure_dir_exists(&loras_dir)?;
55        Ok(loras_dir)
56    }
57
58    /// Get the cache directory path
59    pub fn cache_dir(&self) -> Result<PathBuf> {
60        let cache_dir = self.base_dirs.get_cache_home();
61        self.ensure_dir_exists(&cache_dir)?;
62        Ok(cache_dir)
63    }
64
65    /// Get the config directory path
66    pub fn config_dir(&self) -> Result<PathBuf> {
67        let config_dir = self.base_dirs.get_config_home();
68        self.ensure_dir_exists(&config_dir)?;
69        Ok(config_dir)
70    }
71
72    /// Get the state directory path (XDG state home, instance-namespaced).
73    ///
74    /// Used for runtime-mutated state (e.g. JWT rotation slots, #803) that
75    /// must stay writable even when the config/credentials dir is a read-only
76    /// systemd credentials ramfs.
77    pub fn state_dir(&self) -> Result<PathBuf> {
78        let state_dir = self.base_dirs.get_state_home();
79        self.ensure_dir_exists(&state_dir)?;
80        Ok(state_dir)
81    }
82
83    /// Get the temporary download directory
84    pub fn temp_download_dir(&self) -> Result<PathBuf> {
85        let temp_dir = self.cache_dir()?.join("downloads");
86        self.ensure_dir_exists(&temp_dir)?;
87        Ok(temp_dir)
88    }
89
90    /// List all models in the models directory
91    pub fn list_local_models(&self) -> Result<Vec<String>> {
92        let models_dir = self.models_dir()?;
93        let mut models = Vec::new();
94
95        if models_dir.exists() {
96            for entry in std::fs::read_dir(&models_dir)? {
97                let entry = entry?;
98                if entry.file_type()?.is_file() {
99                    if let Some(name) = entry.file_name().to_str() {
100                        models.push(name.to_owned());
101                    }
102                }
103            }
104        }
105
106        models.sort();
107        Ok(models)
108    }
109
110    /// List all LoRAs in the LoRAs directory
111    pub fn list_local_loras(&self) -> Result<Vec<String>> {
112        let loras_dir = self.loras_dir()?;
113        let mut loras = Vec::new();
114
115        if loras_dir.exists() {
116            for entry in std::fs::read_dir(&loras_dir)? {
117                let entry = entry?;
118                if entry.file_type()?.is_file() {
119                    if let Some(name) = entry.file_name().to_str() {
120                        loras.push(name.to_owned());
121                    }
122                }
123            }
124        }
125
126        loras.sort();
127        Ok(loras)
128    }
129
130    /// Resolve worktree host path for a model+branch (CLI-only, not exposed via RPC)
131    pub fn worktree_path(&self, model_name: &str, branch: &str) -> Result<PathBuf> {
132        Ok(self
133            .models_dir()?
134            .join(model_name)
135            .join("worktrees")
136            .join(branch))
137    }
138
139    /// Ensure a directory exists, creating it if necessary
140    fn ensure_dir_exists(&self, path: &Path) -> Result<()> {
141        if !path.exists() {
142            std::fs::create_dir_all(path)
143                .map_err(|e| anyhow!("Failed to create directory {}: {}", path.display(), e))?;
144        }
145        Ok(())
146    }
147}
148
149#[cfg(test)]
150#[allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stdout)]
151mod tests {
152    use super::*;
153
154    #[tokio::test]
155    async fn test_storage_paths() {
156        let storage = StoragePaths::new().expect("test: create storage paths");
157
158        // Test directory creation
159        let models_dir = storage.models_dir().expect("test: get models dir");
160        let loras_dir = storage.loras_dir().expect("test: get loras dir");
161
162        assert!(models_dir.exists());
163        assert!(loras_dir.exists());
164        assert!(models_dir != loras_dir);
165    }
166}