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