Skip to main content

simee_bundle/
store.rs

1//! The content-addressed chunk store: `chunks/<aa>/<blake3>`, each chunk one LZ4 block of the
2//! data whose BLAKE3 names it. Identical data is stored once, and a reader checks every chunk
3//! against its name.
4
5use std::io::Read;
6use std::path::{Path, PathBuf};
7
8use crate::{Error, Result};
9
10/// The BLAKE3 of `data`, as the manifest writes it.
11pub fn hash(data: &[u8]) -> String {
12    blake3::hash(data).to_hex().to_string()
13}
14
15/// The BLAKE3 of the file at `path`, read in 1 MiB pieces (a 4.4 GB system image: ~3 s).
16pub fn hash_file(path: &Path) -> Result<String> {
17    let f = std::fs::File::open(path).map_err(|e| Error::Io(path.to_path_buf(), e))?;
18    let mut h = blake3::Hasher::new();
19    h.update_reader(std::io::BufReader::with_capacity(1 << 20, f)).map_err(|e| Error::Io(path.to_path_buf(), e))?;
20    Ok(h.finalize().to_hex().to_string())
21}
22
23/// The most a chunk of `len` bytes takes compressed (LZ4's bound for data that doesn't compress).
24pub fn max_compressed(len: u64) -> u64 {
25    lz4_flex::block::get_maximum_output_size(len as usize) as u64
26}
27
28/// `data` as one LZ4 block (no size header: the manifest gives each chunk's length).
29pub fn compress(data: &[u8]) -> Vec<u8> {
30    let mut out = vec![0u8; max_compressed(data.len() as u64) as usize];
31    // The buffer is LZ4's own bound for this input, so the block always fits.
32    let n = lz4_flex::block::compress_into(data, &mut out).unwrap_or(0);
33    out.truncate(n);
34    out
35}
36
37/// Decompresses chunk `hash` into at most `max` bytes (a block that would decompress past it is
38/// refused) and checks it is what its name says.
39pub fn decompress_verified(hash_hex: &str, compressed: &[u8], max: u64) -> Result<Vec<u8>> {
40    let mut data = vec![0u8; max as usize];
41    let n = lz4_flex::block::decompress_into(compressed, &mut data).map_err(|_| Error::ChunkHash(hash_hex.to_owned()))?;
42    data.truncate(n);
43    if hash(&data) != hash_hex {
44        return Err(Error::ChunkHash(hash_hex.to_owned()));
45    }
46    Ok(data)
47}
48
49/// Reads bundle file `path` whole: a regular file (not a symlink, a device or a FIFO) of at most
50/// `limit` bytes, so a directory bundle can't make a reader follow a link to `/dev/zero`.
51pub fn read_regular(path: &Path, limit: u64) -> Result<Vec<u8>> {
52    let meta = std::fs::symlink_metadata(path).map_err(|e| Error::Io(path.to_path_buf(), e))?;
53    if !meta.file_type().is_file() {
54        return Err(Error::Unsupported(format!("{} isn't a regular file", path.display())));
55    }
56    if meta.len() > limit {
57        return Err(Error::Unsupported(format!("{} is {} bytes, more than {limit}", path.display(), meta.len())));
58    }
59    let f = std::fs::File::open(path).map_err(|e| Error::Io(path.to_path_buf(), e))?;
60    let mut v = Vec::with_capacity(meta.len() as usize);
61    f.take(limit + 1).read_to_end(&mut v).map_err(|e| Error::Io(path.to_path_buf(), e))?;
62    if v.len() as u64 > limit {
63        return Err(Error::Unsupported(format!("{} grew past {limit} bytes", path.display())));
64    }
65    Ok(v)
66}
67
68/// The name a chunk has in a bundle: `chunks/<first two hex digits>/<hash>`.
69pub fn chunk_name(hash: &str) -> String {
70    format!("chunks/{}/{hash}", &hash[..2])
71}
72
73/// The hash a bundle entry named like [`chunk_name`] holds, if it is named so.
74pub fn parse_chunk_name(name: &str) -> Option<&str> {
75    let rest = name.strip_prefix("chunks/")?;
76    let (dir, hash) = rest.split_once('/')?;
77    (crate::manifest::is_hash(hash) && dir == &hash[..2]).then_some(hash)
78}
79
80/// A bundle directory's chunks.
81pub struct ChunkStore {
82    root: PathBuf,
83}
84
85impl ChunkStore {
86    /// The store of the bundle directory `root` (its `chunks/`).
87    pub fn new(root: &Path) -> ChunkStore {
88        ChunkStore { root: root.to_path_buf() }
89    }
90
91    pub fn path(&self, hash: &str) -> PathBuf {
92        self.root.join(chunk_name(hash))
93    }
94
95    pub fn has(&self, hash: &str) -> bool {
96        self.path(hash).is_file()
97    }
98
99    /// Stores `compressed` as chunk `hash` unless the store has it; whether it was new. Written
100    /// beside and renamed, so a chunk file is whole or absent.
101    pub fn put(&self, hash: &str, compressed: &[u8]) -> Result<bool> {
102        let path = self.path(hash);
103        if path.is_file() {
104            return Ok(false);
105        }
106        let dir = path.parent().unwrap_or(&self.root);
107        std::fs::create_dir_all(dir).map_err(|e| Error::Io(dir.to_path_buf(), e))?;
108        let tmp = dir.join(format!(".{hash}.partial"));
109        std::fs::write(&tmp, compressed).map_err(|e| Error::Io(tmp.clone(), e))?;
110        std::fs::rename(&tmp, &path).map_err(|e| Error::Io(path.clone(), e))?;
111        Ok(true)
112    }
113
114    /// Chunk `hash`, decompressed (at most `max` bytes) and checked against its name.
115    pub fn get(&self, hash: &str, max: u64) -> Result<Vec<u8>> {
116        let path = self.path(hash);
117        let compressed = match read_regular(&path, max_compressed(max)) {
118            Err(Error::Io(_, e)) if e.kind() == std::io::ErrorKind::NotFound => {
119                return Err(Error::Missing { first: hash.to_owned(), count: 1 });
120            }
121            r => r?,
122        };
123        decompress_verified(hash, &compressed, max)
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    #[test]
132    fn identical_chunks_are_stored_once_and_checked_on_read() {
133        let root = std::env::temp_dir().join(format!("sim-bundle-store-{}", std::process::id()));
134        let _ = std::fs::remove_dir_all(&root);
135        let store = ChunkStore::new(&root);
136        let data = vec![42u8; 100_000];
137        let h = hash(&data);
138        let z = compress(&data);
139        assert!(z.len() < 1000, "a run compresses");
140        // A block that decompresses past what the chunk may hold is refused, not grown into.
141        assert!(matches!(decompress_verified(&h, &z, 99_999), Err(Error::ChunkHash(_))));
142        assert_eq!(decompress_verified(&h, &z, 100_000).expect("exact"), data);
143        assert!(store.put(&h, &z).expect("put"));
144        assert!(!store.put(&h, &z).expect("put again"), "already stored");
145        assert_eq!(std::fs::read_dir(root.join("chunks")).expect("chunks").count(), 1);
146        assert_eq!(store.path(&h), root.join(format!("chunks/{}/{h}", &h[..2])));
147        assert_eq!(parse_chunk_name(&chunk_name(&h)), Some(h.as_str()));
148        assert_eq!(parse_chunk_name(&format!("chunks/zz/{h}")), None, "the directory is the hash's prefix");
149        assert_eq!(parse_chunk_name("chunks/../x"), None);
150        assert_eq!(store.get(&h, 1 << 20).expect("get"), data);
151        assert!(store.get(&h, 10).is_err(), "longer than allowed");
152        // A chunk whose content isn't what its name says.
153        std::fs::write(store.path(&h), compress(b"other")).expect("overwrite");
154        assert!(matches!(store.get(&h, 1 << 20), Err(Error::ChunkHash(_))));
155        assert!(matches!(store.get(&hash(b"absent"), 1 << 20), Err(Error::Missing { .. })));
156        // A chunk that is a link (to /dev/zero, which would read forever) is refused unread.
157        #[cfg(unix)]
158        {
159            std::fs::remove_file(store.path(&h)).expect("rm");
160            std::os::unix::fs::symlink("/dev/zero", store.path(&h)).expect("symlink");
161            assert!(matches!(store.get(&h, 1 << 20), Err(Error::Unsupported(m)) if m.contains("regular file")));
162            assert!(read_regular(Path::new("/dev/zero"), 1 << 20).is_err(), "a device");
163        }
164        let _ = std::fs::remove_dir_all(root);
165    }
166}