#![expect(clippy::similar_names)]
use std::path::{Path, PathBuf};
use crate::delta::Signature;
struct SigCache {
dir: PathBuf,
}
impl SigCache {
fn new() -> Option<Self> {
crate::platform::fs::sig_cache_dir().map(|dir| Self { dir })
}
#[cfg(test)]
fn new_at(dir: PathBuf) -> Self {
Self { dir }
}
fn entry_path(&self, path: &Path) -> PathBuf {
let key = blake3::hash(path.to_string_lossy().as_bytes());
self.dir.join(format!("{}.sig", key.to_hex()))
}
fn lookup(
&self,
path: &Path,
file_size: u64,
mtime_sec: u64,
mtime_nsec: u32,
) -> Option<Signature> {
let bytes = std::fs::read(self.entry_path(path)).ok()?;
let (f_size, f_mtime_sec, f_mtime_nsec, sample, signature): (
u64,
u64,
u32,
[u8; 32],
Signature,
) = postcard::from_bytes(&bytes).ok()?;
if f_size != file_size || f_mtime_sec != mtime_sec || f_mtime_nsec != mtime_nsec {
return None;
}
if content_sample(path) != Some(sample) {
let _ = std::fs::remove_file(self.entry_path(path));
return None;
}
Some(signature)
}
fn store(
&self,
path: &Path,
file_size: u64,
mtime_sec: u64,
mtime_nsec: u32,
signature: &Signature,
) {
let Some(sample) = content_sample(path) else {
return;
};
let Ok(bytes) = postcard::to_allocvec(&(
file_size,
mtime_sec,
mtime_nsec,
sample,
signature,
)) else {
return;
};
if std::fs::create_dir_all(&self.dir).is_err() {
return;
}
let target = self.entry_path(path);
let tmp = PathBuf::from(format!("{}.tmp", target.display()));
if std::fs::write(&tmp, &bytes).is_ok() {
let _ = std::fs::rename(&tmp, &target);
}
}
}
fn content_sample(path: &Path) -> Option<[u8; 32]> {
use std::io::{Read, Seek, SeekFrom};
const SAMPLE: u64 = 4096;
#[expect(clippy::cast_possible_truncation)]
let sample_len = SAMPLE as usize;
let mut file = std::fs::File::open(path).ok()?;
let len = file.metadata().ok()?.len();
let mut hasher = blake3::Hasher::new();
let mut buf = vec![0u8; len.min(SAMPLE) as usize];
file.read_exact(&mut buf).ok()?;
hasher.update(&buf);
if len > SAMPLE {
file.seek(SeekFrom::Start(len - SAMPLE)).ok()?;
let mut tail = vec![0u8; sample_len];
file.read_exact(&mut tail).ok()?;
hasher.update(&tail);
}
Some(*hasher.finalize().as_bytes())
}
fn cache() -> Option<&'static SigCache> {
static CACHE: std::sync::OnceLock<Option<SigCache>> = std::sync::OnceLock::new();
CACHE.get_or_init(SigCache::new).as_ref()
}
pub(crate) fn lookup(
path: &Path,
file_size: u64,
mtime_sec: u64,
mtime_nsec: u32,
) -> Option<Signature> {
cache().and_then(|c| c.lookup(path, file_size, mtime_sec, mtime_nsec))
}
pub(crate) fn store(
path: &Path,
file_size: u64,
mtime_sec: u64,
mtime_nsec: u32,
signature: &Signature,
) {
if let Some(c) = cache() {
c.store(path, file_size, mtime_sec, mtime_nsec, signature);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::delta::{ChunkSignature, Signature};
use std::time::SystemTime;
fn test_sig(n: u64) -> Signature {
let chunk = ChunkSignature {
offset: n,
len: 100,
weak: None,
strong_hash: [(n & 0xFF) as u8; 32],
};
Signature {
file_size: 1000,
chunks: vec![chunk],
}
}
fn sig_cache(tmp: &Path) -> SigCache {
SigCache::new_at(tmp.join("sig-cache"))
}
#[test]
fn lookup_hit_and_miss() {
let tmp = std::env::temp_dir().join(format!("cp2-sigcache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let cache = sig_cache(&tmp);
let path = tmp.join("sub").join("file.bin");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"hello world").unwrap();
assert!(cache.lookup(&path, 11, 1, 2).is_none());
cache.store(&path, 11, 1, 2, &test_sig(7));
let got = cache.lookup(&path, 11, 1, 2).expect("hit");
assert_eq!(got.file_size, 1000);
assert_eq!(got.chunks[0].offset, 7);
assert!(cache.lookup(&path, 12, 1, 2).is_none());
assert!(cache.lookup(&path, 11, 3, 2).is_none());
assert!(cache.lookup(&path, 11, 1, 9).is_none());
let other = tmp.join("other.bin");
std::fs::write(&other, b"x").unwrap();
assert!(cache.lookup(&other, 1, 1, 2).is_none());
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn corrupt_entry_is_a_miss() {
let tmp = std::env::temp_dir().join(format!("cp2-sigcache-corrupt-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let cache = sig_cache(&tmp);
let path = tmp.join("file.bin");
std::fs::create_dir_all(&tmp).unwrap();
std::fs::write(&path, b"data").unwrap();
std::fs::create_dir_all(&cache.dir).unwrap();
std::fs::write(cache.entry_path(&path), b"not postcard").unwrap();
assert!(cache.lookup(&path, 4, 1, 2).is_none());
cache.store(&path, 4, 1, 2, &test_sig(3));
assert!(cache.lookup(&path, 4, 1, 2).is_some());
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn same_size_same_mtime_replacement_is_a_miss() {
let tmp = std::env::temp_dir().join(format!("cp2-sigcache-repl-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let cache = sig_cache(&tmp);
let path = tmp.join("f.bin");
std::fs::create_dir_all(&tmp).unwrap();
std::fs::write(&path, vec![b'a'; 10 * 4096]).unwrap();
let meta = std::fs::metadata(&path).unwrap();
let mtime_sec = crate::platform::fs::mtime_secs(&meta);
let mtime_nsec = crate::platform::fs::mtime_nsecs(&meta);
let size = meta.len();
cache.store(&path, size, mtime_sec, mtime_nsec, &test_sig(1));
assert!(cache.lookup(&path, size, mtime_sec, mtime_nsec).is_some());
let mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
std::fs::write(&path, vec![b'b'; 10 * 4096]).unwrap();
std::fs::File::options()
.write(true)
.open(&path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(mtime))
.unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert_eq!(meta.len(), size);
assert_eq!(crate::platform::fs::mtime_secs(&meta), mtime_sec);
assert_eq!(crate::platform::fs::mtime_nsecs(&meta), mtime_nsec);
assert!(cache.lookup(&path, size, mtime_sec, mtime_nsec).is_none());
assert!(!cache.entry_path(&path).exists());
let _ = std::fs::remove_dir_all(&tmp);
}
#[test]
fn signature_is_content_keyed_by_stat() {
let tmp = std::env::temp_dir().join(format!("cp2-sigcache-stat-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
std::fs::create_dir_all(&tmp).unwrap();
let path = tmp.join("f.bin");
std::fs::write(&path, vec![0u8; 4096]).unwrap();
let meta = std::fs::metadata(&path).unwrap();
let (sec, nsec) = (crate::platform::fs::mtime_secs(&meta), crate::platform::fs::mtime_nsecs(&meta));
let cache = sig_cache(&tmp);
cache.store(&path, meta.len(), sec, nsec, &test_sig(9));
let got = cache.lookup(&path, meta.len(), sec, nsec);
assert_eq!(got.map(|s| s.chunks[0].offset), Some(9));
let ft = std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH);
std::fs::File::options().write(true).open(&path).unwrap().set_times(ft).unwrap();
let meta = std::fs::metadata(&path).unwrap();
assert!(cache.lookup(&path, meta.len(), crate::platform::fs::mtime_secs(&meta), crate::platform::fs::mtime_nsecs(&meta)).is_none());
let _ = std::fs::remove_dir_all(&tmp);
}
}