Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407//! The cover image cache.//!//! Cover bytes are kept on disk under [`crate::paths::Paths::covers_dir`],//! one file per URL named by the URL's SHA-256, so the shelf renders//! without refetching. The directory is capped in size; when it grows past//! the cap the least recently used files (oldest modification time, which//! a cache hit refreshes) are deleted. Concurrent requests for one URL//! share a single fetch.//!//! Covers are fetched without credentials and only from the URL given.
use std::collections::HashMap;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};use std::time::SystemTime;
use tokio::sync::OnceCell;use url::Url;
/// Default cap for the cache directory.pub const DEFAULT_MAX_BYTES: u64 = 64 * 1024 * 1024;
/// The largest single cover accepted. Real covers are a few hundred/// kilobytes; anything near this is not a cover.pub const MAX_COVER_BYTES: u64 = 10 * 1024 * 1024;
/// Why a cover could not be produced. `Clone` because one fetch's result/// is handed to every caller that waited on it.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum CoverError { /// The server answered with an error status. #[error("cover request failed with HTTP {0}")] Status(u16), /// The response was not an image. #[error("cover response is {0:?}, not an image")] NotAnImage(String), /// The response was larger than [`MAX_COVER_BYTES`]. #[error("cover is larger than {MAX_COVER_BYTES} bytes")] TooLarge, /// The request failed. #[error("cannot fetch cover: {0}")] Transport(String), /// The cover URL, or a redirect it led to, was not HTTPS. #[error(transparent)] Insecure(#[from] crate::download::secure::Insecure), /// The cache directory could not be read or written. #[error("cover cache {path}: {message}")] Io { /// The file or directory. path: PathBuf, /// The underlying error. message: String, },}
type Slot = Arc<OnceCell<Result<Arc<[u8]>, CoverError>>>;
/// A size-capped disk cache of cover images.////// Cheap to clone; clones share the in-flight request table.#[derive(Debug, Clone)]pub struct CoverCache { dir: PathBuf, max_bytes: u64, client: reqwest::Client, inflight: Arc<Mutex<HashMap<String, Slot>>>,}
impl CoverCache { /// A cache in `dir` holding at most `max_bytes`, fetching with `client` /// (which must not carry credentials). pub fn new(dir: impl Into<PathBuf>, max_bytes: u64, client: reqwest::Client) -> Self { Self { dir: dir.into(), max_bytes, client, inflight: Arc::new(Mutex::new(HashMap::new())), } }
/// The cache directory. pub fn dir(&self) -> &Path { &self.dir }
/// The cache file for `url`. pub fn path_for(&self, url: &Url) -> PathBuf { self.dir.join(key(url)) }
/// Returns the cover at `url`, from disk if cached, otherwise fetched /// and stored. Concurrent calls for the same URL share one request. /// /// # Errors /// See [`CoverError`]. Failures are not cached; a later call tries again. pub async fn get_or_fetch(&self, url: &Url) -> Result<Arc<[u8]>, CoverError> { let k = key(url); let slot: Slot = { let mut map = self.lock(); Arc::clone(map.entry(k.clone()).or_default()) }; let result = slot .get_or_init(|| self.load_or_fetch(url, &k)) .await .clone(); let mut map = self.lock(); if map.get(&k).is_some_and(|s| Arc::ptr_eq(s, &slot)) { map.remove(&k); } result }
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, Slot>> { // The map only holds Arcs; a panic mid-update cannot tear it. self.inflight .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) }
async fn load_or_fetch(&self, url: &Url, k: &str) -> Result<Arc<[u8]>, CoverError> { let path = self.dir.join(k); match tokio::fs::read(&path).await { Ok(bytes) => { touch(&path); return Ok(bytes.into()); } Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(io_err(&path, &e)), } let bytes = self.fetch(url).await?; let to_write = bytes.clone(); let dir = self.dir.clone(); let max = self.max_bytes; let write_path = path.clone(); tokio::task::spawn_blocking(move || -> Result<(), CoverError> { crate::fsutil::write_atomic(&write_path, &to_write, None) .map_err(|e| io_err(&write_path, &e))?; evict(&dir, max, &write_path).map_err(|e| io_err(&dir, &e)) }) .await .map_err(|e| CoverError::Io { path, message: e.to_string(), })??; Ok(bytes) }
async fn fetch(&self, url: &Url) -> Result<Arc<[u8]>, CoverError> { use futures_util::StreamExt; crate::download::secure::require_https(url)?; let response = self .client .get(url.clone()) .send() .await .map_err(|e| CoverError::Transport(e.to_string()))?; crate::download::secure::require_https(response.url())?; if !response.status().is_success() { return Err(CoverError::Status(response.status().as_u16())); } let content_type = response .headers() .get(reqwest::header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .unwrap_or("") .to_owned(); if !content_type .trim_start() .to_ascii_lowercase() .starts_with("image/") { return Err(CoverError::NotAnImage(content_type)); } if response .content_length() .is_some_and(|n| n > MAX_COVER_BYTES) { return Err(CoverError::TooLarge); } let mut out = Vec::new(); let mut stream = response.bytes_stream(); while let Some(chunk) = stream.next().await { let chunk = chunk.map_err(|e| CoverError::Transport(e.to_string()))?; if (out.len() + chunk.len()) as u64 > MAX_COVER_BYTES { return Err(CoverError::TooLarge); } out.extend_from_slice(&chunk); } Ok(out.into()) }}
fn key(url: &Url) -> String { crate::download::verify::sha256_bytes(url.as_str().as_bytes())}
fn io_err(path: &Path, e: &dyn std::fmt::Display) -> CoverError { CoverError::Io { path: path.to_path_buf(), message: e.to_string(), }}
/// Marks a cache hit as recently used. Failing only weakens LRU order, so/// it is logged rather than surfaced.fn touch(path: &Path) { let result = std::fs::File::options() .write(true) .open(path) .and_then(|f| f.set_modified(SystemTime::now())); if let Err(e) = result { tracing::debug!(path = %path.display(), error = %e, "cannot refresh cover mtime"); }}
/// Deletes the least recently used files until the directory fits in/// `max_bytes`. `keep` (the file just written) is never deleted.fn evict(dir: &Path, max_bytes: u64, keep: &Path) -> std::io::Result<()> { let mut files = Vec::new(); let mut total = 0u64; for entry in std::fs::read_dir(dir)? { let entry = entry?; let meta = entry.metadata()?; if !meta.is_file() || entry.file_name().to_string_lossy().starts_with(".libbui-") { continue; } total += meta.len(); files.push((meta.modified()?, meta.len(), entry.path())); } if total <= max_bytes { return Ok(()); } files.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2))); for (_, len, path) in files { if total <= max_bytes { break; } if path == keep { continue; } match std::fs::remove_file(&path) { Ok(()) => total -= len, Err(e) if e.kind() == std::io::ErrorKind::NotFound => total -= len, Err(e) => return Err(e), } } Ok(())}
#[cfg(test)]mod tests { #![allow(clippy::unwrap_used)] use super::*; use std::time::Duration; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate};
fn jpeg(n: usize) -> Vec<u8> { let mut v = vec![0xFF, 0xD8, 0xFF]; v.resize(n, 7); v }
async fn server_with(route: &str, body: Vec<u8>, delay_ms: u64) -> MockServer { let server = MockServer::start().await; Mock::given(method("GET")) .and(path(route)) .respond_with( ResponseTemplate::new(200) .insert_header("content-type", "image/jpeg") .set_body_bytes(body) .set_delay(Duration::from_millis(delay_ms)), ) .mount(&server) .await; server }
#[tokio::test] async fn fetches_once_then_serves_from_disk() { let dir = tempfile::tempdir().unwrap(); let server = server_with("/c.jpg", jpeg(100), 0).await; let cache = CoverCache::new(dir.path(), DEFAULT_MAX_BYTES, reqwest::Client::new()); let url = Url::parse(&format!("{}/c.jpg", server.uri())).unwrap(); let a = cache.get_or_fetch(&url).await.unwrap(); let b = cache.get_or_fetch(&url).await.unwrap(); assert_eq!(&*a, jpeg(100).as_slice()); assert_eq!(a, b); assert_eq!(server.received_requests().await.unwrap().len(), 1); assert!(cache.path_for(&url).exists()); }
#[tokio::test] async fn a_plain_http_cover_is_refused_without_a_request() { let dir = tempfile::tempdir().unwrap(); let cache = CoverCache::new(dir.path(), DEFAULT_MAX_BYTES, reqwest::Client::new()); let url = Url::parse("http://covers.example/c.jpg").unwrap(); assert_eq!( cache.get_or_fetch(&url).await, Err(CoverError::Insecure(crate::download::secure::Insecure { host: Some("covers.example".to_owned()), })) ); assert!(!cache.path_for(&url).exists()); }
#[tokio::test] async fn concurrent_requests_share_one_fetch() { let dir = tempfile::tempdir().unwrap(); let server = server_with("/c.jpg", jpeg(100), 200).await; let cache = CoverCache::new(dir.path(), DEFAULT_MAX_BYTES, reqwest::Client::new()); let url = Url::parse(&format!("{}/c.jpg", server.uri())).unwrap(); let results = futures_util::future::join_all((0..8).map(|_| cache.get_or_fetch(&url))).await; assert!(results.iter().all(Result::is_ok)); assert_eq!(server.received_requests().await.unwrap().len(), 1); assert!(cache.lock().is_empty()); }
#[tokio::test] async fn errors_are_reported_and_not_cached() { let dir = tempfile::tempdir().unwrap(); let server = MockServer::start().await; Mock::given(path("/missing.jpg")) .respond_with(ResponseTemplate::new(404)) .mount(&server) .await; Mock::given(path("/page.jpg")) .respond_with( ResponseTemplate::new(200) .insert_header("content-type", "text/html") .set_body_string("<html>"), ) .mount(&server) .await; let cache = CoverCache::new(dir.path(), DEFAULT_MAX_BYTES, reqwest::Client::new()); let missing = Url::parse(&format!("{}/missing.jpg", server.uri())).unwrap(); let page = Url::parse(&format!("{}/page.jpg", server.uri())).unwrap(); assert_eq!( cache.get_or_fetch(&missing).await.unwrap_err(), CoverError::Status(404) ); assert!(matches!( cache.get_or_fetch(&page).await.unwrap_err(), CoverError::NotAnImage(_) )); assert!(!cache.path_for(&missing).exists()); cache.get_or_fetch(&missing).await.unwrap_err(); assert_eq!(server.received_requests().await.unwrap().len(), 3); }
#[test] fn eviction_removes_least_recently_used_first() { let dir = tempfile::tempdir().unwrap(); let base = SystemTime::now() - Duration::from_secs(1000); for (i, name) in ["old", "mid", "new"].iter().enumerate() { let p = dir.path().join(name); std::fs::write(&p, vec![0u8; 100]).unwrap(); let f = std::fs::File::options().write(true).open(&p).unwrap(); f.set_modified(base + Duration::from_secs(i as u64 * 10)) .unwrap(); } let keep = dir.path().join("fresh"); std::fs::write(&keep, vec![0u8; 100]).unwrap(); evict(dir.path(), 250, &keep).unwrap(); assert!(!dir.path().join("old").exists()); assert!(!dir.path().join("mid").exists()); assert!(dir.path().join("new").exists()); assert!(keep.exists()); }
#[tokio::test] async fn cache_hit_refreshes_lru_position() { let dir = tempfile::tempdir().unwrap(); let server = MockServer::start().await; for name in ["/a.jpg", "/b.jpg", "/c.jpg"] { Mock::given(path(name)) .respond_with( ResponseTemplate::new(200) .insert_header("content-type", "image/jpeg") .set_body_bytes(jpeg(100)), ) .mount(&server) .await; } let url = |n: &str| Url::parse(&format!("{}/{n}.jpg", server.uri())).unwrap(); let cache = CoverCache::new(dir.path(), 250, reqwest::Client::new()); cache.get_or_fetch(&url("a")).await.unwrap(); cache.get_or_fetch(&url("b")).await.unwrap(); // Age both, then use "a" again so "b" becomes the eviction victim. for n in ["a", "b"] { let f = std::fs::File::options() .write(true) .open(cache.path_for(&url(n))) .unwrap(); let age = if n == "a" { 100 } else { 50 }; f.set_modified(SystemTime::now() - Duration::from_secs(age)) .unwrap(); } cache.get_or_fetch(&url("a")).await.unwrap(); cache.get_or_fetch(&url("c")).await.unwrap(); assert!(cache.path_for(&url("a")).exists()); assert!(!cache.path_for(&url("b")).exists()); assert!(cache.path_for(&url("c")).exists()); }}