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 serde::{Deserialize, Serialize};
6
7use crate::catalog::ModelSpec;
8use crate::hf::{Hub, split_part};
9use crate::token::HfToken;
10
11/// The public Hugging Face Hub.
12pub const HUB: &str = "https://huggingface.co";
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ModelStore {
16    dir: PathBuf,
17    hub: String,
18    token: Option<HfToken>,
19    /// The token goes to any hub, not only the public one (set by [`ModelStore::with_token`]).
20    token_any_hub: bool,
21}
22
23/// A model file (or split model) in the store, from [`ModelStore::list`].
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[non_exhaustive]
26pub struct StoredModel {
27    /// The file stem without the split suffix, as in [`RepoModel::id`](crate::hf::RepoModel::id).
28    pub id: String,
29    /// Paths relative to the store directory, first part first.
30    pub files: Vec<String>,
31    pub size: u64,
32    /// Every part of a split model is there.
33    pub complete: bool,
34}
35
36impl ModelStore {
37    pub fn new(dir: impl Into<PathBuf>) -> Self {
38        Self { dir: dir.into(), hub: HUB.into(), token: None, token_any_hub: false }
39    }
40
41    /// `$WEIRDNET_MODELS_DIR`, else `<user data dir>/weirdnet/models`; the Hub from
42    /// `$WEIRDNET_HF_URL` (a mirror) when set; this node's Hugging Face token
43    /// ([`HfToken::from_env`]), which is sent only to the public Hub, never to a mirror.
44    pub fn from_env() -> Self {
45        let dir = std::env::var_os("WEIRDNET_MODELS_DIR")
46            .filter(|d| !d.is_empty())
47            .map(PathBuf::from)
48            .unwrap_or_else(|| dirs::data_dir().unwrap_or_else(std::env::temp_dir).join("weirdnet").join("models"));
49        let mut store = Self::new(dir);
50        if let Some(hub) = std::env::var("WEIRDNET_HF_URL").ok().filter(|u| !u.trim().is_empty()) {
51            store.hub = hub.trim_end_matches('/').to_string();
52        }
53        store.token = HfToken::from_env();
54        store
55    }
56
57    /// Sends `token` to this store's Hub, whichever it is (a mirror too).
58    pub fn with_token(mut self, token: Option<HfToken>) -> Self {
59        self.token = token;
60        self.token_any_hub = true;
61        self
62    }
63
64    /// The token requests to this store's Hub carry, if any.
65    pub(crate) fn token(&self) -> Option<&HfToken> {
66        self.token.as_ref().filter(|_| self.token_any_hub || self.hub == HUB)
67    }
68
69    /// Whether requests to the Hub carry a token.
70    pub fn has_token(&self) -> bool {
71        self.token().is_some()
72    }
73
74    /// A [`Hub`] client for this store's Hub, with the token when it may go there.
75    pub fn hub_client(&self) -> Hub {
76        Hub::new(&self.hub).with_token(self.token().cloned())
77    }
78
79    /// Use another Hub (a mirror, or a local server in tests).
80    pub fn with_hub(mut self, hub: impl Into<String>) -> Self {
81        self.hub = hub.into().trim_end_matches('/').to_string();
82        self
83    }
84
85    pub fn dir(&self) -> &Path {
86        &self.dir
87    }
88
89    pub fn hub(&self) -> &str {
90        &self.hub
91    }
92
93    /// Where `spec`'s file goes.
94    pub fn path(&self, spec: &ModelSpec) -> PathBuf {
95        self.dir.join(&spec.file)
96    }
97
98    /// Downloaded and complete: the size matches (the checksum was checked when it finished).
99    pub fn installed(&self, spec: &ModelSpec) -> bool {
100        std::fs::metadata(self.path(spec)).is_ok_and(|m| m.len() == spec.size)
101    }
102
103    /// Bytes of a partial download, if any.
104    pub fn partial_bytes(&self, spec: &ModelSpec) -> u64 {
105        std::fs::metadata(self.part_path(spec)).map(|m| m.len()).unwrap_or(0)
106    }
107
108    pub(crate) fn part_path(&self, spec: &ModelSpec) -> PathBuf {
109        self.dir.join(format!("{}.part", spec.file))
110    }
111
112    /// Deletes the file and any partial download. Returns whether a file was removed.
113    pub fn remove(&self, spec: &ModelSpec) -> bool {
114        let _ = std::fs::remove_file(self.part_path(spec));
115        std::fs::remove_file(self.path(spec)).is_ok()
116    }
117
118    /// The GGUF models in the store (split parts grouped; projector, draft and `.part` files
119    /// left out), sorted by id.
120    pub fn list(&self) -> Vec<StoredModel> {
121        let mut files = Vec::new();
122        walk(&self.dir, &self.dir, 0, &mut files);
123        let mut out: std::collections::BTreeMap<String, (Vec<Part>, u32)> = Default::default();
124        for (rel, size) in files {
125            let (key, part, of) = match split_part(&rel) {
126                Some((base, part, of)) => {
127                    let dir = rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
128                    (format!("{dir}{base}"), part, of)
129                }
130                None => (rel.strip_suffix(".gguf").or_else(|| rel.strip_suffix(".GGUF")).unwrap_or(&rel).to_string(), 1, 1),
131            };
132            let e = out.entry(key).or_default();
133            e.0.push((part, rel, size));
134            e.1 = of;
135        }
136        let mut models: Vec<StoredModel> = out
137            .into_iter()
138            .map(|(key, (mut parts, of))| {
139                parts.sort();
140                let complete = parts.len() as u32 == of && parts[0].0 == 1;
141                StoredModel {
142                    id: key.rsplit('/').next().unwrap_or(&key).to_string(),
143                    size: parts.iter().map(|p| p.2).sum(),
144                    files: parts.into_iter().map(|p| p.1).collect(),
145                    complete,
146                }
147            })
148            .collect();
149        models.sort_by(|a, b| a.id.cmp(&b.id).then_with(|| a.files.cmp(&b.files)));
150        models
151    }
152
153    /// Deletes a listed model's files (and their `.part` files) and the directories that leaves
154    /// empty. Returns the bytes freed. Paths outside the store are refused.
155    pub fn remove_local(&self, model: &StoredModel) -> crate::Result<u64> {
156        let mut freed = 0;
157        for rel in &model.files {
158            crate::hf::check_file(rel)?;
159            let path = self.dir.join(rel);
160            let _ = std::fs::remove_file(self.dir.join(format!("{rel}.part")));
161            if let Ok(m) = std::fs::metadata(&path) {
162                std::fs::remove_file(&path)?;
163                freed += m.len();
164            }
165            let mut dir = path.parent().map(Path::to_path_buf);
166            while let Some(d) = dir.filter(|d| d.starts_with(&self.dir) && *d != self.dir) {
167                if std::fs::remove_dir(&d).is_err() {
168                    break;
169                }
170                dir = d.parent().map(Path::to_path_buf);
171            }
172        }
173        Ok(freed)
174    }
175}
176
177/// A file of a stored model: part number, path relative to the store, size.
178type Part = (u32, String, u64);
179
180/// Model GGUFs under `dir`, as `/`-separated paths relative to `root` (four levels deep at most).
181fn walk(root: &Path, dir: &Path, depth: usize, out: &mut Vec<(String, u64)>) {
182    let Ok(entries) = std::fs::read_dir(dir) else { return };
183    for e in entries.flatten() {
184        let Ok(ft) = e.file_type() else { continue };
185        let path = e.path();
186        if ft.is_dir() && depth < 4 {
187            walk(root, &path, depth + 1, out);
188        } else if ft.is_file() {
189            let name = e.file_name().to_string_lossy().to_ascii_lowercase();
190            if !name.ends_with(".gguf") || name.starts_with("mmproj") || name.starts_with("mtp-") {
191                continue;
192            }
193            let Ok(rel) = path.strip_prefix(root) else { continue };
194            let rel: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
195            out.push((rel.join("/"), e.metadata().map(|m| m.len()).unwrap_or(0)));
196        }
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::catalog;
204
205    #[test]
206    fn paths_follow_the_file_name_and_remove_clears_parts() {
207        let tmp = tempfile::tempdir().unwrap();
208        let store = ModelStore::new(tmp.path());
209        let spec = catalog::default_for(catalog::Device::Phone);
210        assert_eq!(store.path(&spec), tmp.path().join("gemma-4-E2B-it-Q4_0.gguf"));
211        assert!(!store.installed(&spec));
212        std::fs::write(store.part_path(&spec), b"abc").unwrap();
213        assert_eq!(store.partial_bytes(&spec), 3);
214        assert!(!store.remove(&spec));
215        assert_eq!(store.partial_bytes(&spec), 0);
216    }
217
218    #[test]
219    fn lists_and_removes_models_with_their_parts() {
220        let tmp = tempfile::tempdir().unwrap();
221        let store = ModelStore::new(tmp.path());
222        let w = |rel: &str, n: usize| {
223            let p = tmp.path().join(rel);
224            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
225            std::fs::write(p, vec![0u8; n]).unwrap();
226        };
227        w("a-Q4_0.gguf", 3);
228        w("mmproj-a.gguf", 1);
229        w("b.gguf.part", 1);
230        w("Q8_0/b-Q8_0-00001-of-00002.gguf", 5);
231        w("Q8_0/b-Q8_0-00002-of-00002.gguf", 6);
232        w("c-00002-of-00002.gguf", 2);
233        let list = store.list();
234        assert_eq!(
235            list.iter().map(|m| (m.id.as_str(), m.size, m.complete)).collect::<Vec<_>>(),
236            [("a-Q4_0", 3, true), ("b-Q8_0", 11, true), ("c", 2, false)]
237        );
238        assert_eq!(list[1].files, ["Q8_0/b-Q8_0-00001-of-00002.gguf", "Q8_0/b-Q8_0-00002-of-00002.gguf"]);
239        w("Q8_0/b-Q8_0-00002-of-00002.gguf.part", 1);
240        assert_eq!(store.remove_local(&list[1]).unwrap(), 11);
241        assert!(!tmp.path().join("Q8_0").exists(), "the emptied directory goes too");
242        assert_eq!(store.list().len(), 2);
243        let mut evil = list[0].clone();
244        evil.files = vec!["../x.gguf".into()];
245        assert!(store.remove_local(&evil).is_err());
246    }
247
248    #[test]
249    fn tokens_go_to_the_public_hub_or_where_they_were_set() {
250        let t = HfToken::new("hf_x");
251        let mut store = ModelStore::new("/x");
252        store.token = t.clone();
253        assert!(store.has_token() && store.hub_client().has_token());
254        let mirror = store.clone().with_hub("http://mirror");
255        assert!(!mirror.has_token(), "an environment token never goes to a mirror");
256        assert!(mirror.with_token(t).has_token());
257        assert!(format!("{store:?}").contains("<redacted>"));
258    }
259
260    #[test]
261    fn a_mirror_loses_its_trailing_slash() {
262        assert_eq!(ModelStore::new("/x").with_hub("http://127.0.0.1:1/").hub(), "http://127.0.0.1:1");
263    }
264}