Skip to main content

weirdnet_model/
download.rs

1//! Consent-gated download of one model file, or every part of a split model: resumes a `.part`,
2//! checks the size and the SHA-256, and only then renames it into place. Requests carry the
3//! store's Hugging Face token when it may go to the store's Hub (see [`ModelStore::from_env`]).
4
5use std::io::{Read, Write};
6use std::path::{Path, PathBuf};
7
8use sha2::{Digest, Sha256};
9
10use crate::catalog::{ModelSpec, human};
11use crate::store::ModelStore;
12use crate::{Error, Result};
13
14/// The user said yes to downloading this model. [`download`] needs one, so nothing downloads
15/// without an explicit OK. Create it only after showing [`ModelSpec::consent_text`].
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Consent {
18    id: String,
19}
20
21impl Consent {
22    pub fn given(spec: &ModelSpec) -> Self {
23        Self { id: spec.id.clone() }
24    }
25}
26
27/// How far a download is.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct Progress {
30    pub done: u64,
31    pub total: u64,
32}
33
34impl Progress {
35    /// 0.0 to 1.0.
36    pub fn fraction(&self) -> f32 {
37        if self.total == 0 { 0.0 } else { (self.done as f64 / self.total as f64).min(1.0) as f32 }
38    }
39}
40
41/// Downloads `spec` into `store`. `progress` returns `false` to cancel (the `.part` is kept so a
42/// later call resumes). Returns the file's path; an already complete, matching file is kept.
43pub fn download(store: &ModelStore, spec: &ModelSpec, consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
44    if consent.id != spec.id {
45        return Err(Error::Consent);
46    }
47    crate::hf::check_file(&spec.file)?;
48    let dest = store.path(spec);
49    let part = store.part_path(spec);
50    std::fs::create_dir_all(dest.parent().unwrap_or(store.dir()))?;
51    let total = spec.size;
52    if total > 0 && std::fs::metadata(&dest).is_ok_and(|m| m.len() == total) {
53        match &spec.sha256 {
54            Some(want) if !sha256_of(&dest)?.eq_ignore_ascii_case(want) => std::fs::remove_file(&dest)?,
55            _ => {
56                progress(Progress { done: total, total });
57                return Ok(dest);
58            }
59        }
60    }
61    let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
62    let mut done = have;
63    if have < total || total == 0 {
64        let mut req = store.hub_client().get(&spec.url(store.hub()));
65        if have > 0 && have < total {
66            req = req.header("Range", format!("bytes={have}-"));
67        }
68        let mut resp = req.call().map_err(|e| Error::Http(e.to_string()))?;
69        let status = resp.status().as_u16();
70        done = match status {
71            206 => have,
72            200 => 0,
73            s @ (401 | 403) if !store.has_token() => {
74                return Err(Error::Http(format!("the Hub answered {s}; {} may be gated or private (set HF_TOKEN on this node)", spec.repo)));
75            }
76            s => return Err(Error::Http(format!("the Hub answered {s}"))),
77        };
78        let mut file = std::fs::OpenOptions::new().create(true).write(true).append(done > 0).truncate(done == 0).open(&part)?;
79        let mut body = resp.body_mut().as_reader();
80        let mut buf = vec![0u8; 1 << 16];
81        loop {
82            if !progress(Progress { done, total }) {
83                return Err(Error::Cancelled { done: human(done), total: human(total) });
84            }
85            let n = body.read(&mut buf)?;
86            if n == 0 {
87                break;
88            }
89            file.write_all(&buf[..n])?;
90            done += n as u64;
91            if done > total {
92                break;
93            }
94        }
95        file.flush()?;
96    }
97    if done != total {
98        if done > total {
99            let _ = std::fs::remove_file(&part);
100        }
101        return Err(Error::Incomplete { done: human(done), total: human(total) });
102    }
103    if let Some(want) = &spec.sha256 {
104        let got = sha256_of(&part)?;
105        if !got.eq_ignore_ascii_case(want) {
106            let _ = std::fs::remove_file(&part);
107            return Err(Error::Checksum { name: spec.file.clone(), got });
108        }
109    }
110    std::fs::rename(&part, &dest)?;
111    progress(Progress { done, total });
112    Ok(dest)
113}
114
115/// Downloads every part of a split model (or the one file of a single one), in order, with one
116/// [`Consent`] for the model: all `parts` must share its id (as
117/// [`RepoModel::specs`](crate::hf::RepoModel::specs) makes them). Progress counts all parts
118/// together. Returns the first part's path, which llama.cpp loads the whole model from.
119pub fn download_parts(store: &ModelStore, parts: &[ModelSpec], consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
120    let first = parts.first().ok_or_else(|| Error::Model("no files to download".into()))?;
121    if parts.iter().any(|p| p.id != consent.id) {
122        return Err(Error::Consent);
123    }
124    let total: u64 = parts.iter().map(|p| p.size).sum();
125    let mut before = 0;
126    for p in parts {
127        download(store, p, consent, &mut |pr| progress(Progress { done: before + pr.done.min(p.size), total }))?;
128        before += p.size;
129    }
130    Ok(store.path(first))
131}
132
133/// Lower-case hex SHA-256 of a file.
134pub fn sha256_of(path: &Path) -> Result<String> {
135    let mut hasher = Sha256::new();
136    std::io::copy(&mut std::fs::File::open(path)?, &mut hasher)?;
137    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use crate::testing::MockHub;
144
145    fn body() -> Vec<u8> {
146        (0..2_000_000u32).map(|i| (i % 251) as u8).collect()
147    }
148
149    fn spec_for(body: &[u8]) -> ModelSpec {
150        let sum = Sha256::digest(body).iter().map(|b| format!("{b:02x}")).collect::<String>();
151        ModelSpec { id: "t".into(), label: "Test".into(), repo: "o/n".into(), file: "t.gguf".into(), size: body.len() as u64, sha256: Some(sum) }
152    }
153
154    #[test]
155    fn downloads_checks_and_renames() {
156        let b = body();
157        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
158        let tmp = tempfile::tempdir().unwrap();
159        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
160        let spec = spec_for(&b);
161        let mut last = 0.0;
162        let path = download(&store, &spec, &Consent::given(&spec), &mut |p| {
163            last = p.fraction();
164            true
165        })
166        .unwrap();
167        assert_eq!(std::fs::read(&path).unwrap(), b);
168        assert_eq!(last, 1.0);
169        assert!(store.installed(&spec));
170        assert_eq!(store.partial_bytes(&spec), 0);
171        // A second call keeps the verified file and makes no request.
172        let hits = hub.requests();
173        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
174        assert_eq!(hub.requests(), hits);
175    }
176
177    #[test]
178    fn a_cancelled_download_resumes_with_a_range_request() {
179        let b = body();
180        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
181        let tmp = tempfile::tempdir().unwrap();
182        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
183        let spec = spec_for(&b);
184        let mut calls = 0;
185        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| {
186            calls += 1;
187            calls < 2
188        })
189        .unwrap_err();
190        assert!(matches!(err, Error::Cancelled { .. }), "{err}");
191        let kept = store.partial_bytes(&spec);
192        assert!(kept > 0 && kept < b.len() as u64, "kept {kept}");
193        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
194        assert_eq!(std::fs::read(store.path(&spec)).unwrap(), b);
195        assert_eq!(hub.last_range(), Some(format!("bytes={kept}-")));
196    }
197
198    #[test]
199    fn a_wrong_checksum_deletes_the_part_and_names_the_file() {
200        let b = body();
201        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
202        let tmp = tempfile::tempdir().unwrap();
203        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
204        let mut spec = spec_for(&b);
205        spec.sha256 = Some("0".repeat(64));
206        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
207        assert!(matches!(err, Error::Checksum { ref name, .. } if name == "t.gguf"), "{err}");
208        assert_eq!(store.partial_bytes(&spec), 0);
209        assert!(!store.installed(&spec));
210    }
211
212    #[test]
213    fn consent_for_another_model_is_refused_and_http_errors_are_reported() {
214        let b = body();
215        let hub = MockHub::start("/o/n/resolve/main/other.gguf", b.clone());
216        let tmp = tempfile::tempdir().unwrap();
217        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
218        let spec = spec_for(&b);
219        let mut other = spec.clone();
220        other.id = "other".into();
221        assert!(matches!(download(&store, &spec, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
222        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
223        assert!(matches!(err, Error::Http(ref m) if m.contains("404")), "{err}");
224    }
225
226    #[test]
227    fn split_models_download_every_part_into_their_directory() {
228        let (a, b) = (body(), body()[..500_000].to_vec());
229        let hub = MockHub::start_with(vec![
230            ("/o/n/resolve/main/Q8_0/m-00001-of-00002.gguf".into(), "application/octet-stream", a.clone()),
231            ("/o/n/resolve/main/Q8_0/m-00002-of-00002.gguf".into(), "application/octet-stream", b.clone()),
232        ]);
233        let tmp = tempfile::tempdir().unwrap();
234        let store = ModelStore::new(tmp.path()).with_hub(hub.url()).with_token(crate::HfToken::new("hf_t"));
235        let mut parts = Vec::new();
236        for (name, data) in [("Q8_0/m-00001-of-00002.gguf", &a), ("Q8_0/m-00002-of-00002.gguf", &b)] {
237            let mut s = spec_for(data);
238            (s.id, s.file) = ("m".into(), name.into());
239            parts.push(s);
240        }
241        let mut seen = Vec::new();
242        let path = download_parts(&store, &parts, &Consent::given(&parts[0]), &mut |p| {
243            seen.push(p);
244            true
245        })
246        .unwrap();
247        assert_eq!(path, tmp.path().join("Q8_0/m-00001-of-00002.gguf"));
248        assert_eq!(std::fs::read(tmp.path().join("Q8_0/m-00002-of-00002.gguf")).unwrap(), b);
249        let total = (a.len() + b.len()) as u64;
250        assert!(seen.iter().all(|p| p.total == total));
251        assert!(seen.windows(2).all(|w| w[0].done <= w[1].done), "progress only goes up");
252        assert_eq!(seen.last().unwrap().done, total);
253        assert!(hub.seen().iter().all(|s| s.auth.as_deref() == Some("Bearer hf_t")));
254        let mut other = parts[0].clone();
255        other.id = "x".into();
256        assert!(matches!(download_parts(&store, &parts, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
257        let mut evil = parts[0].clone();
258        evil.file = "../evil.gguf".into();
259        assert!(download(&store, &evil, &Consent::given(&evil), &mut |_| true).is_err());
260    }
261
262    #[test]
263    fn a_short_body_is_incomplete_and_kept_for_resume() {
264        let b = body();
265        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b[..1000].to_vec());
266        let tmp = tempfile::tempdir().unwrap();
267        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
268        let spec = spec_for(&b);
269        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
270        assert!(matches!(err, Error::Incomplete { .. }), "{err}");
271        assert_eq!(store.partial_bytes(&spec), 1000);
272    }
273}