unistore-cache 0.1.0

In-memory cache capability for UniStore
Documentation
//! 【配置】- 缓存配置
//!
//! 职责:
//! - 定义缓存的配置选项
//! - 提供合理的默认值

use crate::deps::Duration;

/// 缓存配置
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// 最大容量(条目数,默认 1000)
    pub max_capacity: usize,

    /// 默认 TTL(None 表示永不过期,默认 5 分钟)
    pub default_ttl: Option<Duration>,

    /// 过期检查间隔(默认 1 分钟)
    pub cleanup_interval: Duration,

    /// 批量淘汰数量(默认 10%)
    pub eviction_batch_size: usize,

    /// 是否启用统计(默认 true)
    pub enable_stats: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_capacity: 1000,
            default_ttl: Some(Duration::from_secs(300)),
            cleanup_interval: Duration::from_secs(60),
            eviction_batch_size: 100,
            enable_stats: true,
        }
    }
}

impl CacheConfig {
    /// 创建默认配置
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置最大容量
    pub fn max_capacity(mut self, capacity: usize) -> Self {
        self.max_capacity = capacity;
        self.eviction_batch_size = (capacity / 10).max(1);
        self
    }

    /// 设置默认 TTL
    pub fn default_ttl(mut self, ttl: Duration) -> Self {
        self.default_ttl = Some(ttl);
        self
    }

    /// 禁用 TTL(永不过期)
    pub fn no_ttl(mut self) -> Self {
        self.default_ttl = None;
        self
    }

    /// 设置过期检查间隔
    pub fn cleanup_interval(mut self, interval: Duration) -> Self {
        self.cleanup_interval = interval;
        self
    }

    /// 设置批量淘汰数量
    pub fn eviction_batch_size(mut self, size: usize) -> Self {
        self.eviction_batch_size = size;
        self
    }

    /// 禁用统计
    pub fn no_stats(mut self) -> Self {
        self.enable_stats = false;
        self
    }

    /// 创建高性能配置(大容量、长 TTL、禁用统计)
    pub fn high_performance() -> Self {
        Self {
            max_capacity: 100_000,
            default_ttl: Some(Duration::from_secs(3600)),
            cleanup_interval: Duration::from_secs(300),
            eviction_batch_size: 10_000,
            enable_stats: false,
        }
    }

    /// 创建会话缓存配置(中等容量、短 TTL)
    pub fn session() -> Self {
        Self {
            max_capacity: 10_000,
            default_ttl: Some(Duration::from_secs(1800)), // 30 分钟
            cleanup_interval: Duration::from_secs(60),
            eviction_batch_size: 1_000,
            enable_stats: true,
        }
    }

    /// 创建短期缓存配置(小容量、极短 TTL)
    pub fn short_lived() -> Self {
        Self {
            max_capacity: 100,
            default_ttl: Some(Duration::from_secs(60)),
            cleanup_interval: Duration::from_secs(10),
            eviction_batch_size: 10,
            enable_stats: true,
        }
    }
}