use std::fs;
use std::io::Read;
use std::path::Path;
use tracing::debug;
use super::hex::is_sha256_hex;
use super::types::{CacheMeta, MAX_CACHE_META_BYTES};
pub(super) fn read_meta_file(path: &Path) -> Option<CacheMeta> {
let len = fs::metadata(path).ok()?.len();
if len > MAX_CACHE_META_BYTES {
debug!(
path = %path.display(),
len,
cap = MAX_CACHE_META_BYTES,
"cache meta exceeds cap"
);
return None;
}
let n = usize::try_from(len).ok()?;
let mut buf = Vec::new();
if let Err(e) = buf.try_reserve_exact(n) {
debug!(
path = %path.display(),
len,
error = %e,
"cache meta reserve failed"
);
return None;
}
buf.resize(n, 0);
{
let mut file = fs::File::open(path).ok()?;
if file.read_exact(&mut buf).is_err() {
return None;
}
}
let meta: CacheMeta = serde_json::from_slice(&buf).ok()?;
if !meta.digests_look_valid() {
debug!(
path = %path.display(),
"cache meta digests are not sha256 hex"
);
return None;
}
if meta.parser_version.len() > 32 || !meta.parser_version.is_ascii() {
debug!(path = %path.display(), "cache meta parser_version invalid");
return None;
}
if meta.url.is_empty() || meta.final_url.is_empty() || meta.accept.is_empty() {
debug!(path = %path.display(), "cache meta missing required string fields");
return None;
}
debug_assert!(is_sha256_hex(&meta.input_sha256));
Some(meta)
}