1use std::io::Read;
6use std::path::{Path, PathBuf};
7
8use crate::{Error, Result};
9
10pub fn hash(data: &[u8]) -> String {
12 blake3::hash(data).to_hex().to_string()
13}
14
15pub 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
23pub fn max_compressed(len: u64) -> u64 {
25 lz4_flex::block::get_maximum_output_size(len as usize) as u64
26}
27
28pub fn compress(data: &[u8]) -> Vec<u8> {
30 let mut out = vec![0u8; max_compressed(data.len() as u64) as usize];
31 let n = lz4_flex::block::compress_into(data, &mut out).unwrap_or(0);
33 out.truncate(n);
34 out
35}
36
37pub 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
49pub 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
68pub fn chunk_name(hash: &str) -> String {
70 format!("chunks/{}/{hash}", &hash[..2])
71}
72
73pub 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
80pub struct ChunkStore {
82 root: PathBuf,
83}
84
85impl ChunkStore {
86 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 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 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 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 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 #[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}