Skip to main content

troupekit_local/
cache.rs

1use crate::catalog::LocalSpec;
2use crate::error::LocalError;
3use crate::sha256::{to_hex, Sha256};
4use std::collections::BTreeMap;
5use std::fs::{File, Metadata, OpenOptions};
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Mutex, PoisonError};
10use std::time::SystemTime;
11
12const PART_TRIES: usize = 64;
13const HASH_CHUNK: usize = 1024 * 1024;
14
15static VERIFIED: Mutex<BTreeMap<PathBuf, Identity>> = Mutex::new(BTreeMap::new());
16
17const MAX_REDIRECTS: u32 = 5;
18use troupekit_core::http::{HttpRequest, Transport};
19
20/// A folder of downloaded model files, one `<id>-<sha256>.gguf` per row,
21/// so a row with another digest never reuses a file. A file is used only
22/// when its size and SHA-256 match, hashed once per process; `fetch`
23/// checks the SHA-256 before a file gets its final name. No call
24/// downloads alone.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ModelCache {
27    dir: PathBuf,
28}
29
30impl ModelCache {
31    /// Uses `dir` as the model folder; it is created on the first fetch.
32    /// Mobile apps pass their own app folder here.
33    /// Output: the cache.
34    pub fn new(dir: impl Into<PathBuf>) -> Self {
35        Self { dir: dir.into() }
36    }
37
38    /// Picks the default folder: `$TROUPEKIT_MODEL_DIR`, else
39    /// `$HOME/.cache/troupekit/models`, else `%LOCALAPPDATA%\troupekit\models`.
40    /// Output: the cache, or `Cache` asking for `ModelCache::new(dir)`.
41    pub fn default_dir() -> Result<Self, LocalError> {
42        let non_empty = |name: &str| {
43            std::env::var_os(name)
44                .filter(|v| !v.is_empty())
45                .map(PathBuf::from)
46        };
47        if let Some(dir) = non_empty("TROUPEKIT_MODEL_DIR") {
48            return Ok(Self::new(dir));
49        }
50        if let Some(home) = non_empty("HOME") {
51            return Ok(Self::new(
52                home.join(".cache").join("troupekit").join("models"),
53            ));
54        }
55        if let Some(local) = non_empty("LOCALAPPDATA") {
56            return Ok(Self::new(local.join("troupekit").join("models")));
57        }
58        Err(LocalError::Cache(
59            "no model folder: set TROUPEKIT_MODEL_DIR or build the cache with ModelCache::new(dir)"
60                .into(),
61        ))
62    }
63
64    /// Returns the model folder.
65    /// Input: none.
66    /// Output: the folder path.
67    pub fn dir(&self) -> &Path {
68        &self.dir
69    }
70
71    /// Returns the file of a row when it is a regular file of exactly the
72    /// declared size whose SHA-256 matches the row. The first call in a
73    /// process hashes the file; later calls skip it while the file keeps
74    /// its identity (device, inode, size, mtime). A partial or other file
75    /// gives `None`. Never touches the network.
76    pub fn path(&self, spec: &LocalSpec) -> Option<PathBuf> {
77        let path = self.file_of(spec);
78        let meta = std::fs::symlink_metadata(&path).ok()?;
79        if !meta.is_file() || meta.len() != spec.bytes() {
80            return None;
81        }
82        let identity = Identity::of(&meta);
83        let known = VERIFIED
84            .lock()
85            .unwrap_or_else(PoisonError::into_inner)
86            .get(&path)
87            == Some(&identity);
88        if known {
89            return Some(path);
90        }
91        let mut file = File::open(&path).ok()?;
92        if Identity::of(&file.metadata().ok()?) != identity {
93            return None;
94        }
95        if hash_file(&mut file).ok()? != spec.sha256() {
96            return None;
97        }
98        VERIFIED
99            .lock()
100            .unwrap_or_else(PoisonError::into_inner)
101            .insert(path.clone(), identity);
102        Some(path)
103    }
104
105    /// Downloads a row through `transport` unless `path` already finds
106    /// it, following up to 5 redirects that stay on https: into a part file of its own (created exclusively, 0600), refused
107    /// past the declared size or on a hash mismatch, then renamed. Output: the path.
108    pub async fn fetch(
109        &self,
110        spec: &LocalSpec,
111        transport: &dyn Transport,
112    ) -> Result<PathBuf, LocalError> {
113        if let Some(path) = self.path(spec) {
114            return Ok(path);
115        }
116        if !spec.url().starts_with("https://") {
117            return Err(LocalError::Cache(format!(
118                "model {}: refusing a non-https URL",
119                spec.id()
120            )));
121        }
122        create_private_dir(&self.dir)?;
123        let (part, file) = create_part_file(&self.dir, spec.id())?;
124        let mut guard = PartGuard(Some(part));
125        self.download(spec, transport, file).await?;
126        let path = self.file_of(spec);
127        let part = guard.0.as_ref().expect("the guard holds the part path");
128        std::fs::rename(part, &path)
129            .map_err(|e| LocalError::Cache(format!("model {}: rename failed: {e}", spec.id())))?;
130        guard.0 = None;
131        if self.path(spec).is_none() {
132            return Err(LocalError::Cache(format!(
133                "model {}: file changed after it was published",
134                spec.id()
135            )));
136        }
137        Ok(path)
138    }
139
140    async fn download(
141        &self,
142        spec: &LocalSpec,
143        transport: &dyn Transport,
144        mut file: File,
145    ) -> Result<(), LocalError> {
146        let id = spec.id();
147        let mut url = spec.url().to_string();
148        let mut redirects = 0;
149        let mut response = loop {
150            let response = transport
151                .send(HttpRequest::get(url.as_str()))
152                .await
153                .map_err(|e| LocalError::Cache(format!("model {id}: download failed: {e}")))?;
154            if !matches!(response.status, 301 | 302 | 303 | 307 | 308) {
155                break response;
156            }
157            if redirects == MAX_REDIRECTS {
158                return Err(LocalError::Cache(format!(
159                    "model {id}: more than {MAX_REDIRECTS} redirects"
160                )));
161            }
162            redirects += 1;
163            url = redirect_target(&url, response.header("location"))
164                .map_err(|why| LocalError::Cache(format!("model {id}: {why}")))?;
165        };
166        assert!(url.starts_with("https://"), "every followed URL is https");
167        if response.status != 200 {
168            return Err(LocalError::Cache(format!(
169                "model {id}: server answered {}",
170                response.status
171            )));
172        }
173        let mut hasher = Sha256::new();
174        let mut total: u64 = 0;
175        while let Some(chunk) = response
176            .body
177            .chunk()
178            .await
179            .map_err(|e| LocalError::Cache(format!("model {id}: download failed: {e}")))?
180        {
181            total = total.saturating_add(chunk.len() as u64);
182            if total > spec.bytes() {
183                return Err(LocalError::Cache(format!(
184                    "model {id}: download is over the declared {} bytes",
185                    spec.bytes()
186                )));
187            }
188            hasher.update(&chunk);
189            file.write_all(&chunk)
190                .map_err(|e| LocalError::Cache(format!("model {id}: write failed: {e}")))?;
191        }
192        if response.truncated || total != spec.bytes() {
193            return Err(LocalError::Cache(format!(
194                "model {id}: got {total} bytes, expected {}",
195                spec.bytes()
196            )));
197        }
198        file.sync_all()
199            .map_err(|e| LocalError::Cache(format!("model {id}: sync failed: {e}")))?;
200        let got = to_hex(&hasher.finish());
201        if got != spec.sha256() {
202            return Err(LocalError::Cache(format!(
203                "model {id}: SHA-256 {got} does not match the catalog's {}",
204                spec.sha256()
205            )));
206        }
207        Ok(())
208    }
209
210    fn file_of(&self, spec: &LocalSpec) -> PathBuf {
211        assert_eq!(spec.sha256().len(), 64, "a row's digest is checked hex");
212        self.dir
213            .join(format!("{}-{}.gguf", spec.id(), spec.sha256()))
214    }
215}
216
217/// What marks a file as the one already hashed: size, mtime and, on
218/// unix, device and inode. A changed file gets another identity and is
219/// hashed again.
220#[derive(Debug, Clone, PartialEq, Eq)]
221struct Identity {
222    len: u64,
223    modified: Option<SystemTime>,
224    node: (u64, u64),
225}
226
227impl Identity {
228    fn of(meta: &Metadata) -> Self {
229        #[cfg(unix)]
230        let node = {
231            use std::os::unix::fs::MetadataExt;
232            (meta.dev(), meta.ino())
233        };
234        #[cfg(not(unix))]
235        let node = (0, 0);
236        Self {
237            len: meta.len(),
238            modified: meta.modified().ok(),
239            node,
240        }
241    }
242}
243
244/// Hashes an open file from its current position to the end.
245/// Input: the file. Output: the lowercase hex SHA-256, or the read error.
246fn hash_file(file: &mut File) -> std::io::Result<String> {
247    let mut hasher = Sha256::new();
248    let mut buf = vec![0u8; HASH_CHUNK];
249    loop {
250        let n = file.read(&mut buf)?;
251        if n == 0 {
252            break;
253        }
254        hasher.update(&buf[..n]);
255    }
256    let hex = to_hex(&hasher.finish());
257    assert_eq!(hex.len(), 64, "a SHA-256 is 64 hex digits");
258    Ok(hex)
259}
260
261/// Resolves the `Location` of a redirect from `from`: an absolute https
262/// URL as is, a path starting with one `/` on the same origin. Anything
263/// else, plain http included, is refused so a download never leaves https.
264/// Input: the current URL and the header. Output: the next URL or why not.
265fn redirect_target(from: &str, location: Option<&str>) -> Result<String, String> {
266    let Some(location) = location.map(str::trim).filter(|l| !l.is_empty()) else {
267        return Err("redirect without a Location".into());
268    };
269    if location.starts_with("https://") {
270        return Ok(location.to_string());
271    }
272    if location.starts_with('/') && !location.starts_with("//") {
273        let rest = from
274            .strip_prefix("https://")
275            .expect("only https URLs are fetched");
276        let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
277        assert!(!host.is_empty(), "an https URL names a host");
278        return Ok(format!("https://{host}{location}"));
279    }
280    Err("refusing a redirect that leaves https".into())
281}
282
283fn create_private_dir(dir: &Path) -> Result<(), LocalError> {
284    let mut builder = std::fs::DirBuilder::new();
285    builder.recursive(true);
286    #[cfg(unix)]
287    {
288        use std::os::unix::fs::DirBuilderExt;
289        builder.mode(0o700);
290    }
291    builder
292        .create(dir)
293        .map_err(|e| LocalError::Cache(format!("cannot create {}: {e}", dir.display())))
294}
295
296struct PartGuard(Option<PathBuf>);
297
298impl Drop for PartGuard {
299    fn drop(&mut self) {
300        if let Some(part) = self.0.take() {
301            let _ = std::fs::remove_file(part);
302        }
303    }
304}
305
306fn create_part_file(dir: &Path, id: &str) -> Result<(PathBuf, File), LocalError> {
307    static NEXT: AtomicU64 = AtomicU64::new(0);
308    let mut options = OpenOptions::new();
309    options.write(true).create_new(true);
310    #[cfg(unix)]
311    {
312        use std::os::unix::fs::OpenOptionsExt;
313        options.mode(0o600);
314    }
315    for _ in 0..PART_TRIES {
316        let n = NEXT.fetch_add(1, Ordering::Relaxed);
317        let part = dir.join(format!("{id}.gguf.{}-{n}.part", std::process::id()));
318        match options.open(&part) {
319            Ok(file) => return Ok((part, file)),
320            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
321            Err(e) => {
322                return Err(LocalError::Cache(format!(
323                    "cannot create {}: {e}",
324                    part.display()
325                )))
326            }
327        }
328    }
329    Err(LocalError::Cache(format!(
330        "model {id}: no free part file name after {PART_TRIES} tries"
331    )))
332}