#![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, signature): (u64, u64, u32, Signature) =
postcard::from_bytes(&bytes).ok()?;
if f_size != file_size || f_mtime_sec != mtime_sec || f_mtime_nsec != mtime_nsec {
return None;
}
Some(signature)
}
fn store(
&self,
path: &Path,
file_size: u64,
mtime_sec: u64,
mtime_nsec: u32,
signature: &Signature,
) {
let Ok(bytes) = postcard::to_allocvec(&(file_size, mtime_sec, mtime_nsec, 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 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 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);
}
}