weirdnet_model/
download.rs1use std::io::{Read, Write};
5use std::path::{Path, PathBuf};
6
7use sha2::{Digest, Sha256};
8
9use crate::catalog::{ModelSpec, human};
10use crate::store::ModelStore;
11use crate::{Error, Result};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Consent {
17 id: String,
18}
19
20impl Consent {
21 pub fn given(spec: &ModelSpec) -> Self {
22 Self { id: spec.id.clone() }
23 }
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Progress {
29 pub done: u64,
30 pub total: u64,
31}
32
33impl Progress {
34 pub fn fraction(&self) -> f32 {
36 if self.total == 0 { 0.0 } else { (self.done as f64 / self.total as f64).min(1.0) as f32 }
37 }
38}
39
40pub fn download(store: &ModelStore, spec: &ModelSpec, consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
43 if consent.id != spec.id {
44 return Err(Error::Consent);
45 }
46 let dest = store.path(spec);
47 let part = store.part_path(spec);
48 std::fs::create_dir_all(store.dir())?;
49 let total = spec.size;
50 if total > 0 && std::fs::metadata(&dest).is_ok_and(|m| m.len() == total) {
51 match &spec.sha256 {
52 Some(want) if !sha256_of(&dest)?.eq_ignore_ascii_case(want) => std::fs::remove_file(&dest)?,
53 _ => {
54 progress(Progress { done: total, total });
55 return Ok(dest);
56 }
57 }
58 }
59 let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
60 let mut done = have;
61 if have < total || total == 0 {
62 let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
63 let mut req = agent.get(spec.url(store.hub()));
64 if have > 0 && have < total {
65 req = req.header("Range", format!("bytes={have}-"));
66 }
67 let mut resp = req.call().map_err(|e| Error::Http(e.to_string()))?;
68 let status = resp.status().as_u16();
69 done = match status {
70 206 => have,
71 200 => 0,
72 s => return Err(Error::Http(format!("the Hub answered {s}"))),
73 };
74 let mut file = std::fs::OpenOptions::new().create(true).write(true).append(done > 0).truncate(done == 0).open(&part)?;
75 let mut body = resp.body_mut().as_reader();
76 let mut buf = vec![0u8; 1 << 16];
77 loop {
78 if !progress(Progress { done, total }) {
79 return Err(Error::Cancelled { done: human(done), total: human(total) });
80 }
81 let n = body.read(&mut buf)?;
82 if n == 0 {
83 break;
84 }
85 file.write_all(&buf[..n])?;
86 done += n as u64;
87 if done > total {
88 break;
89 }
90 }
91 file.flush()?;
92 }
93 if done != total {
94 if done > total {
95 let _ = std::fs::remove_file(&part);
96 }
97 return Err(Error::Incomplete { done: human(done), total: human(total) });
98 }
99 if let Some(want) = &spec.sha256 {
100 let got = sha256_of(&part)?;
101 if !got.eq_ignore_ascii_case(want) {
102 let _ = std::fs::remove_file(&part);
103 return Err(Error::Checksum { name: spec.file.clone(), got });
104 }
105 }
106 std::fs::rename(&part, &dest)?;
107 progress(Progress { done, total });
108 Ok(dest)
109}
110
111pub fn sha256_of(path: &Path) -> Result<String> {
113 let mut hasher = Sha256::new();
114 std::io::copy(&mut std::fs::File::open(path)?, &mut hasher)?;
115 Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use crate::testing::MockHub;
122
123 fn body() -> Vec<u8> {
124 (0..2_000_000u32).map(|i| (i % 251) as u8).collect()
125 }
126
127 fn spec_for(body: &[u8]) -> ModelSpec {
128 let sum = Sha256::digest(body).iter().map(|b| format!("{b:02x}")).collect::<String>();
129 ModelSpec { id: "t".into(), label: "Test".into(), repo: "o/n".into(), file: "t.gguf".into(), size: body.len() as u64, sha256: Some(sum) }
130 }
131
132 #[test]
133 fn downloads_checks_and_renames() {
134 let b = body();
135 let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
136 let tmp = tempfile::tempdir().unwrap();
137 let store = ModelStore::new(tmp.path()).with_hub(hub.url());
138 let spec = spec_for(&b);
139 let mut last = 0.0;
140 let path = download(&store, &spec, &Consent::given(&spec), &mut |p| {
141 last = p.fraction();
142 true
143 })
144 .unwrap();
145 assert_eq!(std::fs::read(&path).unwrap(), b);
146 assert_eq!(last, 1.0);
147 assert!(store.installed(&spec));
148 assert_eq!(store.partial_bytes(&spec), 0);
149 let hits = hub.requests();
151 download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
152 assert_eq!(hub.requests(), hits);
153 }
154
155 #[test]
156 fn a_cancelled_download_resumes_with_a_range_request() {
157 let b = body();
158 let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
159 let tmp = tempfile::tempdir().unwrap();
160 let store = ModelStore::new(tmp.path()).with_hub(hub.url());
161 let spec = spec_for(&b);
162 let mut calls = 0;
163 let err = download(&store, &spec, &Consent::given(&spec), &mut |_| {
164 calls += 1;
165 calls < 2
166 })
167 .unwrap_err();
168 assert!(matches!(err, Error::Cancelled { .. }), "{err}");
169 let kept = store.partial_bytes(&spec);
170 assert!(kept > 0 && kept < b.len() as u64, "kept {kept}");
171 download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
172 assert_eq!(std::fs::read(store.path(&spec)).unwrap(), b);
173 assert_eq!(hub.last_range(), Some(format!("bytes={kept}-")));
174 }
175
176 #[test]
177 fn a_wrong_checksum_deletes_the_part_and_names_the_file() {
178 let b = body();
179 let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
180 let tmp = tempfile::tempdir().unwrap();
181 let store = ModelStore::new(tmp.path()).with_hub(hub.url());
182 let mut spec = spec_for(&b);
183 spec.sha256 = Some("0".repeat(64));
184 let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
185 assert!(matches!(err, Error::Checksum { ref name, .. } if name == "t.gguf"), "{err}");
186 assert_eq!(store.partial_bytes(&spec), 0);
187 assert!(!store.installed(&spec));
188 }
189
190 #[test]
191 fn consent_for_another_model_is_refused_and_http_errors_are_reported() {
192 let b = body();
193 let hub = MockHub::start("/o/n/resolve/main/other.gguf", b.clone());
194 let tmp = tempfile::tempdir().unwrap();
195 let store = ModelStore::new(tmp.path()).with_hub(hub.url());
196 let spec = spec_for(&b);
197 let mut other = spec.clone();
198 other.id = "other".into();
199 assert!(matches!(download(&store, &spec, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
200 let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
201 assert!(matches!(err, Error::Http(ref m) if m.contains("404")), "{err}");
202 }
203
204 #[test]
205 fn a_short_body_is_incomplete_and_kept_for_resume() {
206 let b = body();
207 let hub = MockHub::start("/o/n/resolve/main/t.gguf", b[..1000].to_vec());
208 let tmp = tempfile::tempdir().unwrap();
209 let store = ModelStore::new(tmp.path()).with_hub(hub.url());
210 let spec = spec_for(&b);
211 let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
212 assert!(matches!(err, Error::Incomplete { .. }), "{err}");
213 assert_eq!(store.partial_bytes(&spec), 1000);
214 }
215}