Skip to main content

yang_base/
tools.rs

1//! 应用资源的显式所有权与统一生命周期。
2//!
3//! [`ToolsBuilder`] 只在启动期可变;[`Tools`] 构建完成后只提供不可变访问。
4//! 高频资源使用直接字段,低频扩展与配置使用按 Rust 类型索引的只读映射。
5
6use crate::error::BaseError;
7use crate::table::RegexCache;
8use std::any::{type_name, Any, TypeId};
9use std::collections::HashMap;
10use std::fmt;
11use std::sync::atomic::{AtomicU8, Ordering};
12use tokio::sync::Mutex;
13
14#[cfg(any(feature = "mysql", feature = "postgres"))]
15use crate::database::{
16    AnyDatabase, Datasource, DatasourceHealth, DatasourcePoolStatus, DatasourceRegistry,
17};
18#[cfg(any(feature = "mysql", feature = "postgres"))]
19use crate::datasource::DatasourceId;
20#[cfg(feature = "http")]
21use crate::http::HttpClient;
22#[cfg(feature = "token")]
23use crate::token::TokenManager;
24#[cfg(any(feature = "mysql", feature = "postgres"))]
25use yang_db::BackendCapability;
26#[cfg(feature = "redis")]
27use yang_db::RedisClient;
28
29const RUNNING: u8 = 0;
30const CLOSING: u8 = 1;
31const CLOSED: u8 = 2;
32
33/// yang-base 受保护查询层与内置 CRUD 在启动期必需的后端能力。
34///
35/// 取两种 SQL 后端都声明的基础能力集合;方言专属能力(如 PostgreSQL 的
36/// `Savepoint`/`Returning`)由调用方通过 [`crate::database::AnyDatabase::require_capabilities`]
37/// 按需追加校验,避免 MySQL 构建被 PG 专属能力卡死。
38#[cfg(any(feature = "mysql", feature = "postgres"))]
39const REQUIRED_DATABASE_CAPABILITIES: &[BackendCapability] = &[
40    BackendCapability::CheckedIdentifiers,
41    BackendCapability::Select,
42    BackendCapability::Aggregate,
43    BackendCapability::Join,
44    BackendCapability::Insert,
45    BackendCapability::BatchInsert,
46    BackendCapability::Update,
47    BackendCapability::BatchUpdate,
48    BackendCapability::Delete,
49    BackendCapability::Upsert,
50    BackendCapability::BatchUpsert,
51    BackendCapability::TransactionCrud,
52];
53
54type TypeMap = HashMap<TypeId, Box<dyn Any + Send + Sync>>;
55
56/// 应用资源生命周期状态。
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum ToolsState {
59    /// 资源可用于请求处理。
60    Running,
61    /// 正在按逆初始化顺序关闭。
62    Closing,
63    /// 资源已经关闭。
64    Closed,
65}
66
67/// 单个已配置资源的健康状态。
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ResourceHealth {
70    /// 稳定的资源类型名。
71    pub resource: &'static str,
72    /// 健康检查是否成功。
73    pub healthy: bool,
74    /// 失败原因;健康时为 `None`。
75    pub detail: Option<String>,
76}
77
78/// [`Tools`] 的健康检查快照。
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ToolsHealth {
81    /// 检查时的生命周期状态。
82    pub state: ToolsState,
83    /// 所有已配置且支持检查的核心资源。
84    pub resources: Vec<ResourceHealth>,
85}
86
87impl ToolsHealth {
88    /// 所有资源是否处于运行且健康状态。
89    pub fn is_healthy(&self) -> bool {
90        self.state == ToolsState::Running && self.resources.iter().all(|item| item.healthy)
91    }
92}
93
94/// 构建完成后冻结的应用资源。
95pub struct Tools {
96    #[cfg(any(feature = "mysql", feature = "postgres"))]
97    databases: Option<DatasourceRegistry>,
98    #[cfg(feature = "redis")]
99    cache: Option<RedisClient>,
100    #[cfg(feature = "token")]
101    token: Option<TokenManager>,
102    #[cfg(feature = "http")]
103    http: Option<HttpClient>,
104    regex_cache: RegexCache,
105    extensions: TypeMap,
106    config: TypeMap,
107    state: AtomicU8,
108    close_lock: Mutex<()>,
109}
110
111impl fmt::Debug for Tools {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        formatter
114            .debug_struct("Tools")
115            .field("state", &self.state())
116            .field("extension_count", &self.extensions.len())
117            .field("config_count", &self.config.len())
118            .finish_non_exhaustive()
119    }
120}
121
122impl Tools {
123    /// 返回当前生命周期状态。
124    pub fn state(&self) -> ToolsState {
125        match self.state.load(Ordering::Acquire) {
126            RUNNING => ToolsState::Running,
127            CLOSING => ToolsState::Closing,
128            _ => ToolsState::Closed,
129        }
130    }
131
132    fn ensure_running(&self) -> Result<(), BaseError> {
133        match self.state() {
134            ToolsState::Running => Ok(()),
135            ToolsState::Closing => Err(BaseError::ConfigError("Tools 正在关闭".to_string())),
136            ToolsState::Closed => Err(BaseError::ConfigError("Tools 已关闭".to_string())),
137        }
138    }
139
140    /// 获取默认数据源;未配置或生命周期已结束时失败。
141    #[cfg(any(feature = "mysql", feature = "postgres"))]
142    pub fn database(&self) -> Result<&AnyDatabase, BaseError> {
143        self.ensure_running()?;
144        self.databases
145            .as_ref()
146            .map(|databases| databases.default_datasource().database())
147            .ok_or(BaseError::DatabaseNotInitialized)
148    }
149
150    /// 按逻辑名获取数据源;未配置、未注册或生命周期已结束时失败。
151    #[cfg(any(feature = "mysql", feature = "postgres"))]
152    pub fn datasource(&self, id: &DatasourceId) -> Result<&crate::database::Datasource, BaseError> {
153        self.ensure_running()?;
154        let databases = self
155            .databases
156            .as_ref()
157            .ok_or(BaseError::DatabaseNotInitialized)?;
158        databases.resolve_id(id)
159    }
160
161    /// 按逻辑名获取数据库容器。
162    #[cfg(any(feature = "mysql", feature = "postgres"))]
163    pub fn database_named(&self, id: &DatasourceId) -> Result<&AnyDatabase, BaseError> {
164        self.datasource(id).map(|datasource| datasource.database())
165    }
166
167    /// 返回全部具名数据源。
168    #[cfg(any(feature = "mysql", feature = "postgres"))]
169    pub fn datasources(&self) -> Result<&DatasourceRegistry, BaseError> {
170        self.ensure_running()?;
171        self.databases
172            .as_ref()
173            .ok_or(BaseError::DatabaseNotInitialized)
174    }
175
176    /// 获取默认数据源的 MySQL 连接池;默认源不是 MySQL 时返回
177    /// [`BaseError::DatabaseNotInitialized`]。
178    #[cfg(feature = "mysql")]
179    pub fn mysql(&self) -> Result<&yang_db::mysql::Database, BaseError> {
180        self.database()
181            .and_then(|database| database.as_mysql().ok_or(BaseError::DatabaseNotInitialized))
182    }
183
184    /// 返回默认数据源的连接池状态快照;未配置数据库时为 `None`。
185    ///
186    /// 不检查生命周期状态,便于关闭后继续观察连接池回收情况。
187    #[cfg(any(feature = "mysql", feature = "postgres"))]
188    pub fn pool_status(&self) -> Option<yang_db::PoolStatus> {
189        self.databases
190            .as_ref()
191            .map(|databases| databases.default_datasource().pool_status())
192    }
193
194    /// 返回全部数据源的连接池状态快照。
195    #[cfg(any(feature = "mysql", feature = "postgres"))]
196    pub fn pool_statuses(&self) -> Vec<DatasourcePoolStatus> {
197        self.databases
198            .as_ref()
199            .map(DatasourceRegistry::pool_statuses)
200            .unwrap_or_default()
201    }
202
203    /// 返回全部数据源的健康快照。
204    #[cfg(any(feature = "mysql", feature = "postgres"))]
205    pub async fn datasource_health(&self) -> Vec<DatasourceHealth> {
206        match &self.databases {
207            Some(databases) if self.state() == ToolsState::Running => databases.health().await,
208            _ => Vec::new(),
209        }
210    }
211
212    /// 获取 Redis 客户端;未配置或生命周期已结束时失败。
213    #[cfg(feature = "redis")]
214    pub fn cache(&self) -> Result<&RedisClient, BaseError> {
215        self.ensure_running()?;
216        self.cache.as_ref().ok_or(BaseError::RedisNotInitialized)
217    }
218
219    /// 获取 Token 管理器;未配置或生命周期已结束时失败。
220    #[cfg(feature = "token")]
221    pub fn token(&self) -> Result<&TokenManager, BaseError> {
222        self.ensure_running()?;
223        self.token
224            .as_ref()
225            .ok_or_else(|| BaseError::ConfigError("Tools 未配置 TokenManager".to_string()))
226    }
227
228    /// 获取 HTTP 客户端;未配置或生命周期已结束时失败。
229    ///
230    /// reqwest 客户端无需显式关闭,故该槽位不参与 close/health_check 流程。
231    #[cfg(feature = "http")]
232    pub fn http(&self) -> Result<&HttpClient, BaseError> {
233        self.ensure_running()?;
234        self.http
235            .as_ref()
236            .ok_or(BaseError::HttpClientNotInitialized)
237    }
238
239    /// 获取共享的有界正则缓存。
240    ///
241    /// 缓存为冻结的不可变资源,无需参与 close/health_check 流程;始终可用。
242    pub fn regex_cache(&self) -> &RegexCache {
243        &self.regex_cache
244    }
245
246    /// 按具体类型获取低频扩展。
247    pub fn extension<T>(&self) -> Result<&T, BaseError>
248    where
249        T: Any + Send + Sync,
250    {
251        self.ensure_running()?;
252        self.extensions
253            .get(&TypeId::of::<T>())
254            .and_then(|value| value.downcast_ref::<T>())
255            .ok_or_else(|| {
256                BaseError::ConfigError(format!("Tools 未配置扩展: {}", type_name::<T>()))
257            })
258    }
259
260    /// 按具体类型获取只读配置。
261    pub fn config<T>(&self) -> Result<&T, BaseError>
262    where
263        T: Any + Send + Sync,
264    {
265        self.ensure_running()?;
266        self.config
267            .get(&TypeId::of::<T>())
268            .and_then(|value| value.downcast_ref::<T>())
269            .ok_or_else(|| {
270                BaseError::ConfigError(format!("Tools 未配置配置类型: {}", type_name::<T>()))
271            })
272    }
273
274    /// 检查所有已配置核心资源并返回稳定快照。
275    pub async fn health_check(&self) -> ToolsHealth {
276        let state = self.state();
277        if state != ToolsState::Running {
278            return ToolsHealth {
279                state,
280                resources: Vec::new(),
281            };
282        }
283
284        #[cfg(any(feature = "mysql", feature = "postgres", feature = "redis"))]
285        let mut resources = Vec::new();
286        #[cfg(not(any(feature = "mysql", feature = "postgres", feature = "redis")))]
287        let resources = Vec::new();
288        #[cfg(any(feature = "mysql", feature = "postgres"))]
289        if let Some(databases) = &self.databases {
290            resources.extend(databases.health_check().await);
291        }
292        #[cfg(feature = "redis")]
293        if let Some(cache) = &self.cache {
294            resources.push(match cache.health_check().await {
295                Ok(healthy) => ResourceHealth {
296                    resource: "cache",
297                    healthy,
298                    detail: None,
299                },
300                Err(error) => ResourceHealth {
301                    resource: "cache",
302                    healthy: false,
303                    detail: Some(error.to_string()),
304                },
305            });
306        }
307
308        ToolsHealth { state, resources }
309    }
310
311    /// 幂等关闭所有核心资源。
312    ///
313    /// 关闭顺序与常见启动顺序相反:先 Redis,再数据库。并发调用会等待首个关闭流程完成。
314    pub async fn close(&self) {
315        let _guard = self.close_lock.lock().await;
316        if self.state() == ToolsState::Closed {
317            return;
318        }
319        self.state.store(CLOSING, Ordering::Release);
320
321        #[cfg(feature = "redis")]
322        if let Some(cache) = &self.cache {
323            cache.close().await;
324        }
325        #[cfg(any(feature = "mysql", feature = "postgres"))]
326        if let Some(databases) = &self.databases {
327            databases.close().await;
328        }
329
330        self.state.store(CLOSED, Ordering::Release);
331    }
332}
333
334/// 仅在启动期可变的应用资源构建器。
335#[derive(Default)]
336#[must_use = "ToolsBuilder 必须调用 build() 才会冻结并交给应用"]
337pub struct ToolsBuilder {
338    #[cfg(any(feature = "mysql", feature = "postgres"))]
339    databases: Vec<Datasource>,
340    #[cfg(any(feature = "mysql", feature = "postgres"))]
341    default_datasource: Option<DatasourceId>,
342    #[cfg(feature = "redis")]
343    cache: Option<RedisClient>,
344    #[cfg(feature = "token")]
345    token: Option<TokenManager>,
346    #[cfg(feature = "http")]
347    http: Option<HttpClient>,
348    regex_cache: RegexCache,
349    extensions: TypeMap,
350    config: TypeMap,
351    duplicate: Option<String>,
352}
353
354impl fmt::Debug for ToolsBuilder {
355    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
356        formatter
357            .debug_struct("ToolsBuilder")
358            .field("extension_count", &self.extensions.len())
359            .field("config_count", &self.config.len())
360            .field("duplicate", &self.duplicate)
361            .finish_non_exhaustive()
362    }
363}
364
365impl ToolsBuilder {
366    /// 创建空构建器。
367    pub fn new() -> Self {
368        Self::default()
369    }
370
371    /// 设置默认数据源的 MySQL 资源(兼容入口)。
372    #[cfg(feature = "mysql")]
373    pub fn mysql(self, mysql: yang_db::mysql::Database) -> Self {
374        self.database_named(DatasourceId::default_source(), AnyDatabase::mysql(mysql))
375    }
376
377    /// 设置默认数据源的运行时数据库后端(MySQL 或 PostgreSQL,兼容入口)。
378    #[cfg(any(feature = "mysql", feature = "postgres"))]
379    pub fn database(self, database: AnyDatabase) -> Self {
380        self.database_named(DatasourceId::default_source(), database)
381    }
382
383    /// 用逻辑名注册一个数据源。
384    #[cfg(any(feature = "mysql", feature = "postgres"))]
385    pub fn database_named(mut self, id: DatasourceId, database: AnyDatabase) -> Self {
386        if id.is_default() && self.default_datasource.is_none() {
387            self.default_datasource = Some(id.clone());
388        }
389        self.databases.push(Datasource::new(id, database, true));
390        self
391    }
392
393    /// 用逻辑名注册一个数据源,并指定它是否参与 readiness。
394    #[cfg(any(feature = "mysql", feature = "postgres"))]
395    pub fn database_named_with_policy(
396        mut self,
397        id: DatasourceId,
398        database: AnyDatabase,
399        required: bool,
400    ) -> Self {
401        if id.is_default() && self.default_datasource.is_none() {
402            self.default_datasource = Some(id.clone());
403        }
404        self.databases.push(Datasource::new(id, database, required));
405        self
406    }
407
408    /// 用逻辑名注册一个 MySQL 数据源。
409    #[cfg(feature = "mysql")]
410    pub fn mysql_named(self, id: DatasourceId, database: yang_db::mysql::Database) -> Self {
411        self.database_named(id, AnyDatabase::mysql(database))
412    }
413
414    /// 用逻辑名注册一个 PostgreSQL 数据源。
415    #[cfg(feature = "postgres")]
416    pub fn postgres_named(self, id: DatasourceId, database: yang_db::postgres::Database) -> Self {
417        self.database_named(id, AnyDatabase::postgres(database))
418    }
419
420    /// 显式指定默认数据源。
421    #[cfg(any(feature = "mysql", feature = "postgres"))]
422    pub fn default_datasource(mut self, id: DatasourceId) -> Self {
423        self.default_datasource = Some(id);
424        self
425    }
426
427    /// 设置唯一 Redis 客户端。
428    #[cfg(feature = "redis")]
429    pub fn cache(mut self, cache: RedisClient) -> Self {
430        if self.cache.replace(cache).is_some() {
431            self.record_duplicate("RedisClient");
432        }
433        self
434    }
435
436    /// 从 URL + 池配置连接 Redis 并注册。
437    ///
438    /// 失败返回 [`BaseError::RedisConnectionFailed`](保留底层错误链)。
439    #[cfg(feature = "redis")]
440    pub async fn cache_from_url(
441        self,
442        url: impl Into<String>,
443        config: yang_db::RedisConfig,
444    ) -> Result<Self, BaseError> {
445        let client = RedisClient::connect_with_config(url, config)
446            .await
447            .map_err(BaseError::RedisConnectionFailed)?;
448        Ok(self.cache(client))
449    }
450
451    /// 设置唯一 Token 管理器。
452    #[cfg(feature = "token")]
453    pub fn token(mut self, token: TokenManager) -> Self {
454        if self.token.replace(token).is_some() {
455            self.record_duplicate("TokenManager");
456        }
457        self
458    }
459
460    /// 设置唯一 HTTP 客户端。
461    ///
462    /// reqwest 客户端无需显式关闭,构建后只读共享,不参与 close/health_check 流程。
463    #[cfg(feature = "http")]
464    pub fn http(mut self, client: HttpClient) -> Self {
465        if self.http.replace(client).is_some() {
466            self.record_duplicate("HttpClient");
467        }
468        self
469    }
470
471    /// 覆盖默认容量的共享正则缓存。
472    pub fn regex_cache(mut self, cache: RegexCache) -> Self {
473        self.regex_cache = cache;
474        self
475    }
476
477    /// 注册一个按具体 Rust 类型索引的低频扩展。
478    pub fn extension<T>(mut self, extension: T) -> Self
479    where
480        T: Any + Send + Sync,
481    {
482        if self
483            .extensions
484            .insert(TypeId::of::<T>(), Box::new(extension))
485            .is_some()
486        {
487            self.record_duplicate(type_name::<T>());
488        }
489        self
490    }
491
492    /// 注册一个按具体 Rust 类型索引的只读配置。
493    pub fn config<T>(mut self, config: T) -> Self
494    where
495        T: Any + Send + Sync,
496    {
497        if self
498            .config
499            .insert(TypeId::of::<T>(), Box::new(config))
500            .is_some()
501        {
502            self.record_duplicate(type_name::<T>());
503        }
504        self
505    }
506
507    fn record_duplicate(&mut self, resource: &str) {
508        if self.duplicate.is_none() {
509            self.duplicate = Some(resource.to_string());
510        }
511    }
512
513    /// 校验唯一性、连接 Token 撤销存储并冻结资源。
514    pub fn build(self) -> Result<Tools, BaseError> {
515        if let Some(resource) = self.duplicate {
516            return Err(BaseError::ConfigError(format!(
517                "Tools 资源重复注册: {resource}"
518            )));
519        }
520
521        // 启动期能力门禁:核心查询/CRUD 所需能力缺失时 fail-fast。
522        #[cfg(any(feature = "mysql", feature = "postgres"))]
523        let databases = if self.databases.is_empty() {
524            if let Some(default) = &self.default_datasource {
525                return Err(BaseError::ConfigError(format!(
526                    "指定了默认数据源 {default},但没有注册任何数据源"
527                )));
528            }
529            None
530        } else {
531            let registry =
532                DatasourceRegistry::new(self.default_datasource.clone(), self.databases)?;
533            for datasource in registry.iter() {
534                datasource
535                    .database()
536                    .require_capabilities(REQUIRED_DATABASE_CAPABILITIES)?;
537            }
538            Some(registry)
539        };
540
541        #[cfg(feature = "token")]
542        let token = {
543            let mut token = self.token;
544            if let (Some(token), Some(cache)) = (&mut token, &self.cache) {
545                token.attach_revocation_cache(cache.clone());
546            }
547            token
548        };
549
550        Ok(Tools {
551            #[cfg(any(feature = "mysql", feature = "postgres"))]
552            databases,
553            #[cfg(feature = "redis")]
554            cache: self.cache,
555            #[cfg(feature = "token")]
556            token,
557            #[cfg(feature = "http")]
558            http: self.http,
559            regex_cache: self.regex_cache,
560            extensions: self.extensions,
561            config: self.config,
562            state: AtomicU8::new(RUNNING),
563            close_lock: Mutex::new(()),
564        })
565    }
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571
572    #[derive(Debug, PartialEq, Eq)]
573    struct TestExtension(u32);
574
575    #[derive(Debug, PartialEq, Eq)]
576    struct TestConfig(&'static str);
577
578    #[test]
579    fn typed_entries_are_frozen_and_separate() {
580        let tools = ToolsBuilder::new()
581            .extension(TestExtension(7))
582            .config(TestConfig("local"))
583            .build()
584            .expect("类型化资源应构建成功");
585
586        assert_eq!(
587            tools.extension::<TestExtension>().expect("扩展应存在"),
588            &TestExtension(7)
589        );
590        assert_eq!(
591            tools.config::<TestConfig>().expect("配置应存在"),
592            &TestConfig("local")
593        );
594        assert!(tools.extension::<TestConfig>().is_err());
595        assert!(tools.config::<TestExtension>().is_err());
596    }
597
598    #[test]
599    fn duplicate_type_is_rejected_at_build_time() {
600        let result = ToolsBuilder::new()
601            .extension(TestExtension(1))
602            .extension(TestExtension(2))
603            .build();
604        assert!(
605            matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
606        );
607    }
608
609    #[tokio::test]
610    async fn close_is_idempotent_and_changes_health_semantics() {
611        let tools = ToolsBuilder::new()
612            .build()
613            .expect("空资源集合可用于纯逻辑测试");
614        assert!(tools.health_check().await.is_healthy());
615
616        tools.close().await;
617        tools.close().await;
618
619        let health = tools.health_check().await;
620        assert_eq!(health.state, ToolsState::Closed);
621        assert!(!health.is_healthy());
622        assert!(matches!(
623            tools.extension::<TestExtension>(),
624            Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
625        ));
626    }
627
628    #[cfg(feature = "http")]
629    fn test_http_client() -> crate::http::HttpClient {
630        crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功")
631    }
632
633    #[cfg(feature = "http")]
634    #[test]
635    fn http_slot_returns_client_when_configured() {
636        let tools = ToolsBuilder::new()
637            .http(test_http_client())
638            .build()
639            .expect("配置 HTTP 客户端后应构建成功");
640
641        let client = tools.http().expect("已配置时应返回 HTTP 客户端");
642        // 验证拿到的是可用客户端(能构建请求)
643        let _builder = client.get("https://api.example.com/test");
644    }
645
646    #[cfg(feature = "http")]
647    #[test]
648    fn http_slot_errors_when_not_configured() {
649        let tools = ToolsBuilder::new().build().expect("空资源集合应构建成功");
650
651        assert!(matches!(
652            tools.http(),
653            Err(BaseError::HttpClientNotInitialized)
654        ));
655    }
656
657    #[cfg(feature = "http")]
658    #[test]
659    fn http_slot_duplicate_registration_is_rejected_at_build_time() {
660        let result = ToolsBuilder::new()
661            .http(test_http_client())
662            .http(test_http_client())
663            .build();
664
665        assert!(
666            matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
667        );
668    }
669
670    #[cfg(feature = "http")]
671    #[tokio::test]
672    async fn http_slot_errors_after_close() {
673        let tools = ToolsBuilder::new()
674            .http(test_http_client())
675            .build()
676            .expect("配置 HTTP 客户端后应构建成功");
677
678        tools.close().await;
679
680        assert!(matches!(
681            tools.http(),
682            Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
683        ));
684    }
685
686    /// 用惰性连接池构造 MySQL 连接池:不建立真实网络连接。
687    #[cfg(feature = "mysql")]
688    fn test_mysql_pool() -> yang_db::mysql::Database {
689        let pool = sqlx::MySqlPool::connect_lazy("mysql://root:test@127.0.0.1:3306/test")
690            .expect("惰性 MySQL 连接池应创建成功");
691        yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
692            .expect("默认 MySQL 配置应通过校验")
693    }
694
695    #[cfg(feature = "mysql")]
696    fn test_mysql_database() -> AnyDatabase {
697        AnyDatabase::mysql(test_mysql_pool())
698    }
699
700    /// 用惰性连接池构造 PostgreSQL 连接池:不建立真实网络连接。
701    #[cfg(feature = "postgres")]
702    fn test_postgres_pool() -> yang_db::postgres::Database {
703        let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
704            .expect("惰性 PostgreSQL 连接池应创建成功");
705        yang_db::postgres::Database::from_pool(pool, yang_db::postgres::DatabaseConfig::default())
706            .expect("默认 PostgreSQL 配置应通过校验")
707    }
708
709    #[cfg(feature = "postgres")]
710    fn test_postgres_database() -> AnyDatabase {
711        AnyDatabase::postgres(test_postgres_pool())
712    }
713
714    #[cfg(feature = "mysql")]
715    #[tokio::test]
716    async fn mysql_handler_reports_backend_and_pool_status() {
717        let tools = ToolsBuilder::new()
718            .mysql(test_mysql_pool())
719            .build()
720            .expect("配置 MySQL 后应构建成功");
721
722        assert_eq!(
723            tools.database().expect("数据库应存在").backend(),
724            yang_db::BackendKind::MySql
725        );
726        assert!(tools.mysql().is_ok());
727        assert!(tools.pool_status().is_some());
728        assert!(tools.database().expect("数据库应存在").as_mysql().is_some());
729    }
730
731    #[cfg(feature = "postgres")]
732    #[tokio::test]
733    async fn postgres_handler_reports_backend_and_pool_status() {
734        let tools = ToolsBuilder::new()
735            .database(test_postgres_database())
736            .build()
737            .expect("配置 PostgreSQL 后应构建成功");
738
739        assert_eq!(
740            tools.database().expect("数据库应存在").backend(),
741            yang_db::BackendKind::PostgreSql
742        );
743        assert!(tools.pool_status().is_some());
744        assert!(tools
745            .database()
746            .expect("数据库应存在")
747            .as_postgres()
748            .is_some());
749    }
750
751    #[cfg(feature = "mysql")]
752    #[tokio::test]
753    async fn database_slot_errors_after_close() {
754        let tools = ToolsBuilder::new()
755            .database(test_mysql_database())
756            .build()
757            .expect("配置数据库后应构建成功");
758
759        tools.close().await;
760
761        assert!(matches!(
762            tools.database(),
763            Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
764        ));
765    }
766
767    #[cfg(feature = "mysql")]
768    #[tokio::test]
769    async fn duplicate_database_registration_is_rejected_at_build_time() {
770        let result = ToolsBuilder::new()
771            .database(test_mysql_database())
772            .database(test_mysql_database())
773            .build();
774
775        assert!(
776            matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
777        );
778    }
779
780    #[cfg(all(feature = "mysql", feature = "postgres"))]
781    #[tokio::test]
782    async fn mysql_accessor_rejects_postgres_backend() {
783        let tools = ToolsBuilder::new()
784            .database(test_postgres_database())
785            .build()
786            .expect("配置 PostgreSQL 后应构建成功");
787
788        assert_eq!(
789            tools.database().expect("数据库应存在").backend(),
790            yang_db::BackendKind::PostgreSql
791        );
792        assert!(matches!(
793            tools.mysql(),
794            Err(BaseError::DatabaseNotInitialized)
795        ));
796        assert!(tools
797            .database()
798            .expect("数据库应存在")
799            .as_postgres()
800            .is_some());
801    }
802}