sisa-caching-memory 0.1.0

The in-process local store of Sisa Caching, with TTLs and an optional entry limit
Documentation
use std::time::Duration;

use sisa_caching_core::{
    cache::PurgeableStore,
    worker::{CancellationToken, WorkerService},
};

/// Drops a store's expired entries every `purge_interval_secs` of its settings. With no interval,
/// or a zero one, it stops at once.
#[derive(Debug)]
pub struct PurgeWorker<C> {
    cache: C,
    interval: Option<Duration>,
}

impl<C: PurgeableStore> PurgeWorker<C> {
    /// A worker for `cache`. It reads the store's purge interval once, here; register it on a
    /// `WorkerHost`.
    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");
    }
}