trelent-hyok 0.1.12

A Rust library implementing Hold Your Own Key (HYOK) encryption patterns with support for multiple cloud providers
Documentation
use crate::cache::DEKCacheTrait;
use crate::error::cache::CacheError;
use mini_moka::sync::Cache;
use std::time::Duration;

/// A [`MokaCache`] uses the [mini-moka](https://crates.io/crates/mini-moka) library for caching,
/// implementing the [`DEKCacheTrait`] for storing and retrieving data.
pub struct MokaCache {
    pub(crate) cache: Cache<String, Vec<u8>>,
}

impl MokaCache {
    /// Creates a new [`MokaCache`] with the specified capacity, time-to-live (TTL),
    /// and time-to-idle (TTI) durations.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The maximum number of items that the cache can hold.
    /// * `ttl` - The duration after which a cached entry will be removed, regardless of access.
    /// * `tti` - The duration of inactivity after which a cached entry will be removed.
    ///
    /// # Returns
    ///
    /// A [`MokaCache`] instance configured with the provided cache settings.
    pub fn new(capacity: u64, ttl: Duration, tti: Duration) -> Self {
        let cache = Cache::builder()
            .max_capacity(capacity)
            .time_to_live(ttl)
            .time_to_idle(tti)
            .build();
        MokaCache { cache }
    }
}

impl DEKCacheTrait for MokaCache {
    type Identifier = String;

    /// Retrieves data from the cache for the provided key by using its hex-encoded value.
    ///
    /// # Arguments
    ///
    /// * `k` - A reference to the string key that will be hex-encoded to look up the cached data.
    ///
    /// # Returns
    ///
    /// An [`Option<Vec<u8>>`] containing the cached data if it exists, or `None` if the key is not found.
    fn get(&self, k: &String) -> Option<Vec<u8>> {
        self.cache.get(&hex::encode(k))
    }

    /// Stores data in the cache for the given key by hex-encoding the key.
    ///
    /// # Arguments
    ///
    /// * `k` - A string key under which the value should be stored (will be hex-encoded).
    /// * `v` - A vector of bytes representing the data to be cached.
    ///
    /// # Returns
    ///
    /// A [`Result<Vec<u8>, CacheError>`] containing the stored data upon success,
    /// or a [`CacheError`] if something went wrong.
    fn set(&self, k: String, v: Vec<u8>) -> Result<Vec<u8>, CacheError> {
        self.cache.insert(hex::encode(k), v.clone());
        Ok(v)
    }
}