use std::time::Duration;
use sisa_caching_core::{
cache::PurgeableStore,
worker::{CancellationToken, WorkerService},
};
#[derive(Debug)]
pub struct PurgeWorker<C> {
cache: C,
interval: Option<Duration>,
}
impl<C: PurgeableStore> PurgeWorker<C> {
pub fn new(cache: C) -> Self {
let interval = cache
.purge_interval()
.filter(|interval| !interval.is_zero());
Self { cache, interval }
}
}
impl<C> WorkerService for PurgeWorker<C>
where
C: PurgeableStore + Send + 'static,
{
fn name(&self) -> &'static str {
"in-memory-cache-purge-worker"
}
async fn run(self, _shutdown: CancellationToken) {
let Some(interval) = self.interval else {
return;
};
loop {
tokio::time::sleep(interval).await;
self.cache.purge();
}
}
}
#[cfg(test)]
mod tests {
use sisa_caching_core::{CacheKey, CacheOptions, CacheStore, settings::MAX_TTL_SECS};
use sisa_caching_testing::ManualClock;
use super::*;
use crate::{settings::InMemoryCacheSettings, store::InMemoryCacheStore};
fn purging_every(secs: Option<u64>) -> InMemoryCacheStore {
InMemoryCacheStore::new("app")
.unwrap()
.with_settings(InMemoryCacheSettings {
purge_interval_secs: secs,
..InMemoryCacheSettings::default()
})
.unwrap()
}
#[tokio::test(start_paused = true)]
async fn the_worker_purges_every_interval() {
let clock = ManualClock::new();
let store = purging_every(Some(60)).with_clock(clock.clone());
let one_second = CacheOptions::with_ttl(Duration::from_secs(1));
store
.set(&CacheKey::new("user", 1).unwrap(), 1_u32, one_second)
.await
.unwrap();
clock.advance(Duration::from_secs(1));
let running = tokio::spawn(PurgeWorker::new(store.clone()).run(CancellationToken::new()));
tokio::time::sleep(Duration::from_secs(61)).await;
assert_eq!(store.purge(), 0, "the worker already purged it");
running.abort();
}
#[tokio::test]
async fn without_an_interval_the_worker_stops_at_once() {
for secs in [None, Some(0)] {
let worker = PurgeWorker::new(purging_every(secs));
tokio::time::timeout(Duration::from_secs(1), worker.run(CancellationToken::new()))
.await
.expect("the worker returns");
}
}
#[tokio::test(start_paused = true)]
async fn the_longest_interval_waits_without_panicking() {
let worker = PurgeWorker::new(purging_every(Some(MAX_TTL_SECS)));
let waited = tokio::time::timeout(
Duration::from_secs(3600),
worker.run(CancellationToken::new()),
)
.await;
assert!(waited.is_err(), "the worker keeps waiting");
}
}