zenmanage 1.0.0

Official Zenmanage feature flags SDK for Rust
Documentation
use std::{collections::HashMap, sync::Arc, time::Duration};

use tokio::sync::RwLock;

use super::{CacheBackend, CacheFuture};

#[derive(Clone, Debug)]
struct CacheEntry {
    value: String,
    /// `None` when the TTL is too large to ever pass.
    expires_at: Option<std::time::Instant>,
}

/// In-memory cache backend suitable for most server runtimes.
#[derive(Clone, Debug, Default)]
pub struct MemoryCache {
    store: Arc<RwLock<HashMap<String, CacheEntry>>>,
}

impl MemoryCache {
    /// An empty cache.
    pub fn new() -> Self {
        Self::default()
    }
}

impl CacheBackend for MemoryCache {
    fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<String>> {
        Box::pin(async move {
            let mut store = self.store.write().await;

            let expired = store
                .get(key)
                .and_then(|entry| entry.expires_at)
                .is_some_and(|expires_at| std::time::Instant::now() >= expires_at);

            if expired {
                store.remove(key);
                return Ok(None);
            }

            Ok(store.get(key).map(|entry| entry.value.clone()))
        })
    }

    fn set<'a>(&'a self, key: &'a str, value: String, ttl: Duration) -> CacheFuture<'a, ()> {
        Box::pin(async move {
            let entry = CacheEntry {
                value,
                expires_at: std::time::Instant::now().checked_add(ttl),
            };

            self.store.write().await.insert(key.to_owned(), entry);
            Ok(())
        })
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[tokio::test]
    async fn stores_and_expires_values() {
        let cache = MemoryCache::new();
        cache
            .set("rules", "cached".to_owned(), Duration::from_millis(5))
            .await
            .expect("set");
        assert_eq!(
            cache.get("rules").await.expect("get"),
            Some("cached".to_owned())
        );

        tokio::time::sleep(Duration::from_millis(7)).await;
        assert_eq!(cache.get("rules").await.expect("get"), None);
    }
}