garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! API Key 协议层测试 mock 实现(仅 `cfg(test)` 编译):`MockDao`(`tokio::sync::Mutex<HashMap>`
//! 模拟 DAO)供 `protocol::apikey::tests` 生成/校验测试复用;`keys` 复用
//! `crate::dao::glob_match`。

use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::collections::HashMap;
use tokio::sync::Mutex;

/// 测试用 Mock DAO。
pub struct MockDao {
    data: Mutex<HashMap<String, String>>,
}

impl MockDao {
    /// 创建空的 mock DAO 实例(无任何键值)。
    pub fn new() -> Self {
        Self {
            data: Mutex::new(HashMap::new()),
        }
    }
}

#[async_trait]
impl GarrisonDao for MockDao {
    async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
        let data = self.data.lock().await;
        Ok(data.get(key).cloned())
    }

    async fn set(&self, key: &str, value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
        let mut data = self.data.lock().await;
        data.insert(key.to_string(), value.to_string());
        Ok(())
    }

    async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
        let mut data = self.data.lock().await;
        if data.contains_key(key) {
            data.insert(key.to_string(), value.to_string());
            Ok(())
        } else {
            Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key)))
        }
    }

    async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
        Ok(())
    }

    async fn delete(&self, key: &str) -> GarrisonResult<()> {
        let mut data = self.data.lock().await;
        data.remove(key);
        Ok(())
    }

    /// keys 复用 `crate::dao::glob_match`(避免重复实现 glob 逻辑)。
    async fn keys(&self, pattern: &str) -> GarrisonResult<Vec<String>> {
        let data = self.data.lock().await;
        let mut result = Vec::new();
        for key in data.keys() {
            if crate::dao::glob_match(pattern, key) {
                result.push(key.clone());
            }
        }
        Ok(result)
    }
    crate::atomic_test_fallback!();
}