1use crate::error::BaseError;
7use std::any::{type_name, Any, TypeId};
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::atomic::{AtomicU8, Ordering};
11use tokio::sync::Mutex;
12
13#[cfg(feature = "http")]
14use crate::http::HttpClient;
15#[cfg(feature = "token")]
16use crate::token::TokenManager;
17#[cfg(feature = "mysql")]
18use yang_db::Database;
19#[cfg(feature = "redis")]
20use yang_db::RedisClient;
21
22const RUNNING: u8 = 0;
23const CLOSING: u8 = 1;
24const CLOSED: u8 = 2;
25
26type TypeMap = HashMap<TypeId, Box<dyn Any + Send + Sync>>;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ToolsState {
31 Running,
33 Closing,
35 Closed,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct ResourceHealth {
42 pub resource: &'static str,
44 pub healthy: bool,
46 pub detail: Option<String>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct ToolsHealth {
53 pub state: ToolsState,
55 pub resources: Vec<ResourceHealth>,
57}
58
59impl ToolsHealth {
60 pub fn is_healthy(&self) -> bool {
62 self.state == ToolsState::Running && self.resources.iter().all(|item| item.healthy)
63 }
64}
65
66pub struct Tools {
68 #[cfg(feature = "mysql")]
69 mysql: Option<Database>,
70 #[cfg(feature = "redis")]
71 cache: Option<RedisClient>,
72 #[cfg(feature = "token")]
73 token: Option<TokenManager>,
74 #[cfg(feature = "http")]
75 http: Option<HttpClient>,
76 extensions: TypeMap,
77 config: TypeMap,
78 state: AtomicU8,
79 close_lock: Mutex<()>,
80}
81
82impl fmt::Debug for Tools {
83 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84 formatter
85 .debug_struct("Tools")
86 .field("state", &self.state())
87 .field("extension_count", &self.extensions.len())
88 .field("config_count", &self.config.len())
89 .finish_non_exhaustive()
90 }
91}
92
93impl Tools {
94 pub fn state(&self) -> ToolsState {
96 match self.state.load(Ordering::Acquire) {
97 RUNNING => ToolsState::Running,
98 CLOSING => ToolsState::Closing,
99 _ => ToolsState::Closed,
100 }
101 }
102
103 fn ensure_running(&self) -> Result<(), BaseError> {
104 match self.state() {
105 ToolsState::Running => Ok(()),
106 ToolsState::Closing => Err(BaseError::ConfigError("Tools 正在关闭".to_string())),
107 ToolsState::Closed => Err(BaseError::ConfigError("Tools 已关闭".to_string())),
108 }
109 }
110
111 #[cfg(feature = "mysql")]
113 pub fn mysql(&self) -> Result<&Database, BaseError> {
114 self.ensure_running()?;
115 self.mysql.as_ref().ok_or(BaseError::DatabaseNotInitialized)
116 }
117
118 #[cfg(feature = "mysql")]
120 pub(crate) fn optional_mysql(&self) -> Result<Option<&Database>, BaseError> {
121 self.ensure_running()?;
122 Ok(self.mysql.as_ref())
123 }
124
125 #[cfg(feature = "redis")]
127 pub fn cache(&self) -> Result<&RedisClient, BaseError> {
128 self.ensure_running()?;
129 self.cache.as_ref().ok_or(BaseError::RedisNotInitialized)
130 }
131
132 #[cfg(feature = "token")]
134 pub fn token(&self) -> Result<&TokenManager, BaseError> {
135 self.ensure_running()?;
136 self.token
137 .as_ref()
138 .ok_or_else(|| BaseError::ConfigError("Tools 未配置 TokenManager".to_string()))
139 }
140
141 #[cfg(feature = "http")]
145 pub fn http(&self) -> Result<&HttpClient, BaseError> {
146 self.ensure_running()?;
147 self.http
148 .as_ref()
149 .ok_or(BaseError::HttpClientNotInitialized)
150 }
151
152 pub fn extension<T>(&self) -> Result<&T, BaseError>
154 where
155 T: Any + Send + Sync,
156 {
157 self.ensure_running()?;
158 self.extensions
159 .get(&TypeId::of::<T>())
160 .and_then(|value| value.downcast_ref::<T>())
161 .ok_or_else(|| {
162 BaseError::ConfigError(format!("Tools 未配置扩展: {}", type_name::<T>()))
163 })
164 }
165
166 pub fn config<T>(&self) -> Result<&T, BaseError>
168 where
169 T: Any + Send + Sync,
170 {
171 self.ensure_running()?;
172 self.config
173 .get(&TypeId::of::<T>())
174 .and_then(|value| value.downcast_ref::<T>())
175 .ok_or_else(|| {
176 BaseError::ConfigError(format!("Tools 未配置配置类型: {}", type_name::<T>()))
177 })
178 }
179
180 pub async fn health_check(&self) -> ToolsHealth {
182 let state = self.state();
183 if state != ToolsState::Running {
184 return ToolsHealth {
185 state,
186 resources: Vec::new(),
187 };
188 }
189
190 #[cfg(any(feature = "mysql", feature = "redis"))]
191 let mut resources = Vec::new();
192 #[cfg(not(any(feature = "mysql", feature = "redis")))]
193 let resources = Vec::new();
194 #[cfg(feature = "mysql")]
195 if let Some(mysql) = &self.mysql {
196 resources.push(match mysql.health_check().await {
197 Ok(healthy) => ResourceHealth {
198 resource: "mysql",
199 healthy,
200 detail: None,
201 },
202 Err(error) => ResourceHealth {
203 resource: "mysql",
204 healthy: false,
205 detail: Some(error.to_string()),
206 },
207 });
208 }
209 #[cfg(feature = "redis")]
210 if let Some(cache) = &self.cache {
211 resources.push(match cache.health_check().await {
212 Ok(healthy) => ResourceHealth {
213 resource: "cache",
214 healthy,
215 detail: None,
216 },
217 Err(error) => ResourceHealth {
218 resource: "cache",
219 healthy: false,
220 detail: Some(error.to_string()),
221 },
222 });
223 }
224
225 ToolsHealth { state, resources }
226 }
227
228 pub async fn close(&self) {
232 let _guard = self.close_lock.lock().await;
233 if self.state() == ToolsState::Closed {
234 return;
235 }
236 self.state.store(CLOSING, Ordering::Release);
237
238 #[cfg(feature = "redis")]
239 if let Some(cache) = &self.cache {
240 cache.close().await;
241 }
242 #[cfg(feature = "mysql")]
243 if let Some(mysql) = &self.mysql {
244 mysql.close().await;
245 }
246
247 self.state.store(CLOSED, Ordering::Release);
248 }
249}
250
251#[derive(Default)]
253#[must_use = "ToolsBuilder 必须调用 build() 才会冻结并交给应用"]
254pub struct ToolsBuilder {
255 #[cfg(feature = "mysql")]
256 mysql: Option<Database>,
257 #[cfg(feature = "redis")]
258 cache: Option<RedisClient>,
259 #[cfg(feature = "token")]
260 token: Option<TokenManager>,
261 #[cfg(feature = "http")]
262 http: Option<HttpClient>,
263 extensions: TypeMap,
264 config: TypeMap,
265 duplicate: Option<String>,
266}
267
268impl fmt::Debug for ToolsBuilder {
269 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
270 formatter
271 .debug_struct("ToolsBuilder")
272 .field("extension_count", &self.extensions.len())
273 .field("config_count", &self.config.len())
274 .field("duplicate", &self.duplicate)
275 .finish_non_exhaustive()
276 }
277}
278
279impl ToolsBuilder {
280 pub fn new() -> Self {
282 Self::default()
283 }
284
285 #[cfg(feature = "mysql")]
287 pub fn mysql(mut self, mysql: Database) -> Self {
288 if self.mysql.replace(mysql).is_some() {
289 self.record_duplicate("MySQL");
290 }
291 self
292 }
293
294 #[cfg(feature = "redis")]
296 pub fn cache(mut self, cache: RedisClient) -> Self {
297 if self.cache.replace(cache).is_some() {
298 self.record_duplicate("RedisClient");
299 }
300 self
301 }
302
303 #[cfg(feature = "token")]
305 pub fn token(mut self, token: TokenManager) -> Self {
306 if self.token.replace(token).is_some() {
307 self.record_duplicate("TokenManager");
308 }
309 self
310 }
311
312 #[cfg(feature = "http")]
316 pub fn http(mut self, client: HttpClient) -> Self {
317 if self.http.replace(client).is_some() {
318 self.record_duplicate("HttpClient");
319 }
320 self
321 }
322
323 pub fn extension<T>(mut self, extension: T) -> Self
325 where
326 T: Any + Send + Sync,
327 {
328 if self
329 .extensions
330 .insert(TypeId::of::<T>(), Box::new(extension))
331 .is_some()
332 {
333 self.record_duplicate(type_name::<T>());
334 }
335 self
336 }
337
338 pub fn config<T>(mut self, config: T) -> Self
340 where
341 T: Any + Send + Sync,
342 {
343 if self
344 .config
345 .insert(TypeId::of::<T>(), Box::new(config))
346 .is_some()
347 {
348 self.record_duplicate(type_name::<T>());
349 }
350 self
351 }
352
353 fn record_duplicate(&mut self, resource: &str) {
354 if self.duplicate.is_none() {
355 self.duplicate = Some(resource.to_string());
356 }
357 }
358
359 pub fn build(self) -> Result<Tools, BaseError> {
361 if let Some(resource) = self.duplicate {
362 return Err(BaseError::ConfigError(format!(
363 "Tools 资源重复注册: {resource}"
364 )));
365 }
366
367 #[cfg(feature = "token")]
368 let token = {
369 let mut token = self.token;
370 if let (Some(token), Some(cache)) = (&mut token, &self.cache) {
371 token.attach_revocation_cache(cache.clone());
372 }
373 token
374 };
375
376 Ok(Tools {
377 #[cfg(feature = "mysql")]
378 mysql: self.mysql,
379 #[cfg(feature = "redis")]
380 cache: self.cache,
381 #[cfg(feature = "token")]
382 token,
383 #[cfg(feature = "http")]
384 http: self.http,
385 extensions: self.extensions,
386 config: self.config,
387 state: AtomicU8::new(RUNNING),
388 close_lock: Mutex::new(()),
389 })
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[derive(Debug, PartialEq, Eq)]
398 struct TestExtension(u32);
399
400 #[derive(Debug, PartialEq, Eq)]
401 struct TestConfig(&'static str);
402
403 #[test]
404 fn typed_entries_are_frozen_and_separate() {
405 let tools = ToolsBuilder::new()
406 .extension(TestExtension(7))
407 .config(TestConfig("local"))
408 .build()
409 .expect("类型化资源应构建成功");
410
411 assert_eq!(
412 tools.extension::<TestExtension>().expect("扩展应存在"),
413 &TestExtension(7)
414 );
415 assert_eq!(
416 tools.config::<TestConfig>().expect("配置应存在"),
417 &TestConfig("local")
418 );
419 assert!(tools.extension::<TestConfig>().is_err());
420 assert!(tools.config::<TestExtension>().is_err());
421 }
422
423 #[test]
424 fn duplicate_type_is_rejected_at_build_time() {
425 let result = ToolsBuilder::new()
426 .extension(TestExtension(1))
427 .extension(TestExtension(2))
428 .build();
429 assert!(
430 matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
431 );
432 }
433
434 #[tokio::test]
435 async fn close_is_idempotent_and_changes_health_semantics() {
436 let tools = ToolsBuilder::new()
437 .build()
438 .expect("空资源集合可用于纯逻辑测试");
439 assert!(tools.health_check().await.is_healthy());
440
441 tools.close().await;
442 tools.close().await;
443
444 let health = tools.health_check().await;
445 assert_eq!(health.state, ToolsState::Closed);
446 assert!(!health.is_healthy());
447 assert!(matches!(
448 tools.extension::<TestExtension>(),
449 Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
450 ));
451 }
452
453 #[cfg(feature = "http")]
454 fn test_http_client() -> crate::http::HttpClient {
455 crate::http::HttpClient::new(30).expect("测试 HTTP 客户端应创建成功")
456 }
457
458 #[cfg(feature = "http")]
459 #[test]
460 fn http_slot_returns_client_when_configured() {
461 let tools = ToolsBuilder::new()
462 .http(test_http_client())
463 .build()
464 .expect("配置 HTTP 客户端后应构建成功");
465
466 let client = tools.http().expect("已配置时应返回 HTTP 客户端");
467 let _builder = client.get("https://api.example.com/test");
469 }
470
471 #[cfg(feature = "http")]
472 #[test]
473 fn http_slot_errors_when_not_configured() {
474 let tools = ToolsBuilder::new().build().expect("空资源集合应构建成功");
475
476 assert!(matches!(
477 tools.http(),
478 Err(BaseError::HttpClientNotInitialized)
479 ));
480 }
481
482 #[cfg(feature = "http")]
483 #[test]
484 fn http_slot_duplicate_registration_is_rejected_at_build_time() {
485 let result = ToolsBuilder::new()
486 .http(test_http_client())
487 .http(test_http_client())
488 .build();
489
490 assert!(
491 matches!(result, Err(BaseError::ConfigError(message)) if message.contains("重复注册"))
492 );
493 }
494
495 #[cfg(feature = "http")]
496 #[tokio::test]
497 async fn http_slot_errors_after_close() {
498 let tools = ToolsBuilder::new()
499 .http(test_http_client())
500 .build()
501 .expect("配置 HTTP 客户端后应构建成功");
502
503 tools.close().await;
504
505 assert!(matches!(
506 tools.http(),
507 Err(BaseError::ConfigError(message)) if message == "Tools 已关闭"
508 ));
509 }
510}