Skip to main content

tuff_core/
cache.rs

1use std::path::{Path, PathBuf};
2
3use sha2::{Digest, Sha256};
4
5use crate::error::{Result, TuffError};
6
7pub fn cache_root(home: &Path) -> PathBuf {
8    crate::paths::user_cache(home).join("sha256")
9}
10
11pub fn cache_path(home: &Path, hash: &str) -> Result<PathBuf> {
12    cache_path_in(&cache_root(home), hash)
13}
14
15/// Where a baseline with `hash` lives under a baseline folder `root`.
16pub fn cache_path_in(root: &Path, hash: &str) -> Result<PathBuf> {
17    validate_hash(hash)?;
18    Ok(root.join(&hash[..2]).join(hash))
19}
20
21pub fn validate_hash(hash: &str) -> Result<()> {
22    if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
23        return Err(TuffError::corrupt(format!(
24            "invalid capability hash: {hash}"
25        )));
26    }
27    Ok(())
28}
29
30/// Hashes a materialized directory using sorted relative paths and file bytes.
31/// Directory metadata and filesystem iteration order are intentionally ignored.
32pub fn hash_tree(root: &Path) -> Result<String> {
33    let mut files = Vec::new();
34    collect_files(root, root, &mut files)?;
35    files.sort_by(|a, b| a.0.cmp(&b.0));
36
37    let mut hasher = Sha256::new();
38    for (path, content) in files {
39        let path = path.to_string_lossy().replace('\\', "/");
40        hasher.update((path.len() as u64).to_be_bytes());
41        hasher.update(path.as_bytes());
42        hasher.update((content.len() as u64).to_be_bytes());
43        hasher.update(content);
44    }
45    Ok(format!("{:x}", hasher.finalize()))
46}
47
48pub fn populate(home: &Path, hash: &str, source: &Path) -> Result<PathBuf> {
49    populate_in(&cache_root(home), hash, source)
50}
51
52/// `populate` into a baseline folder the caller names, such as the one
53/// [`cache_root`] gives for a home directory.
54pub fn populate_in(root: &Path, hash: &str, source: &Path) -> Result<PathBuf> {
55    let destination = cache_path_in(root, hash)?;
56    let actual = hash_tree(source)?;
57    if actual != hash {
58        return Err(TuffError::corrupt(format!(
59            "materialized capability hash mismatch: expected {hash}, got {actual}"
60        ))
61        .with_hint("run 'tuff cache clear' and retry; the lockfile is the source of truth"));
62    }
63
64    if destination.is_dir() {
65        if hash_tree(&destination)? == hash {
66            return Ok(destination);
67        }
68        if let Err(error) = std::fs::remove_dir_all(&destination) {
69            if error.kind() == std::io::ErrorKind::PermissionDenied {
70                return Ok(source.to_path_buf());
71            }
72            return Err(error.into());
73        }
74    }
75
76    let parent = destination
77        .parent()
78        .ok_or_else(|| TuffError::new("invalid cache destination"))?;
79    if let Err(error) = std::fs::create_dir_all(parent) {
80        if error.kind() == std::io::ErrorKind::PermissionDenied {
81            return Ok(source.to_path_buf());
82        }
83        return Err(error.into());
84    }
85    let temporary = match tempfile::Builder::new()
86        .prefix("tuff-cache-")
87        .tempdir_in(parent)
88    {
89        Ok(temporary) => temporary,
90        Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
91            return Ok(source.to_path_buf());
92        }
93        Err(error) => return Err(error.into()),
94    };
95    if let Err(error) = copy_tree(source, temporary.path()) {
96        if error.to_string().contains("Permission denied") {
97            return Ok(source.to_path_buf());
98        }
99        return Err(error);
100    }
101    let temporary_path = temporary.keep();
102    if let Err(error) = std::fs::rename(&temporary_path, &destination) {
103        if error.kind() == std::io::ErrorKind::PermissionDenied {
104            return Ok(source.to_path_buf());
105        }
106
107        // Another process may have populated the same content-addressed
108        // directory between our existence check and the rename. Reuse its
109        // verified result instead of treating that harmless race as a cache
110        // failure.
111        if destination.is_dir() && hash_tree(&destination).ok().as_deref() == Some(hash) {
112            let _ = std::fs::remove_dir_all(&temporary_path);
113            return Ok(destination);
114        }
115
116        return Err(error.into());
117    }
118    Ok(destination)
119}
120
121pub fn read_verified(home: &Path, hash: &str) -> Result<Option<PathBuf>> {
122    let path = cache_path(home, hash)?;
123    if !path.is_dir() {
124        return Ok(None);
125    }
126    if hash_tree(&path)? != hash {
127        return Ok(None);
128    }
129    Ok(Some(path))
130}
131
132pub fn clear(home: &Path) -> Result<()> {
133    let root = crate::paths::user_cache(home);
134    if root.exists() {
135        std::fs::remove_dir_all(root)?;
136    }
137    Ok(())
138}
139
140fn collect_files(root: &Path, current: &Path, output: &mut Vec<(PathBuf, Vec<u8>)>) -> Result<()> {
141    for entry in std::fs::read_dir(current)? {
142        let entry = entry?;
143        let path = entry.path();
144        if path.is_dir() {
145            collect_files(root, &path, output)?;
146        } else if path.is_file() {
147            let relative = path
148                .strip_prefix(root)
149                .map_err(|error| TuffError::of(crate::error::ErrorKind::Io, error.to_string()))?
150                .to_path_buf();
151            output.push((relative, std::fs::read(path)?));
152        }
153    }
154    Ok(())
155}
156
157fn copy_tree(source: &Path, destination: &Path) -> Result<()> {
158    std::fs::create_dir_all(destination)?;
159    for entry in std::fs::read_dir(source)? {
160        let entry = entry?;
161        let source_path = entry.path();
162        let destination_path = destination.join(entry.file_name());
163        if source_path.is_dir() {
164            copy_tree(&source_path, &destination_path)?;
165        } else if source_path.is_file() {
166            std::fs::copy(source_path, destination_path)?;
167        }
168    }
169    Ok(())
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use tempfile::TempDir;
176
177    #[test]
178    fn hash_tree_is_independent_of_creation_order() {
179        let left = TempDir::new().unwrap();
180        let right = TempDir::new().unwrap();
181        std::fs::create_dir_all(left.path().join("nested")).unwrap();
182        std::fs::create_dir_all(right.path().join("nested")).unwrap();
183        std::fs::write(left.path().join("a"), "a").unwrap();
184        std::fs::write(left.path().join("nested/b"), "b").unwrap();
185        std::fs::write(right.path().join("nested/b"), "b").unwrap();
186        std::fs::write(right.path().join("a"), "a").unwrap();
187        assert_eq!(
188            hash_tree(left.path()).unwrap(),
189            hash_tree(right.path()).unwrap()
190        );
191    }
192
193    #[test]
194    fn cache_round_trip_verifies_content() {
195        let home = TempDir::new().unwrap();
196        let source = TempDir::new().unwrap();
197        std::fs::write(source.path().join("file"), "content").unwrap();
198        let hash = hash_tree(source.path()).unwrap();
199        let path = populate(home.path(), &hash, source.path()).unwrap();
200        assert_eq!(read_verified(home.path(), &hash).unwrap(), Some(path));
201    }
202
203    #[test]
204    fn concurrent_populate_reuses_existing_content_addressed_directory() {
205        let home = TempDir::new().unwrap();
206        let source = TempDir::new().unwrap();
207        std::fs::write(source.path().join("file"), "content").unwrap();
208        let hash = hash_tree(source.path()).unwrap();
209        let home_path = home.path().to_path_buf();
210        let source_path = source.path().to_path_buf();
211
212        let workers = (0..8)
213            .map(|_| {
214                let home_path = home_path.clone();
215                let source_path = source_path.clone();
216                let hash = hash.clone();
217                std::thread::spawn(move || populate(&home_path, &hash, &source_path))
218            })
219            .collect::<Vec<_>>();
220
221        for worker in workers {
222            worker.join().unwrap().unwrap();
223        }
224
225        assert!(read_verified(home.path(), &hash).unwrap().is_some());
226    }
227}