1use 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::AnyDatabase;
16#[cfg(feature = "http")]
17use crate::http::HttpClient;
18#[cfg(feature = "token")]
19use crate::token::TokenManager;
20#[cfg(any(feature = "mysql", feature = "postgres"))]
21use yang_db::BackendCapability;
22#[cfg(feature = "redis")]
23use yang_db::RedisClient;
24
25const RUNNING: u8 = 0;
26const CLOSING: u8 = 1;
27const CLOSED: u8 = 2;
28
29#[cfg(any(feature = "mysql", feature = "postgres"))]
35const REQUIRED_DATABASE_CAPABILITIES: &[BackendCapability] = &[
36 BackendCapability::CheckedIdentifiers,
37 BackendCapability::Select,
38 BackendCapability::Aggregate,
39 BackendCapability::Join,
40 BackendCapability::Insert,
41 BackendCapability::BatchInsert,
42 BackendCapability::Update,
43 BackendCapability::BatchUpdate,
44 BackendCapability::Delete,
45 BackendCapability::Upsert,
46 BackendCapability::BatchUpsert,
47 BackendCapability::TransactionCrud,
48];
49
50type TypeMap = HashMap<TypeId, Box<dyn Any + Send + Sync>>;
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ToolsState {
55 Running,
57 Closing,
59 Closed,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct ResourceHealth {
66 pub resource: &'static str,
68 pub healthy: bool,
70 pub detail: Option<String>,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ToolsHealth {
77 pub state: ToolsState,
79 pub resources: Vec<ResourceHealth>,
81}
82
83impl ToolsHealth {
84 pub fn is_healthy(&self) -> bool {
86 self.state == ToolsState::Running && self.resources.iter().all(|item| item.healthy)
87 }
88}
89
90pub struct Tools {
92 #[cfg(any(feature = "mysql", feature = "postgres"))]
93 database: Option<AnyDatabase>,
94 #[cfg(feature = "redis")]
95 cache: Option<RedisClient>,
96 #[cfg(feature = "token")]
97 token: Option<TokenManager>,
98 #[cfg(feature = "http")]
99 http: Option<HttpClient>,
100 regex_cache: RegexCache,
101 extensions: TypeMap,
102 config: TypeMap,
103 state: AtomicU8,
104 close_lock: Mutex<()>,
105}
106
107impl fmt::Debug for Tools {
108 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109 formatter
110 .debug_struct("Tools")
111 .field("state", &self.state())
112 .field("extension_count", &self.extensions.len())
113 .field("config_count", &self.config.len())
114 .finish_non_exhaustive()
115 }
116}
117
118impl Tools {
119 pub fn state(&self) -> ToolsState {
121 match self.state.load(Ordering::Acquire) {
122 RUNNING => ToolsState::Running,
123 CLOSING => ToolsState::Closing,
124 _ => ToolsState::Closed,
125 }
126 }
127
128 fn ensure_running(&self) -> Result<(), BaseError> {
129 match self.state() {
130 ToolsState::Running => Ok(()),
131 ToolsState::Closing => Err(BaseError::ConfigError("Tools 正在关闭".to_string())),
132 ToolsState::Closed => Err(BaseError::ConfigError("Tools 已关闭".to_string())),
133 }
134 }
135
136 #[cfg(any(feature = "mysql", feature = "postgres"))]
138 pub fn database(&self) -> Result<&AnyDatabase, BaseError> {
139 self.ensure_running()?;
140 self.database
141 .as_ref()
142 .ok_or(BaseError::DatabaseNotInitialized)
143 }
144
145 #[cfg(feature = "mysql")]
150 pub fn mysql(&self) -> Result<&yang_db::mysql::Database, BaseError> {
151 self.ensure_running()?;
152 self.database
153 .as_ref()
154 .and_then(AnyDatabase::as_mysql)
155 .ok_or(BaseError::DatabaseNotInitialized)
156 }
157
158 #[cfg(any(feature = "mysql", feature = "postgres"))]
162 pub fn pool_status(&self) -> Option<yang_db::PoolStatus> {
163 self.database.as_ref().map(AnyDatabase::pool_status)
164 }
165
166 #[cfg(feature = "redis")]
168 pub fn cache(&self) -> Result<&RedisClient, BaseError> {
169 self.ensure_running()?;
170 self.cache.as_ref().ok_or(BaseError::RedisNotInitialized)
171 }
172
173 #[cfg(feature = "token")]
175 pub fn token(&self) -> Result<&TokenManager, BaseError> {
176 self.ensure_running()?;
177 self.token
178 .as_ref()
179 .ok_or_else(|| BaseError::ConfigError("Tools 未配置 TokenManager".to_string()))
180 }
181
182 #[cfg(feature = "http")]
186 pub fn http(&self) -> Result<&HttpClient, BaseError> {
187 self.ensure_running()?;
188 self.http
189 .as_ref()
190 .ok_or(BaseError::HttpClientNotInitialized)
191 }
192
193 pub fn regex_cache(&self) -> &RegexCache {
197 &self.regex_cache
198 }
199
200 pub fn extension<T>(&self) -> Result<&T, BaseError>
202 where
203 T: Any + Send + Sync,
204 {
205 self.ensure_running()?;
206 self.extensions
207 .get(&TypeId::of::<T>())
208 .and_then(|value| value.downcast_ref::<T>())
209 .ok_or_else(|| {
210 BaseError::ConfigError(format!("Tools 未配置扩展: {}", type_name::<T>()))
211 })
212 }
213
214 pub fn config<T>(&self) -> Result<&T, BaseError>
216 where
217 T: Any + Send + Sync,
218 {
219 self.ensure_running()?;
220 self.config
221 .get(&TypeId::of::<T>())
222 .and_then(|value| value.downcast_ref::<T>())
223 .ok_or_else(|| {
224 BaseError::ConfigError(format!("Tools 未配置配置类型: {}", type_name::<T>()))
225 })
226 }
227
228 pub async fn health_check(&self) -> ToolsHealth {
230 let state = self.state();
231 if state != ToolsState::Running {
232 return ToolsHealth {
233 state,
234 resources: Vec::new(),
235 };
236 }
237
238 #[cfg(any(feature = "mysql", feature = "postgres", feature = "redis"))]
239 let mut resources = Vec::new();
240 #[cfg(not(any(feature = "mysql", feature = "postgres", feature = "redis")))]
241 let resources = Vec::new();
242 #[cfg(any(feature = "mysql", feature = "postgres"))]
243 if let Some(database) = &self.database {
244 let resource = match database.backend() {
245 yang_db::BackendKind::MySql => "mysql",
246 yang_db::BackendKind::PostgreSql => "postgres",
247 _ => "database",
248 };
249 resources.push(match database.health_check().await {
250 Ok(healthy) => ResourceHealth {
251 resource,
252 healthy,
253 detail: None,
254 },
255 Err(error) => ResourceHealth {
256 resource,
257 healthy: false,
258 detail: Some(error.to_string()),
259 },
260 });
261 }
262 #[cfg(feature = "redis")]
263 if let Some(cache) = &self.cache {
264 resources.push(match cache.health_check().await {
265 Ok(healthy) => ResourceHealth {
266 resource: "cache",
267 healthy,
268 detail: None,
269 },
270 Err(error) => ResourceHealth {
271 resource: "cache",
272 healthy: false,
273 detail: Some(error.to_string()),
274 },
275 });
276 }
277
278 ToolsHealth { state, resources }
279 }
280
281 pub async fn close(&self) {
285 let _guard = self.close_lock.lock().await;
286 if self.state() == ToolsState::Closed {
287 return;
288 }
289 self.state.store(CLOSING, Ordering::Release);
290
291 #[cfg(feature = "redis")]
292 if let Some(cache) = &self.cache {
293 cache.close().await;
294 }
295 #[cfg(any(feature = "mysql", feature = "postgres"))]
296 if let Some(database) = &self.database {
297 database.close().await;
298 }
299
300 self.state.store(CLOSED, Ordering::Release);
301 }
302}
303
304#[derive(Default)]
306#[must_use = "ToolsBuilder 必须调用 build() 才会冻结并交给应用"]
307pub struct ToolsBuilder {
308 #[cfg(any(feature = "mysql", feature = "postgres"))]
309 database: Option<AnyDatabase>,
310 #[cfg(feature = "redis")]
311 cache: Option<RedisClient>,
312 #[cfg(feature = "token")]
313 token: Option<TokenManager>,
314 #[cfg(feature = "http")]
315 http: Option<HttpClient>,
316 regex_cache: RegexCache,
317 extensions: TypeMap,
318 config: TypeMap,
319 duplicate: Option<String>,
320}
321
322impl fmt::Debug for ToolsBuilder {
323 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
324 formatter
325 .debug_struct("ToolsBuilder")
326 .field("extension_count", &self.extensions.len())
327 .field("config_count", &self.config.len())
328 .field("duplicate", &self.duplicate)
329 .finish_non_exhaustive()
330 }
331}
332
333impl ToolsBuilder {
334 pub fn new() -> Self {
336 Self::default()
337 }
338
339 #[cfg(feature = "mysql")]
341 pub fn mysql(mut self, mysql: yang_db::mysql::Database) -> Self {
342 self.set_database(AnyDatabase::mysql(mysql), "MySQL");
343 self
344 }
345
346 #[cfg(any(feature = "mysql", feature = "postgres"))]
348 pub fn database(mut self, database: AnyDatabase) -> Self {
349 self.set_database(database, "Database");
350 self
351 }
352
353 #[cfg(any(feature = "mysql", feature = "postgres"))]
354 fn set_database(&mut self, database: AnyDatabase, resource: &str) {
355 if self.database.replace(database).is_some() {
356 self.record_duplicate(resource);
357 }
358 }
359
360 #[cfg(feature = "redis")]
362 pub fn cache(mut self, cache: RedisClient) -> Self {
363 if self.cache.replace(cache).is_some() {
364 self.record_duplicate("RedisClient");
365 }
366 self
367 }
368
369 #[cfg(feature = "redis")]
373 pub async fn cache_from_url(
374 self,
375 url: impl Into<String>,
376 config: yang_db::RedisConfig,
377 ) -> Result<Self, BaseError> {
378 let client = RedisClient::connect_with_config(url, config)
379 .await
380 .map_err(BaseError::RedisConnectionFailed)?;
381 Ok(self.cache(client))
382 }
383
384 #[cfg(feature = "token")]
386 pub fn token(mut self, token: TokenManager) -> Self {
387 if self.token.replace(token).is_some() {
388 self.record_duplicate("TokenManager");
389 }
390 self
391 }
392
393 #[cfg(feature = "http")]
397 pub fn http(mut self, client: HttpClient) -> Self {
398 if self.http.replace(client).is_some() {
399 self.record_duplicate("HttpClient");
400 }
401 self
402 }
403
404 pub fn regex_cache(mut self, cache: RegexCache) -> Self {
406 self.regex_cache = cache;
407 self
408 }
409
410 pub fn extension<T>(mut self, extension: T) -> Self
412 where
413 T: Any + Send + Sync,
414 {
415 if self
416 .extensions
417 .insert(TypeId::of::<T>(), Box::new(extension))
418 .is_some()
419 {
420 self.record_duplicate(type_name::<T>());
421 }
422 self
423 }
424
425 pub fn config<T>(mut self, config: T) -> Self
427 where
428 T: Any + Send + Sync,
429 {
430 if self
431 .config
432 .insert(TypeId::of::<T>(), Box::new(config))
433 .is_some()
434 {
435 self.record_duplicate(type_name::<T>());
436 }
437 self
438 }
439
440 fn record_duplicate(&mut self, resource: &str) {
441 if self.duplicate.is_none() {
442 self.duplicate = Some(resource.to_string());
443 }
444 }
445
446 pub fn build(self) -> Result<Tools, BaseError> {
448 if let Some(resource) = self.duplicate {
449 return Err(BaseError::ConfigError(format!(
450 "Tools 资源重复注册: {resource}"
451 )));
452 }
453
454 #[cfg(any(feature = "mysql", feature = "postgres"))]
456 if let Some(database) = &self.database {
457 database.require_capabilities(REQUIRED_DATABASE_CAPABILITIES)?;
458 }
459
460 #[cfg(feature = "token")]
461 let token = {
462 let mut token = self.token;
463 if let (Some(token), Some(cache)) = (&mut token, &self.cache) {
464 token.attach_revocation_cache(cache.clone());
465 }
466 token
467 };
468
469 Ok(Tools {
470 #[cfg(any(feature = "mysql", feature = "postgres"))]
471 database: self.database,
472 #[cfg(feature = "redis")]
473 cache: self.cache,
474 #[cfg(feature = "token")]
475 token,
476 #[cfg(feature = "http")]
477 http: self.http,
478 regex_cache: self.regex_cache,
479 extensions: self.extensions,
480 config: self.config,
481 state: AtomicU8::new(RUNNING),
482 close_lock: Mutex::new(()),
483 })
484 }
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490
491 #[derive(Debug, PartialEq, Eq)]
492 struct TestExtension(u32);
493
494 #[derive(Debug, PartialEq, Eq)]
495 struct TestConfig(&'static str);
496
497 #[test]
498 fn typed_entries_are_frozen_and_separate() {
499 let tools = ToolsBuilder::new()
500 .extension(TestExtension(7))
501 .config(TestConfig("local"))
502 .build()
503 .expect("类型化资源应构建成功");
504
505 assert_eq!(
506 tools.extension::<TestExtension>().expect("扩展应存在"),
507 &TestExtension(7)
508 );
509 assert_eq!(
510 tools.config::<TestConfig>().expect("配置应存在"),
511 &TestConfig("local")
512 );
513 assert!(tools.extension::<TestConfig>().is_err());
514 assert!(tools.config::<TestExtension>().is_err());
515 }
516
517 #[test]
518 fn duplicate_type_is_rejected_at_build_time() {
519 let result = ToolsBuilder::new()
520 .extension(TestExtension(1))
521 .extension(TestExtension(2))
522 .build();
523 assert!(
524 matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
525 );
526 }
527
528 #[tokio::test]
529 async fn close_is_idempotent_and_changes_health_semantics() {
530 let tools = ToolsBuilder::new()
531 .build()
532 .expect("空资源集合可用于纯逻辑测试");
533 assert!(tools.health_check().await.is_healthy());
534
535 tools.close().await;
536 tools.close().await;
537
538 let health = tools.health_check().await;
539 assert_eq!(health.state, ToolsState::Closed);
540 assert!(!health.is_healthy());
541 assert!(matches!(
542 tools.extension::<TestExtension>(),
543 Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
544 ));
545 }
546
547 #[cfg(feature = "http")]
548 fn test_http_client() -> crate::http::HttpClient {
549 crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功")
550 }
551
552 #[cfg(feature = "http")]
553 #[test]
554 fn http_slot_returns_client_when_configured() {
555 let tools = ToolsBuilder::new()
556 .http(test_http_client())
557 .build()
558 .expect("配置 HTTP 客户端后应构建成功");
559
560 let client = tools.http().expect("已配置时应返回 HTTP 客户端");
561 let _builder = client.get("https://api.example.com/test");
563 }
564
565 #[cfg(feature = "http")]
566 #[test]
567 fn http_slot_errors_when_not_configured() {
568 let tools = ToolsBuilder::new().build().expect("空资源集合应构建成功");
569
570 assert!(matches!(
571 tools.http(),
572 Err(BaseError::HttpClientNotInitialized)
573 ));
574 }
575
576 #[cfg(feature = "http")]
577 #[test]
578 fn http_slot_duplicate_registration_is_rejected_at_build_time() {
579 let result = ToolsBuilder::new()
580 .http(test_http_client())
581 .http(test_http_client())
582 .build();
583
584 assert!(
585 matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
586 );
587 }
588
589 #[cfg(feature = "http")]
590 #[tokio::test]
591 async fn http_slot_errors_after_close() {
592 let tools = ToolsBuilder::new()
593 .http(test_http_client())
594 .build()
595 .expect("配置 HTTP 客户端后应构建成功");
596
597 tools.close().await;
598
599 assert!(matches!(
600 tools.http(),
601 Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
602 ));
603 }
604
605 #[cfg(feature = "mysql")]
607 fn test_mysql_pool() -> yang_db::mysql::Database {
608 let pool = sqlx::MySqlPool::connect_lazy("mysql://root:test@127.0.0.1:3306/test")
609 .expect("惰性 MySQL 连接池应创建成功");
610 yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
611 .expect("默认 MySQL 配置应通过校验")
612 }
613
614 #[cfg(feature = "mysql")]
615 fn test_mysql_database() -> AnyDatabase {
616 AnyDatabase::mysql(test_mysql_pool())
617 }
618
619 #[cfg(feature = "postgres")]
621 fn test_postgres_pool() -> yang_db::postgres::Database {
622 let pool = sqlx::PgPool::connect_lazy("postgres://postgres:postgres@127.0.0.1:55432/test")
623 .expect("惰性 PostgreSQL 连接池应创建成功");
624 yang_db::postgres::Database::from_pool(pool, yang_db::postgres::DatabaseConfig::default())
625 .expect("默认 PostgreSQL 配置应通过校验")
626 }
627
628 #[cfg(feature = "postgres")]
629 fn test_postgres_database() -> AnyDatabase {
630 AnyDatabase::postgres(test_postgres_pool())
631 }
632
633 #[cfg(feature = "mysql")]
634 #[tokio::test]
635 async fn mysql_handler_reports_backend_and_pool_status() {
636 let tools = ToolsBuilder::new()
637 .mysql(test_mysql_pool())
638 .build()
639 .expect("配置 MySQL 后应构建成功");
640
641 assert_eq!(
642 tools.database().expect("数据库应存在").backend(),
643 yang_db::BackendKind::MySql
644 );
645 assert!(tools.mysql().is_ok());
646 assert!(tools.pool_status().is_some());
647 assert!(tools.database().expect("数据库应存在").as_mysql().is_some());
648 }
649
650 #[cfg(feature = "postgres")]
651 #[tokio::test]
652 async fn postgres_handler_reports_backend_and_pool_status() {
653 let tools = ToolsBuilder::new()
654 .database(test_postgres_database())
655 .build()
656 .expect("配置 PostgreSQL 后应构建成功");
657
658 assert_eq!(
659 tools.database().expect("数据库应存在").backend(),
660 yang_db::BackendKind::PostgreSql
661 );
662 assert!(tools.pool_status().is_some());
663 assert!(tools
664 .database()
665 .expect("数据库应存在")
666 .as_postgres()
667 .is_some());
668 }
669
670 #[cfg(feature = "mysql")]
671 #[tokio::test]
672 async fn database_slot_errors_after_close() {
673 let tools = ToolsBuilder::new()
674 .database(test_mysql_database())
675 .build()
676 .expect("配置数据库后应构建成功");
677
678 tools.close().await;
679
680 assert!(matches!(
681 tools.database(),
682 Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
683 ));
684 }
685
686 #[cfg(feature = "mysql")]
687 #[tokio::test]
688 async fn duplicate_database_registration_is_rejected_at_build_time() {
689 let result = ToolsBuilder::new()
690 .database(test_mysql_database())
691 .database(test_mysql_database())
692 .build();
693
694 assert!(
695 matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
696 );
697 }
698
699 #[cfg(all(feature = "mysql", feature = "postgres"))]
700 #[tokio::test]
701 async fn mysql_accessor_rejects_postgres_backend() {
702 let tools = ToolsBuilder::new()
703 .database(test_postgres_database())
704 .build()
705 .expect("配置 PostgreSQL 后应构建成功");
706
707 assert_eq!(
708 tools.database().expect("数据库应存在").backend(),
709 yang_db::BackendKind::PostgreSql
710 );
711 assert!(matches!(
712 tools.mysql(),
713 Err(BaseError::DatabaseNotInitialized)
714 ));
715 assert!(tools
716 .database()
717 .expect("数据库应存在")
718 .as_postgres()
719 .is_some());
720 }
721}