garrison 0.9.0

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

//! 管理器模块,提供全局管理器单例与编译期工厂注册。
//!
//! `GarrisonManager` 统筹 DAO、配置、策略等组件的全局生命周期:持有
//! `Arc<GarrisonLogicDefault>` 全局单例(基于 `arc_swap::ArcSwapOption`,读路径无锁、支持
//! 重复 init);`GarrisonLogicFactory` trait 通过 `inventory::submit!` 编译期注册;业务方经
//! `GarrisonManager::builder().dao(dao).config(config).interface(interface).build().await`
//! 注入依赖;`GarrisonUtil::login(id)` 等静态方法委托到 `GARRISON_MANAGER` 单例。
//!
//! ## 初始化流程
//!
//! ```ignore
//! use std::sync::Arc;
//! use garrison::prelude::*;
//!
//! // 1. 准备依赖
//! let dao: Arc<dyn GarrisonDao> = /* oxcache 或 dbnexus 实现 */;
//! let config = Arc::new(GarrisonConfig::default_config());
//! let interface: Arc<dyn GarrisonInterface> = Arc::new(MyInterface);
//!
//! // 2. 初始化全局管理器
//! GarrisonManager::builder()
//! .dao(dao)
//! .config(config)
//! .interface(interface)
//! .build()
//! .await
//! .unwrap();
//!
//! // 3. 使用静态 API(task_local 上下文由 middleware 设置)
//! let token = GarrisonUtil::login_simple("1001").await.unwrap();
//! ```

use crate::stp::GarrisonLogicDefault;
use crate::strategy::Strategy;
use arc_swap::ArcSwapOption;
use parking_lot::RwLock;
use std::sync::Arc;
use std::sync::LazyLock;
#[cfg(feature = "anomalous-detector-dual")]
use tokio::sync::watch;
use tokio::task::JoinHandle;

// 显式 Manager API
// 启用 manager-explicit feature 后提供不依赖全局单例的 Manager struct。
#[cfg(feature = "manager-explicit")]
pub mod explicit;

// 工厂子系统(GarrisonLogicFactoryContext / GarrisonLogicFactoryEntry / garrison_logic_factory_default)。
pub mod factory;
// GarrisonManager 实现块(含 Drop impl)。
pub mod impls;
// 可组合的初始化 builder(GarrisonManagerBuilder / TaskHandles / build / build_explicit)。
pub mod builder;

// Re-export factory 公共 API(保持原 mod.rs 路径兼容,如 crate::manager::GarrisonLogicFactoryEntry)。
pub use factory::*;
// Re-export builder 公共 API(crate::manager::GarrisonManagerBuilder)。
pub use builder::GarrisonManagerBuilder;

/// 全局管理器,统筹 `GarrisonLogicDefault` 的生命周期。
///
/// 持有全局 `Arc<GarrisonLogicDefault>` 引用,提供静态方法入口。
///
/// # 初始化
///
/// 启动时调用 `GarrisonManager::builder().dao(dao).config(config).interface(interface).build().await`
/// 注入依赖。未初始化时调用 `GarrisonUtil::login(id)` 等返回 `GarrisonError::Session`
/// (错误码 `manager-not-init`,与 locales 键一致)。
///
/// # 并发写入契约
///
/// `logic` 与 `strategy` 是两个独立的 `ArcSwapOption`,单次 `store` 原子但两者成对非原子;
/// 并发 `build()` 可能产生 `(logic_B, strategy_A)` 错配对。该风险由 builder 内进程级
/// `BUILD_LOCK` 串行化单例写入段消除——不要绕过 builder 直接 `store` 全局单例字段。
pub struct GarrisonManager {
    /// 全局 `GarrisonLogicDefault` 引用(ArcSwapOption 支持测试时重复 init 与 reset)。
    logic: ArcSwapOption<GarrisonLogicDefault>,
    /// 全局 Strategy 注册表引用。
    ///
    /// 外层 `ArcSwapOption` 管理 Option(初始化/重置),内层 `Arc<RwLock<Strategy>>`
    /// 允许运行时通过 `strategy.write().register_*()` 替换策略。
    strategy: ArcSwapOption<RwLock<Strategy>>,
    /// 后台 cleanup task 的 JoinHandle。
    ///
    /// `builder().build()` 时若 `config.token_map_cleanup_interval_secs > 0` 则启动 task 并保存 handle。
    /// `reset_for_test` / `Drop` 时 abort task,避免后台线程在测试间或程序退出后残留。
    cleanup_task_handle: RwLock<Option<Arc<JoinHandle<()>>>>,
    /// 异常登录分析器 task 的 JoinHandle(anomalous-detector-dual feature)。
    ///
    /// `builder().build()` 时若 `anomalous-detector-dual` feature 启用则启动 analyzer task 并保存 handle。
    /// `reset_for_test` / `Drop` 时 abort task,避免后台线程在测试间或程序退出后残留。
    #[cfg(feature = "anomalous-detector-dual")]
    anomalous_analyzer_handle: RwLock<Option<Arc<JoinHandle<()>>>>,
    /// 异常登录分析器 shutdown 信号发送端(anomalous-detector-dual feature)。
    ///
    /// 保存 `shutdown_tx` 使其生命周期与 `GarrisonManager` 一致,
    /// 避免 `shutdown_rx` 因 sender drop 而误触发停止。
    /// `reset_for_test` / `Drop` 时 take 清空,触发 `shutdown_rx.changed()` 返回 Err 通知 task 退出。
    #[cfg(feature = "anomalous-detector-dual")]
    anomalous_analyzer_shutdown_tx: RwLock<Option<watch::Sender<bool>>>,
}

/// 全局管理器单例(`LazyLock` 懒加载,首次访问时调用 `GarrisonManager::new()`)。
pub static GARRISON_MANAGER: LazyLock<GarrisonManager> = LazyLock::new(GarrisonManager::new);

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;