Skip to content

The platform for continuously improving AI agents.

4.7 KB
Raw Blame
use std::{
    collections::HashMap,
    future::Future,
    sync::{Arc, Mutex},
    time::{Duration, Instant},
};

use tokio::sync::Semaphore;

pub const DEFAULT_MAX_CONCURRENT_READS: usize = 4;
const MAX_CACHE_ENTRIES: usize = 256;

/// Reads `OTEL_READ_CACHE_TTL_MS` from the environment. Defaults to `0` (disabled)
/// so unit tests always observe fresh reads immediately unless explicitly configured.
pub fn read_cache_ttl_from_env() -> Duration {
    let ms = std::env::var("OTEL_READ_CACHE_TTL_MS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .unwrap_or(0);
    Duration::from_millis(ms)
}

/// Reads `OTEL_MAX_CONCURRENT_READS` from the environment (default `4`, clamped `1..=64`).
pub fn max_concurrent_reads_from_env() -> usize {
    std::env::var("OTEL_MAX_CONCURRENT_READS")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(DEFAULT_MAX_CONCURRENT_READS)
        .clamp(1, 64)
}

/// Bounded in-memory TTL cache with semaphore-gated double-checked loading to prevent
/// concurrent read-storms against DuckDB.
pub struct ReadCache<V> {
    ttl: Duration,
    entries: Mutex<HashMap<Vec<u8>, (Instant, V)>>,
}

impl<V: Clone> ReadCache<V> {
    pub fn new(ttl: Duration) -> Self {
        Self {
            ttl,
            entries: Mutex::new(HashMap::new()),
        }
    }

    pub fn get(&self, key: &[u8]) -> Option<V> {
        if self.ttl.is_zero() {
            return None;
        }
        let now = Instant::now();
        let guard = self.entries.lock().unwrap_or_else(|p| p.into_inner());
        guard
            .get(key)
            .filter(|(expires_at, _)| *expires_at > now)
            .map(|(_, value)| value.clone())
    }

    pub fn insert(&self, key: Vec<u8>, value: V) {
        if self.ttl.is_zero() {
            return;
        }
        let now = Instant::now();
        let mut guard = self.entries.lock().unwrap_or_else(|p| p.into_inner());
        if guard.len() >= MAX_CACHE_ENTRIES {
            guard.retain(|_, (expires_at, _)| *expires_at > now);
            if guard.len() >= MAX_CACHE_ENTRIES {
                guard.clear();
            }
        }
        guard.insert(key, (now + self.ttl, value));
    }

    pub fn clear(&self) {
        if self.ttl.is_zero() {
            return;
        }
        let mut guard = self.entries.lock().unwrap_or_else(|p| p.into_inner());
        guard.clear();
    }

    pub async fn get_or_load<E, F, Fut>(
        &self,
        semaphore: &Arc<Semaphore>,
        key: Vec<u8>,
        load: F,
    ) -> Result<V, E>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<V, E>>,
    {
        if let Some(hit) = self.get(&key) {
            return Ok(hit);
        }
        let _permit = semaphore
            .acquire()
            .await
            .expect("read concurrency semaphore is never closed");
        if let Some(hit) = self.get(&key) {
            return Ok(hit);
        }
        let value = load().await?;
        self.insert(key, value.clone());
        Ok(value)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    #[tokio::test]
    async fn disabled_when_ttl_is_zero() {
        let cache: ReadCache<usize> = ReadCache::new(Duration::ZERO);
        let sem = Arc::new(Semaphore::new(2));
        let calls = Arc::new(AtomicUsize::new(0));

        for expected in 1..=2 {
            let c = Arc::clone(&calls);
            let val = cache
                .get_or_load(&sem, b"k".to_vec(), move || async move {
                    Ok::<_, ()>(c.fetch_add(1, Ordering::SeqCst) + 1)
                })
                .await
                .unwrap();
            assert_eq!(val, expected);
        }
    }

    #[tokio::test]
    async fn coalesces_and_serves_cached_value_within_ttl() {
        let cache = Arc::new(ReadCache::new(Duration::from_secs(5)));
        let sem = Arc::new(Semaphore::new(1));
        let calls = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for _ in 0..8 {
            let cache = Arc::clone(&cache);
            let sem = Arc::clone(&sem);
            let calls = Arc::clone(&calls);
            handles.push(tokio::spawn(async move {
                cache
                    .get_or_load(&sem, b"same-key".to_vec(), move || async move {
                        tokio::time::sleep(Duration::from_millis(15)).await;
                        Ok::<_, ()>(calls.fetch_add(1, Ordering::SeqCst) + 1)
                    })
                    .await
                    .unwrap()
            }));
        }

        for h in handles {
            assert_eq!(h.await.unwrap(), 1);
        }
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }
}