Skip to main content

kape/
backend.rs

1use std::{hash::Hash, sync::Arc};
2
3use crate::{CacheEntry, KapeResult, SetItem, validate_set_items};
4
5/// A typed cache backend implementation.
6///
7/// Implementations must represent misses as `None`, preserve exact remaining
8/// TTL and read positions, and reject duplicate batch-write keys before
9/// mutation. Apply `#[async_trait::async_trait]` to each implementation block.
10#[async_trait::async_trait]
11pub trait CacheBackend<K, V>: Send + Sync
12where
13    K: Sync,
14    V: Send + Sync,
15{
16    /// Queries one key.
17    async fn get(&self, key: &K) -> KapeResult<Option<CacheEntry<V>>>;
18
19    /// Stores or immediately invalidates one key using a millisecond TTL.
20    async fn set(&self, key: &K, value: Arc<V>, ttl: i64) -> KapeResult<()>;
21
22    /// Removes one key.
23    async fn remove(&self, key: &K) -> KapeResult<()>;
24
25    /// Clears entries owned by this backend instance.
26    async fn clear(&self) -> KapeResult<()>;
27
28    /// Queries multiple keys while preserving input order and duplicates.
29    async fn get_many(&self, keys: &[&K]) -> KapeResult<Vec<Option<CacheEntry<V>>>> {
30        let mut results = Vec::with_capacity(keys.len());
31        for key in keys {
32            results.push(self.get(key).await?);
33        }
34        Ok(results)
35    }
36
37    /// Writes multiple uniquely keyed items in input order.
38    async fn set_many(&self, items: &[SetItem<&K, V>]) -> KapeResult<()>
39    where
40        K: Eq + Hash,
41    {
42        validate_set_items(items)?;
43        for item in items {
44            self.set(item.key, Arc::clone(&item.value), item.ttl)
45                .await?;
46        }
47        Ok(())
48    }
49
50    /// Removes multiple keys in input order.
51    async fn remove_many(&self, keys: &[&K]) -> KapeResult<()> {
52        for key in keys {
53            self.remove(key).await?;
54        }
55        Ok(())
56    }
57}