Skip to main content

weirdnet_model/
store.rs

1//! Where model files live on disk, and which Hub they come from.
2
3use std::path::{Path, PathBuf};
4
5use crate::catalog::ModelSpec;
6
7/// The public Hugging Face Hub.
8pub const HUB: &str = "https://huggingface.co";
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct ModelStore {
12    dir: PathBuf,
13    hub: String,
14}
15
16impl ModelStore {
17    pub fn new(dir: impl Into<PathBuf>) -> Self {
18        Self { dir: dir.into(), hub: HUB.into() }
19    }
20
21    /// `$WEIRDNET_MODELS_DIR`, else `<user data dir>/weirdnet/models`; the Hub from
22    /// `$WEIRDNET_HF_URL` (a mirror) when set.
23    pub fn from_env() -> Self {
24        let dir = std::env::var_os("WEIRDNET_MODELS_DIR")
25            .filter(|d| !d.is_empty())
26            .map(PathBuf::from)
27            .unwrap_or_else(|| dirs::data_dir().unwrap_or_else(std::env::temp_dir).join("weirdnet").join("models"));
28        let mut store = Self::new(dir);
29        if let Some(hub) = std::env::var("WEIRDNET_HF_URL").ok().filter(|u| !u.trim().is_empty()) {
30            store.hub = hub.trim_end_matches('/').to_string();
31        }
32        store
33    }
34
35    /// Use another Hub (a mirror, or a local server in tests).
36    pub fn with_hub(mut self, hub: impl Into<String>) -> Self {
37        self.hub = hub.into().trim_end_matches('/').to_string();
38        self
39    }
40
41    pub fn dir(&self) -> &Path {
42        &self.dir
43    }
44
45    pub fn hub(&self) -> &str {
46        &self.hub
47    }
48
49    /// Where `spec`'s file goes.
50    pub fn path(&self, spec: &ModelSpec) -> PathBuf {
51        self.dir.join(&spec.file)
52    }
53
54    /// Downloaded and complete: the size matches (the checksum was checked when it finished).
55    pub fn installed(&self, spec: &ModelSpec) -> bool {
56        std::fs::metadata(self.path(spec)).is_ok_and(|m| m.len() == spec.size)
57    }
58
59    /// Bytes of a partial download, if any.
60    pub fn partial_bytes(&self, spec: &ModelSpec) -> u64 {
61        std::fs::metadata(self.part_path(spec)).map(|m| m.len()).unwrap_or(0)
62    }
63
64    pub(crate) fn part_path(&self, spec: &ModelSpec) -> PathBuf {
65        self.dir.join(format!("{}.part", spec.file))
66    }
67
68    /// Deletes the file and any partial download. Returns whether a file was removed.
69    pub fn remove(&self, spec: &ModelSpec) -> bool {
70        let _ = std::fs::remove_file(self.part_path(spec));
71        std::fs::remove_file(self.path(spec)).is_ok()
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use crate::catalog;
79
80    #[test]
81    fn paths_follow_the_file_name_and_remove_clears_parts() {
82        let tmp = tempfile::tempdir().unwrap();
83        let store = ModelStore::new(tmp.path());
84        let spec = catalog::default_for(catalog::Device::Phone);
85        assert_eq!(store.path(&spec), tmp.path().join("gemma-4-E2B-it-Q4_0.gguf"));
86        assert!(!store.installed(&spec));
87        std::fs::write(store.part_path(&spec), b"abc").unwrap();
88        assert_eq!(store.partial_bytes(&spec), 3);
89        assert!(!store.remove(&spec));
90        assert_eq!(store.partial_bytes(&spec), 0);
91    }
92
93    #[test]
94    fn a_mirror_loses_its_trailing_slash() {
95        assert_eq!(ModelStore::new("/x").with_hub("http://127.0.0.1:1/").hub(), "http://127.0.0.1:1");
96    }
97}