Skip to main content

openlark_client/traits/
service.rs

1//! OpenLark Service 核心特征
2//!
3//! 定义服务的统一接口和行为
4
5use crate::Result;
6
7/// 🌐 服务基础特征
8///
9/// 所有服务实现都应该实现此特征
10///
11/// # 特性要求
12/// - 异步支持:所有操作都是异步的
13/// - 线程安全:服务可以跨线程安全使用
14/// - 生命周期:支持服务的启动、停止和重启
15pub trait ServiceTrait: Send + Sync {
16    /// 📋 服务名称
17    fn name(&self) -> &'static str;
18
19    /// 🔢 服务版本
20    fn version(&self) -> &'static str {
21        "1.0.0"
22    }
23
24    /// 📝 服务描述
25    fn description(&self) -> &'static str {
26        "OpenLark Service"
27    }
28
29    /// ✅ 检查服务健康状态
30    async fn health_check(&self) -> Result<bool>;
31
32    /// 🔄 启动服务
33    async fn start(&self) -> Result<()> {
34        tracing::info!("服务 '{}' 启动", self.name());
35        Ok(())
36    }
37
38    /// 🛑 停止服务
39    async fn stop(&self) -> Result<()> {
40        tracing::info!("服务 '{}' 停止", self.name());
41        Ok(())
42    }
43}
44
45/// 🔄 服务生命周期特征
46///
47/// 定义服务的启动、停止和健康检查生命周期管理
48pub trait ServiceLifecycle: Send + Sync {
49    /// 🚀 启动服务
50    async fn start(&self) -> Result<()> {
51        tracing::info!("服务启动");
52        Ok(())
53    }
54
55    /// 🛑 停止服务
56    async fn stop(&self) -> Result<()> {
57        tracing::info!("服务停止");
58        Ok(())
59    }
60
61    /// 🔄 重启服务
62    async fn restart(&self) -> Result<()> {
63        tracing::info!("服务重启");
64        self.stop().await?;
65        self.start().await
66    }
67
68    /// ✅ 健康检查
69    async fn health_check(&self) -> Result<bool> {
70        Ok(true)
71    }
72}
73
74#[cfg(test)]
75#[allow(unused_imports)]
76mod tests {
77    use super::*;
78
79    struct TestService {
80        name: &'static str,
81    }
82
83    impl ServiceTrait for TestService {
84        fn name(&self) -> &'static str {
85            self.name
86        }
87
88        async fn health_check(&self) -> Result<bool> {
89            Ok(true)
90        }
91    }
92
93    #[tokio::test]
94    async fn test_service_trait() {
95        let service = TestService {
96            name: "test_service",
97        };
98
99        assert_eq!(service.name(), "test_service");
100        assert_eq!(service.version(), "1.0.0");
101        assert_eq!(service.description(), "OpenLark Service");
102
103        let health = service.health_check().await;
104        assert!(health.is_ok());
105        assert!(health.unwrap());
106    }
107}