Skip to main content

sz_rust_capability/
facade.rs

1use std::sync::{Arc, OnceLock};
2
3use crate::capability::Capability;
4use crate::error::{CapError, CapResult};
5use crate::metrics::CapMetrics;
6use crate::permission::PermissionChecker;
7use crate::registry::CapabilityRegistry;
8use crate::source::CapabilitySource;
9
10struct CapInstance {
11    registry: CapabilityRegistry,
12}
13
14static GLOBAL: OnceLock<CapInstance> = OnceLock::new();
15
16/// Capability Registry 全局 facade,对齐 `Ai` facade 模式。
17///
18/// 使用 `OnceLock<CapInstance>` 全局单例,所有静态方法通过 `instance()` 获取后委托给内部 [`CapabilityRegistry`]。
19///
20/// # 使用方式
21///
22/// ```no_run
23/// use sz_rust_capability::Cap;
24///
25/// Cap::init().ok(); // 初始化(仅需一次)
26/// let metrics = Cap::metrics().unwrap();
27/// ```
28pub struct Cap;
29
30impl Cap {
31    pub fn init() -> CapResult<()> {
32        GLOBAL
33            .set(CapInstance {
34                registry: CapabilityRegistry::new(),
35            })
36            .map_err(|_| CapError::NotInitialized)
37    }
38
39    pub fn is_initialized() -> bool {
40        GLOBAL.get().is_some()
41    }
42
43    fn instance() -> CapResult<&'static CapInstance> {
44        GLOBAL.get().ok_or(CapError::NotInitialized)
45    }
46
47    pub fn register(cap: Arc<dyn Capability>) -> CapResult<Option<Arc<dyn Capability>>> {
48        Ok(Self::instance()?.registry.register(cap))
49    }
50
51    pub fn unregister(name: &str) -> CapResult<Option<Arc<dyn Capability>>> {
52        Ok(Self::instance()?.registry.unregister(name))
53    }
54
55    pub fn get(name: &str) -> CapResult<Option<Arc<dyn Capability>>> {
56        Ok(Self::instance()?.registry.get(name))
57    }
58
59    pub fn find_by_tags(
60        tags: &[&str],
61        source: Option<CapabilitySource>,
62    ) -> CapResult<Vec<Arc<dyn Capability>>> {
63        Ok(Self::instance()?.registry.find_by_tags(tags, source))
64    }
65
66    pub fn search(query: &str) -> CapResult<Vec<Arc<dyn Capability>>> {
67        Ok(Self::instance()?.registry.search(query))
68    }
69
70    pub fn list_all() -> CapResult<Vec<Arc<dyn Capability>>> {
71        Ok(Self::instance()?.registry.list_all())
72    }
73
74    pub fn list_by_source(source: CapabilitySource) -> CapResult<Vec<Arc<dyn Capability>>> {
75        Ok(Self::instance()?.registry.list_by_source(source))
76    }
77
78    pub async fn call(name: &str, args: serde_json::Value) -> CapResult<serde_json::Value> {
79        Self::instance()?.registry.call(name, args).await
80    }
81
82    /// 调用能力,携带租户上下文用于权限检查。
83    pub async fn call_with_tenant(
84        name: &str,
85        args: serde_json::Value,
86        tenant_id: i64,
87    ) -> CapResult<serde_json::Value> {
88        Self::instance()?
89            .registry
90            .call_with_tenant(name, args, tenant_id)
91            .await
92    }
93
94    /// 设置权限检查器。
95    pub fn set_permission_checker(checker: Arc<dyn PermissionChecker>) -> CapResult<()> {
96        Self::instance()?.registry.set_permission_checker(checker);
97        Ok(())
98    }
99
100    pub fn metrics() -> CapResult<CapMetrics> {
101        Ok(Self::instance()?.registry.metrics())
102    }
103
104    pub fn len() -> CapResult<usize> {
105        Ok(Self::instance()?.registry.len())
106    }
107
108    pub fn is_empty() -> CapResult<bool> {
109        Ok(Self::instance()?.registry.is_empty())
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use async_trait::async_trait;
117    use serde_json::json;
118
119    struct TestCapability;
120
121    #[async_trait]
122    impl Capability for TestCapability {
123        fn name(&self) -> &'static str {
124            "test_cap"
125        }
126        fn description(&self) -> &'static str {
127            "测试能力"
128        }
129        fn schema(&self) -> serde_json::Value {
130            json!({})
131        }
132        fn tags(&self) -> &[&'static str] {
133            &["test"]
134        }
135        fn source(&self) -> CapabilitySource {
136            CapabilitySource::Skill
137        }
138        async fn call(&self, args: serde_json::Value) -> CapResult<serde_json::Value> {
139            Ok(args)
140        }
141    }
142
143    #[test]
144    fn test_facade_lifecycle() {
145        Cap::init().ok();
146        let cap = Arc::new(TestCapability) as Arc<dyn Capability>;
147        Cap::register(cap).unwrap();
148        assert!(Cap::get("test_cap").unwrap().is_some());
149        assert!(Cap::len().unwrap() >= 1);
150    }
151
152    #[tokio::test]
153    async fn test_call_through_facade() {
154        Cap::init().ok();
155        let cap = Arc::new(TestCapability) as Arc<dyn Capability>;
156        Cap::register(cap).ok();
157        let result = Cap::call("test_cap", json!({"hello": "world"})).await;
158        assert!(result.is_ok());
159    }
160}