use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::Path;
use std::sync::{PoisonError, RwLock};
use bytes::Bytes;
use super::Error;
const DEFAULT_HTML_CACHE_MAX_BYTES: i64 = 64 << 20;
pub(super) struct Snapshot {
files: HashSet<String>,
html_max: i64,
html: RwLock<HtmlCache>,
}
#[derive(Default)]
struct HtmlCache {
entries: HashMap<String, Bytes>,
bytes: i64,
}
impl Snapshot {
pub(super) fn build(root: &Path, html_max: i64) -> Result<Self, Error> {
let resolved = fs::canonicalize(root).map_err(|e| Error::Index(root.to_path_buf(), e))?;
let mut files = HashSet::new();
walk(&resolved, "", &mut files).map_err(|e| Error::Index(root.to_path_buf(), e))?;
let html_max = if html_max == 0 {
DEFAULT_HTML_CACHE_MAX_BYTES
} else {
html_max
};
Ok(Self {
files,
html_max,
html: RwLock::default(),
})
}
pub(super) fn contains(&self, key: &str) -> bool {
self.files.contains(key)
}
pub(super) fn cached_html(&self, key: &str) -> Option<Bytes> {
self.html
.read()
.unwrap_or_else(PoisonError::into_inner)
.entries
.get(key)
.cloned()
}
pub(super) fn store_html(&self, key: &str, body: Bytes) -> Bytes {
let mut cache = self.html.write().unwrap_or_else(PoisonError::into_inner);
if let Some(existing) = cache.entries.get(key) {
return existing.clone();
}
let len = i64::try_from(body.len()).unwrap_or(i64::MAX);
if cache.bytes.saturating_add(len) <= self.html_max {
cache.bytes += len;
cache.entries.insert(key.to_owned(), body.clone());
}
body
}
}
fn walk(dir: &Path, prefix: &str, files: &mut HashSet<String>) -> io::Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let key = format!("{prefix}/{name}");
let ft = entry.file_type()?;
if ft.is_dir() {
walk(&entry.path(), &key, files)?;
} else if ft.is_symlink() {
if fs::metadata(entry.path()).is_ok_and(|m| m.is_file()) {
files.insert(key);
}
} else if ft.is_file() {
files.insert(key);
}
}
Ok(())
}