add cache ttl handling to cleanup

This commit is contained in:
slonkazoid 2024-12-29 13:37:48 +03:00
parent 9b96b09ee0
commit c9bbb5234e
Signed by: slonk
SSH key fingerprint: SHA256:tbZfJX4IOvZ0LGWOWu5Ijo8jfMPi78TU7x1VoEeCIjM
3 changed files with 13 additions and 4 deletions

View file

@ -307,7 +307,7 @@ impl PostManager for Blag {
async fn cleanup(&self) { async fn cleanup(&self) {
if let Some(cache) = &self.cache { if let Some(cache) = &self.cache {
cache cache
.retain(|key, value| { .cleanup(|key, value| {
let mtime = std::fs::metadata( let mtime = std::fs::metadata(
self.root self.root
.join(self.as_raw(&key.name).unwrap_or_else(|| unreachable!())), .join(self.as_raw(&key.name).unwrap_or_else(|| unreachable!())),

View file

@ -56,7 +56,7 @@ impl Cache {
mtime <= cached.mtime mtime <= cached.mtime
&& self && self
.ttl .ttl
.is_some_and(|ttl| cached.cached_at + u64::from(ttl) as u128 >= now()) .is_none_or(|ttl| cached.cached_at + u64::from(ttl) as u128 >= now())
} }
#[instrument(level = "debug", skip(self), fields(entry_mtime))] #[instrument(level = "debug", skip(self), fields(entry_mtime))]
@ -158,7 +158,6 @@ impl Cache {
r r
} }
#[instrument(level = "debug", name = "cleanup", skip_all)]
pub async fn retain(&self, predicate: impl Fn(&CacheKey, &CacheValue) -> bool) { pub async fn retain(&self, predicate: impl Fn(&CacheKey, &CacheValue) -> bool) {
let old_size = self.map.len(); let old_size = self.map.len();
let mut i = 0; let mut i = 0;
@ -181,6 +180,16 @@ impl Cache {
debug!("removed {i} entries ({old_size} -> {new_size} entries)"); debug!("removed {i} entries ({old_size} -> {new_size} entries)");
} }
#[instrument(level = "debug", skip_all)]
pub async fn cleanup(&self, predicate: impl Fn(&CacheKey, &CacheValue) -> bool) {
self.retain(|k, v| {
self.ttl
.is_none_or(|ttl| v.cached_at + u64::from(ttl) as u128 >= now())
&& predicate(k, v)
})
.await
}
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.map.len() self.map.len()
} }

View file

@ -297,7 +297,7 @@ impl PostManager for MarkdownPosts {
async fn cleanup(&self) { async fn cleanup(&self) {
if let Some(cache) = &self.cache { if let Some(cache) = &self.cache {
cache cache
.retain(|CacheKey { name, extra }, value| { .cleanup(|CacheKey { name, extra }, value| {
// nuke entries with different render options // nuke entries with different render options
if self.render_hash != *extra { if self.render_hash != *extra {
return false; return false;