secra-memory 0.1.1

A unified memory cache management library for plugin systems, built on top of moka
Documentation
/// 内存缓存配置
use std::time::Duration;

/// 内存缓存配置结构
#[derive(Debug, Clone)]
pub struct MemoryConfig {
    /// 最大容量(条目数)
    pub max_capacity: u64,

    /// 初始容量(条目数)
    pub initial_capacity: usize,

    /// 默认 TTL(过期时间)
    pub default_ttl: Duration,

    /// TTL 随机化范围(防缓存雪崩)
    /// 实际 TTL 会在 default_ttl ± random_range 范围内随机
    pub ttl_random_range: Option<Duration>,

    /// 空闲过期时间(秒),None 表示不过期
    pub time_to_idle: Option<Duration>,

    /// 系统标识(用于 Key 前缀)
    pub system_name: String,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            max_capacity: 10_000,
            initial_capacity: 100,
            default_ttl: Duration::from_secs(3600), // 默认 1 小时
            ttl_random_range: Some(Duration::from_secs(300)), // ±5 分钟随机
            time_to_idle: Some(Duration::from_secs(1800)), // 30 分钟空闲过期
            system_name: "secra".to_string(),
        }
    }
}

impl MemoryConfig {
    /// 创建新的内存缓存配置
    ///
    /// # Arguments
    /// * `max_capacity` - 最大容量(条目数)
    /// * `default_ttl` - 默认 TTL
    /// * `ttl_random_range` - TTL 随机化范围(可选)
    ///
    /// # Returns
    /// * `Self` - 配置实例
    pub fn new(
        max_capacity: u64,
        default_ttl: Duration,
        ttl_random_range: Option<Duration>,
    ) -> Self {
        Self {
            max_capacity,
            initial_capacity: 100,
            default_ttl,
            ttl_random_range,
            time_to_idle: Some(Duration::from_secs(1800)),
            system_name: "secra".to_string(),
        }
    }

    /// 设置系统标识
    ///
    /// # Arguments
    /// * `system_name` - 系统标识
    ///
    /// # Returns
    /// * `Self` - 配置实例
    pub fn with_system_name(mut self, system_name: String) -> Self {
        self.system_name = system_name;
        self
    }

    /// 设置初始容量
    ///
    /// # Arguments
    /// * `initial_capacity` - 初始容量
    ///
    /// # Returns
    /// * `Self` - 配置实例
    pub fn with_initial_capacity(mut self, initial_capacity: usize) -> Self {
        self.initial_capacity = initial_capacity;
        self
    }

    /// 设置空闲过期时间
    ///
    /// # Arguments
    /// * `time_to_idle` - 空闲过期时间
    ///
    /// # Returns
    /// * `Self` - 配置实例
    pub fn with_time_to_idle(mut self, time_to_idle: Option<Duration>) -> Self {
        self.time_to_idle = time_to_idle;
        self
    }
}