use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::errors::{ConfigError, ResourceError};
const STALE_PARTIAL_AGE: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Debug)]
pub struct CachedBlob {
pub path: PathBuf,
pub size: u64,
pub mime_type: Option<String>,
pub file: tokio::fs::File,
}
#[derive(Debug)]
pub struct BlobCache {
dir: Option<PathBuf>,
configured: Option<PathBuf>,
max_bytes: u64,
}
impl BlobCache {
#[must_use]
pub fn new(dir: Option<PathBuf>, max_bytes: u64) -> Self {
let configured = dir.clone();
let dir = dir.filter(|_| max_bytes > 0);
Self {
dir,
configured,
max_bytes,
}
}
pub fn from_env() -> Result<Self, ConfigError> {
Self::from_lookup(crate::context::env_value)
}
pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
let max_bytes = crate::context::parse_number(
"ATPMCP_BLOB_CACHE_MAX_BYTES",
lookup("ATPMCP_BLOB_CACHE_MAX_BYTES").as_deref(),
0,
crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES,
)?
.unwrap_or(crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES);
let dir = lookup("ATPMCP_BLOB_CACHE_DIR")
.map(PathBuf::from)
.or_else(|| dirs::cache_dir().map(|dir| dir.join("atpmcp").join("blobs")));
if dir.is_none() {
tracing::warn!("No cache directory available; blob caching is disabled.");
}
Ok(Self::new(dir, max_bytes))
}
#[must_use]
pub fn is_enabled(&self) -> bool {
self.dir.is_some()
}
#[must_use]
pub fn admits(&self, size: u64) -> bool {
self.is_enabled() && size <= self.max_bytes
}
#[must_use]
pub fn dir(&self) -> Option<&Path> {
self.dir.as_deref()
}
pub async fn get(&self, cid: &str) -> Option<CachedBlob> {
let path = self.path_for(cid)?;
let (size, computed, file) = hash_file(&path).await.ok()?;
if computed != cid {
tracing::warn!(
expected = %cid,
computed = %computed,
"Cached blob failed verification; discarding."
);
let _ = tokio::fs::remove_file(&path).await;
let _ = tokio::fs::remove_file(path.with_extension("type")).await;
return None;
}
let mime_type = tokio::fs::read_to_string(path.with_extension("type"))
.await
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
Some(CachedBlob {
path,
size,
mime_type,
file,
})
}
pub async fn put(
&self,
cid: &str,
data: &[u8],
mime_type: Option<&str>,
) -> Result<(), ResourceError> {
let Some(target) = self.prepare_write(cid, Some(data.len() as u64)).await? else {
return Ok(());
};
tokio::fs::write(&target.temp_path, data)
.await
.map_err(|error| ResourceError::CacheFailure {
reason: format!("could not write {}: {error}", target.temp_path.display()),
})?;
self.commit_write(&target, mime_type).await
}
pub async fn prepare_write(
&self,
cid: &str,
size: Option<u64>,
) -> Result<Option<WriteTarget>, ResourceError> {
if size.is_some_and(|size| !self.admits(size)) {
return Ok(None);
}
let Some(final_path) = self.path_for(cid) else {
return Ok(None);
};
let Some(parent) = final_path.parent() else {
return Ok(None);
};
tokio::fs::create_dir_all(parent)
.await
.map_err(|error| ResourceError::CacheFailure {
reason: format!("could not create {}: {error}", parent.display()),
})?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ =
tokio::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).await;
}
let temp_path = parent.join(temp_name(cid));
Ok(Some(WriteTarget {
temp_path,
final_path,
}))
}
pub async fn commit_write(
&self,
target: &WriteTarget,
mime_type: Option<&str>,
) -> Result<(), ResourceError> {
tokio::fs::rename(&target.temp_path, &target.final_path)
.await
.map_err(|error| ResourceError::CacheFailure {
reason: format!(
"could not rename into {}: {error}",
target.final_path.display()
),
})?;
if let Some(mime_type) = mime_type {
let _ = tokio::fs::write(target.final_path.with_extension("type"), mime_type).await;
}
self.prune(Some(&target.final_path)).await;
Ok(())
}
pub async fn abort_write(&self, target: &WriteTarget) {
let _ = tokio::fs::remove_file(&target.temp_path).await;
}
#[must_use]
pub fn path_for(&self, cid: &str) -> Option<PathBuf> {
let dir = self.dir.as_ref()?;
if !is_safe_key(cid) {
tracing::warn!(cid = %cid, "Refusing to build a cache path from an unsafe key.");
return None;
}
Some(dir.join(cid))
}
pub async fn sweep(&self) -> usize {
let Some(dir) = self.configured.as_ref() else {
return 0;
};
let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
return 0;
};
let clear = !self.is_enabled();
let (mut partials, mut committed) = (0usize, 0usize);
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let Some(kind) = name.to_str().and_then(entry_kind) else {
continue;
};
let Ok(metadata) = entry.metadata().await else {
continue;
};
if !metadata.is_file() {
continue;
}
let remove = match kind {
EntryKind::Partial => metadata
.modified()
.ok()
.and_then(|modified| modified.elapsed().ok())
.is_some_and(|age| age > STALE_PARTIAL_AGE),
EntryKind::Blob | EntryKind::ContentType => clear,
};
if !remove || tokio::fs::remove_file(entry.path()).await.is_err() {
continue;
}
if kind == EntryKind::Partial {
partials += 1;
} else {
committed += 1;
}
}
if partials > 0 {
tracing::info!(
removed = partials,
directory = %dir.display(),
"Removed abandoned partial writes from the blob cache."
);
}
if committed > 0 {
tracing::info!(
removed = committed,
directory = %dir.display(),
"ATPMCP_BLOB_CACHE_MAX_BYTES is 0; removed the blob cache's entries."
);
}
let pruned = if clear { 0 } else { self.prune(None).await };
if pruned > 0 {
tracing::info!(
removed = pruned,
directory = %dir.display(),
max_bytes = self.max_bytes,
"Pruned the blob cache to ATPMCP_BLOB_CACHE_MAX_BYTES."
);
}
partials + committed + pruned
}
async fn prune(&self, keep: Option<&Path>) -> usize {
let Some(dir) = self.dir.as_ref() else {
return 0;
};
let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
return 0;
};
let mut candidates: std::collections::BTreeMap<PathBuf, Candidate> =
std::collections::BTreeMap::new();
let mut total: u64 = 0;
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let Some(kind) = name.to_str().and_then(entry_kind) else {
continue;
};
if kind == EntryKind::Partial {
continue;
}
let Ok(metadata) = entry.metadata().await else {
continue;
};
if !metadata.is_file() {
continue;
}
let modified = metadata
.modified()
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
let path = entry.path();
let candidate = if kind == EntryKind::ContentType {
let candidate = candidates.entry(path.with_extension("")).or_default();
candidate.content_type = Some(modified);
candidate
} else {
let candidate = candidates.entry(path).or_default();
candidate.blob = Some(modified);
candidate
};
candidate.size += metadata.len();
total += metadata.len();
}
if total <= self.max_bytes {
return 0;
}
let mut candidates: Vec<(PathBuf, Candidate)> = candidates.into_iter().collect();
candidates.sort_by_key(|(_, candidate)| candidate.modified());
let mut removed = 0usize;
for (blob, candidate) in candidates {
if total <= self.max_bytes {
break;
}
if keep.is_some_and(|keep| keep == blob) {
continue;
}
let content_type = blob.with_extension("type");
if candidate.blob.is_some() {
if tokio::fs::remove_file(&blob).await.is_err() {
continue;
}
removed += 1;
if tokio::fs::remove_file(&content_type).await.is_ok() {
removed += 1;
}
} else {
if tokio::fs::remove_file(&content_type).await.is_err() {
continue;
}
removed += 1;
}
total = total.saturating_sub(candidate.size);
}
removed
}
}
#[derive(Debug, Default)]
struct Candidate {
blob: Option<std::time::SystemTime>,
content_type: Option<std::time::SystemTime>,
size: u64,
}
impl Candidate {
fn modified(&self) -> std::time::SystemTime {
self.blob
.or(self.content_type)
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
}
}
async fn hash_file(path: &Path) -> std::io::Result<(u64, String, tokio::fs::File)> {
use tokio::io::AsyncReadExt as _;
let mut file = tokio::fs::File::open(path).await?;
let mut hasher = atproto_dasl::cid::RawCidHasher::new();
let mut buffer = vec![0u8; 64 * 1024];
let mut size: u64 = 0;
loop {
let read = file.read(&mut buffer).await?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
size += read as u64;
}
Ok((size, hasher.finalize().to_string(), file))
}
#[derive(Debug, Clone)]
pub struct WriteTarget {
pub temp_path: PathBuf,
pub final_path: PathBuf,
}
fn temp_name(cid: &str) -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
format!(
"{cid}.partial-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EntryKind {
Blob,
ContentType,
Partial,
}
fn entry_kind(name: &str) -> Option<EntryKind> {
let (cid, suffix) = match name.split_once('.') {
Some((cid, suffix)) => (cid, Some(suffix)),
None => (name, None),
};
crate::blob::validate_blob_cid(cid).ok()?;
match suffix {
None => Some(EntryKind::Blob),
Some("type") => Some(EntryKind::ContentType),
Some(suffix) => {
let (pid, counter) = suffix.strip_prefix("partial-")?.split_once('-')?;
let digits = |part: &str| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit());
(digits(pid) && digits(counter)).then_some(EntryKind::Partial)
}
}
}
fn is_safe_key(key: &str) -> bool {
!key.is_empty()
&& key.len() <= 128
&& key
.chars()
.all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())
}
#[cfg(test)]
mod tests {
use super::*;
fn unique_temp_dir(prefix: &str) -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
std::env::temp_dir().join(format!(
"{prefix}-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
))
}
#[test]
fn the_cache_ceiling_is_a_whole_number_or_refused() {
let with = |value: &'static str| {
move |name: &str| (name == "ATPMCP_BLOB_CACHE_MAX_BYTES").then(|| value.to_string())
};
let error = BlobCache::from_lookup(with("512MiB")).expect_err("a unit is refused");
assert!(
matches!(
error,
ConfigError::NotANumber {
name: "ATPMCP_BLOB_CACHE_MAX_BYTES",
..
}
),
"{error}"
);
let cache = BlobCache::from_lookup(with("0")).expect("zero is a setting");
assert_eq!(cache.max_bytes, 0);
assert!(!cache.is_enabled(), "and a setting that caches nothing");
let cache = BlobCache::from_lookup(|_| None).expect("unset keeps the default");
assert_eq!(
cache.max_bytes,
crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES
);
}
fn temp_cache() -> (BlobCache, PathBuf) {
let dir = unique_temp_dir("atpmcp-cache-test");
(BlobCache::new(Some(dir.clone()), 1024 * 1024), dir)
}
#[tokio::test]
async fn round_trips_a_blob_with_its_content_type() {
let (cache, dir) = temp_cache();
let data = b"hello blob".to_vec();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, Some("text/plain")).await.unwrap();
let cached = cache.get(&cid).await.expect("blob is cached");
assert_eq!(std::fs::read(&cached.path).unwrap(), data);
assert_eq!(cached.size, data.len() as u64);
assert_eq!(cached.mime_type.as_deref(), Some("text/plain"));
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn an_entry_larger_than_one_read_verifies_across_chunks() {
let (cache, dir) = temp_cache();
let data: Vec<u8> = (0..200_000u32).map(|index| (index % 251) as u8).collect();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, None).await.unwrap();
let cached = cache.get(&cid).await.expect("a multi-chunk entry verifies");
assert_eq!(cached.size, data.len() as u64);
let mut tampered = data.clone();
tampered[150_000] ^= 1;
std::fs::write(cache.path_for(&cid).unwrap(), &tampered).unwrap();
assert!(
cache.get(&cid).await.is_none(),
"a change past the first chunk is caught"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_miss_returns_none() {
let (cache, dir) = temp_cache();
let cid = atproto_dasl::compute_raw_cid(b"absent").to_string();
assert!(cache.get(&cid).await.is_none());
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_corrupted_entry_is_rejected_and_removed() {
let (cache, dir) = temp_cache();
let data = b"original bytes".to_vec();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, None).await.unwrap();
let path = cache.path_for(&cid).unwrap();
std::fs::write(&path, b"tampered bytes").unwrap();
assert!(
cache.get(&cid).await.is_none(),
"verification must reject bytes that do not hash to the key"
);
assert!(!path.exists(), "a failed entry is discarded, not kept");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn eviction_brings_the_cache_under_budget() {
let (_, dir) = temp_cache();
let cache = BlobCache::new(Some(dir.clone()), 2048);
for index in 0..8u8 {
let data = vec![index; 512];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, None).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
let total: u64 = std::fs::read_dir(&dir)
.unwrap()
.filter_map(Result::ok)
.filter_map(|entry| entry.metadata().ok())
.map(|metadata| metadata.len())
.sum();
assert!(
total <= 2048,
"cache should be pruned to budget, got {total}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_disabled_cache_is_inert() {
let cache = BlobCache::new(None, 0);
assert!(!cache.is_enabled());
assert!(cache.put("bafkrei", b"x", None).await.is_ok());
assert!(cache.get("bafkrei").await.is_none());
}
#[test]
fn unsafe_keys_never_become_paths() {
let cache = BlobCache::new(Some(PathBuf::from("/tmp/atpmcp-test")), 1024);
for key in ["", "../escape", "a/b", "UPPER", "with.dot", "sp ace"] {
assert!(
cache.path_for(key).is_none(),
"key {key:?} must not produce a path"
);
}
assert!(cache.path_for("bafkreiabc123").is_some());
}
#[tokio::test]
async fn a_prepared_write_is_invisible_until_committed() {
let (cache, dir) = temp_cache();
let data = b"streamed bytes".to_vec();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
assert_ne!(target.temp_path, target.final_path);
tokio::fs::write(&target.temp_path, &data).await.unwrap();
assert!(
cache.get(&cid).await.is_none(),
"an uncommitted write must not be visible as a cache hit"
);
assert!(target.temp_path.exists());
assert!(!target.final_path.exists());
cache
.commit_write(&target, Some("text/plain"))
.await
.unwrap();
assert!(!target.temp_path.exists(), "the temp file is renamed away");
let cached = cache.get(&cid).await.expect("now visible");
assert_eq!(cached.path, target.final_path);
assert_eq!(std::fs::read(&cached.path).unwrap(), data);
assert_eq!(cached.mime_type.as_deref(), Some("text/plain"));
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn aborting_a_write_deletes_only_the_temp_file() {
let (cache, dir) = temp_cache();
let cid = atproto_dasl::compute_raw_cid(b"never committed").to_string();
let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
tokio::fs::write(&target.temp_path, b"never committed")
.await
.unwrap();
assert!(target.temp_path.exists());
cache.abort_write(&target).await;
assert!(!target.temp_path.exists());
assert!(cache.get(&cid).await.is_none());
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn two_concurrent_writes_of_the_same_cid_do_not_share_a_temp_name() {
let (cache, dir) = temp_cache();
let cid = atproto_dasl::compute_raw_cid(b"raced content").to_string();
let first = cache.prepare_write(&cid, None).await.unwrap().unwrap();
let second = cache.prepare_write(&cid, None).await.unwrap().unwrap();
assert_ne!(
first.temp_path, second.temp_path,
"concurrent writers of one CID must not collide on a temp name"
);
assert_eq!(first.final_path, second.final_path);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_zero_budget_stores_nothing() {
let dir = unique_temp_dir("atpmcp-cache-zero");
let cache = BlobCache::new(Some(dir.clone()), 0);
assert!(!cache.is_enabled());
assert!(cache.dir().is_none());
let data = b"nowhere to go".to_vec();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
assert!(cache.prepare_write(&cid, None).await.unwrap().is_none());
cache.put(&cid, &data, None).await.unwrap();
assert!(!dir.exists(), "nothing is written for a zero budget");
}
#[tokio::test]
async fn a_write_known_to_exceed_the_budget_is_not_prepared() {
let (_, dir) = temp_cache();
let cache = BlobCache::new(Some(dir.clone()), 16);
let cid = atproto_dasl::compute_raw_cid(b"sized").to_string();
assert!(cache.prepare_write(&cid, Some(17)).await.unwrap().is_none());
assert!(cache.prepare_write(&cid, Some(16)).await.unwrap().is_some());
assert!(
cache.prepare_write(&cid, None).await.unwrap().is_some(),
"an unknown size is let in, to be checked with `admits` once written"
);
assert!(cache.admits(16));
assert!(!cache.admits(17), "and a written size over budget is not");
assert!(
!BlobCache::new(Some(dir.clone()), 0).admits(0),
"a disabled cache admits nothing"
);
let data = vec![7u8; 17];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, None).await.unwrap();
assert!(
!cache.path_for(&cid).unwrap().exists(),
"a put larger than the budget is not stored"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_commit_never_evicts_its_own_entry() {
let (_, dir) = temp_cache();
let cache = BlobCache::new(Some(dir.clone()), 16);
let commit = |data: Vec<u8>| {
let cache = &cache;
async move {
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
let target = cache.prepare_write(&cid, None).await.unwrap().unwrap();
tokio::fs::write(&target.temp_path, &data).await.unwrap();
cache.commit_write(&target, None).await.unwrap();
target.final_path
}
};
let first = commit(vec![1u8; 32]).await;
assert!(first.exists(), "a commit keeps what it has just written");
let second = commit(vec![2u8; 32]).await;
assert!(second.exists(), "and so does the next one");
assert!(
!first.exists(),
"the next commit's prune still evicts an older entry over budget"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_prune_counts_and_evicts_only_atpmcps_entries() {
let (_, dir) = temp_cache();
std::fs::create_dir_all(&dir).unwrap();
let other = atproto_dasl::compute_raw_cid(b"not an entry").to_string();
let unrelated = [
dir.join("notes.txt"),
dir.join("notes.type"),
dir.join("bafkreinotacid"),
dir.join(format!("{other}.bak")),
];
for path in &unrelated {
std::fs::write(path, vec![0u8; 4096]).unwrap();
age(path, Duration::from_secs(2 * 24 * 60 * 60));
}
let entry = 512 + "text/plain".len() as u64;
let cache = BlobCache::new(Some(dir.clone()), 4 * entry);
let mut cids = Vec::new();
for index in 0..5u8 {
let data = vec![index; 512];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, Some("text/plain")).await.unwrap();
let written = Duration::from_secs(60 * (10 - u64::from(index)));
age(&dir.join(&cid), written);
age(&dir.join(format!("{cid}.type")), written);
cids.push(cid);
}
for path in &unrelated {
assert!(path.exists(), "{} is not atpmcp's", path.display());
}
assert!(
!dir.join(&cids[0]).exists(),
"the fifth commit evicts the oldest entry"
);
assert!(
!dir.join(format!("{}.type", cids[0])).exists(),
"and its content type with it"
);
for cid in &cids[1..] {
assert!(
cache.get(cid).await.is_some(),
"{cid} is within the budget once only atpmcp's entries count"
);
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn only_atpmcps_own_names_are_entries() {
let cid = atproto_dasl::compute_raw_cid(b"an entry").to_string();
assert_eq!(entry_kind(&cid), Some(EntryKind::Blob));
assert_eq!(
entry_kind(&format!("{cid}.type")),
Some(EntryKind::ContentType)
);
assert_eq!(entry_kind(&temp_name(&cid)), Some(EntryKind::Partial));
let record = atproto_dasl::compute_cid_for(&serde_json::json!({ "a": 1 }))
.unwrap()
.to_string();
for name in [
"notes.txt".to_string(),
"bafkreinotacid".to_string(),
cid.to_uppercase(),
record.clone(),
format!("{record}.partial-1-2"),
format!("{cid}.txt"),
format!("{cid}.partial"),
format!("{cid}.partial-1"),
format!("{cid}.partial-x-2"),
format!("{cid}.partial-1-2.bak"),
format!("{cid}.type.bak"),
] {
assert_eq!(entry_kind(&name), None, "{name} is not atpmcp's");
}
}
fn age(path: &Path, age: Duration) {
std::fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(std::time::SystemTime::now() - age)
.unwrap();
}
#[tokio::test]
async fn the_startup_sweep_removes_only_stale_partial_writes() {
let (cache, dir) = temp_cache();
let data = b"a committed entry".to_vec();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, Some("text/plain")).await.unwrap();
let two_days = Duration::from_secs(2 * 24 * 60 * 60);
age(&dir.join(&cid), two_days);
age(&dir.join(format!("{cid}.type")), two_days);
let stale = dir.join(temp_name(&cid));
let fresh = dir.join(temp_name(&cid));
let unrelated = dir.join("notes.partial-1-2");
for path in [&stale, &fresh, &unrelated] {
std::fs::write(path, b"partial bytes").unwrap();
}
age(&stale, two_days);
age(&unrelated, two_days);
assert_eq!(cache.sweep().await, 1);
assert!(!stale.exists(), "a day-old partial write is removed");
assert!(fresh.exists(), "a younger one may still be being written");
assert!(
unrelated.exists(),
"a name atpmcp never writes is left alone"
);
assert!(
cache.get(&cid).await.is_some(),
"and so is a committed entry, however old"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_zero_budget_sweep_clears_only_atpmcps_entries() {
let (cache, dir) = temp_cache();
let mut cids = Vec::new();
for data in [b"first".to_vec(), b"second".to_vec()] {
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, Some("text/plain")).await.unwrap();
cids.push(cid);
}
let stale = dir.join(temp_name(&cids[0]));
let fresh = dir.join(temp_name(&cids[0]));
std::fs::write(&stale, b"partial").unwrap();
std::fs::write(&fresh, b"partial").unwrap();
age(&stale, Duration::from_secs(2 * 24 * 60 * 60));
let other = atproto_dasl::compute_raw_cid(b"a directory").to_string();
let unrelated = [
dir.join("notes.txt"),
dir.join("bafkreinotacid"),
dir.join(format!("{}.bak", cids[1])),
];
for path in &unrelated {
std::fs::write(path, b"someone else's").unwrap();
}
std::fs::create_dir(dir.join(&other)).unwrap();
let disabled = BlobCache::new(Some(dir.clone()), 0);
assert_eq!(disabled.sweep().await, 5, "two blobs, two types, a partial");
for cid in &cids {
assert!(!dir.join(cid).exists(), "the blob {cid} is removed");
assert!(!dir.join(format!("{cid}.type")).exists());
}
assert!(!stale.exists(), "and a stale partial write");
assert!(fresh.exists(), "a fresh one may be another process's write");
for path in &unrelated {
assert!(path.exists(), "{} is not atpmcp's", path.display());
}
assert!(dir.join(&other).is_dir(), "nor is a directory");
assert!(dir.is_dir(), "the directory itself is kept");
assert_eq!(
BlobCache::new(None, 0).sweep().await,
0,
"with no directory there is nothing to sweep"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn the_startup_sweep_prunes_to_a_lowered_budget() {
let (cache, dir) = temp_cache();
let mut cids = Vec::new();
for index in 0..4u8 {
let data = vec![index; 512];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, Some("text/plain")).await.unwrap();
let written = Duration::from_secs(60 * (10 - u64::from(index)));
age(&dir.join(&cid), written);
age(&dir.join(format!("{cid}.type")), written);
cids.push(cid);
}
let unrelated = dir.join("notes.txt");
std::fs::write(&unrelated, vec![0u8; 4096]).unwrap();
age(&unrelated, Duration::from_secs(2 * 24 * 60 * 60));
let entry = 512 + "text/plain".len() as u64;
let lowered = BlobCache::new(Some(dir.clone()), 2 * entry);
assert_eq!(lowered.sweep().await, 4, "two blobs and their types");
for cid in &cids[..2] {
assert!(!dir.join(cid).exists(), "the older entry {cid} is evicted");
assert!(!dir.join(format!("{cid}.type")).exists(), "with its type");
}
for cid in &cids[2..] {
assert!(
lowered.get(cid).await.is_some(),
"{cid} is within the lowered budget"
);
}
assert!(
unrelated.exists(),
"a file atpmcp never writes is left alone"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn eviction_ignores_an_in_progress_write() {
let (_, dir) = temp_cache();
let cache = BlobCache::new(Some(dir.clone()), 512);
let data = vec![1u8; 512];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
cache.put(&cid, &data, None).await.unwrap();
let other_cid = atproto_dasl::compute_raw_cid(b"in flight").to_string();
let target = cache
.prepare_write(&other_cid, None)
.await
.unwrap()
.unwrap();
tokio::fs::write(&target.temp_path, vec![2u8; 4096])
.await
.unwrap();
cache.prune(None).await;
assert!(
target.temp_path.exists(),
"an in-progress write must survive a prune triggered elsewhere"
);
assert!(
cache.get(&cid).await.is_some(),
"the committed entry at budget should not be evicted because of an unrelated in-flight write"
);
let _ = std::fs::remove_dir_all(dir);
}
}