Skip to main content

openstranded_plugin_api/
service.rs

1use std::collections::HashMap;
2
3use crate::{ServiceError, Value};
4
5/// Unified interface for cross-plugin calls.
6///
7/// Each plugin registers one or more services that other plugins can call
8/// through `Service::call()`.
9///
10/// # Example
11///
12/// ```rust
13/// use openstranded_plugin_api::{Service, Value, ServiceError};
14///
15/// struct HealthService;
16///
17/// impl Service for HealthService {
18///     fn call(&self, method: &str, args: &[Value]) -> Result<Value, ServiceError> {
19///         match method {
20///             "get_max" => Ok(Value::U32(100)),
21///             _ => Err(ServiceError::UnknownMethod(method.into())),
22///         }
23///     }
24/// }
25/// ```
26pub trait Service: Send + Sync {
27    /// Call a method on this service.
28    ///
29    /// - `method`: method name (case-sensitive string)
30    /// - `args`: call arguments
31    fn call(&self, method: &str, args: &[Value]) -> Result<Value, ServiceError>;
32}
33
34/// Host-side registry of all registered services.
35///
36/// Stores services registered by plugins and provides access by domain name.
37#[derive(Default)]
38pub struct ServiceRegistry {
39    services: HashMap<String, Box<dyn Service>>,
40}
41
42impl ServiceRegistry {
43    /// Create an empty registry.
44    #[must_use]
45    pub fn new() -> Self {
46        Self {
47            services: HashMap::new(),
48        }
49    }
50
51    /// Register a service under the given domain name.
52    ///
53    /// Returns an error if the domain is already taken.
54    pub fn register(
55        &mut self,
56        domain: &str,
57        service: Box<dyn Service>,
58    ) -> Result<(), ServiceError> {
59        let domain = domain.to_owned();
60        if self.services.contains_key(&domain) {
61            return Err(ServiceError::Internal(format!(
62                "service domain '{domain}' is already registered"
63            )));
64        }
65        self.services.insert(domain, service);
66        Ok(())
67    }
68
69    /// Get a reference to a service by domain name.
70    pub fn get(&self, domain: &str) -> Result<&dyn Service, ServiceError> {
71        self.services
72            .get(domain)
73            .map(std::convert::AsRef::as_ref)
74            .ok_or_else(|| ServiceError::DomainNotFound(domain.into()))
75    }
76
77    /// Check whether a domain is registered.
78    #[must_use]
79    pub fn has(&self, domain: &str) -> bool {
80        self.services.contains_key(domain)
81    }
82
83    /// Remove a service by domain name.
84    pub fn unregister(&mut self, domain: &str) -> Option<Box<dyn Service>> {
85        self.services.remove(domain)
86    }
87
88    /// Number of registered services.
89    #[must_use]
90    pub fn len(&self) -> usize {
91        self.services.len()
92    }
93
94    /// Whether the registry is empty.
95    #[must_use]
96    pub fn is_empty(&self) -> bool {
97        self.services.is_empty()
98    }
99
100    /// Iterate over all registered domain names.
101    pub fn domains(&self) -> impl Iterator<Item = &str> {
102        self.services.keys().map(std::string::String::as_str)
103    }
104}
105
106// ── Tests ──────────────────────────────────────────────────────────
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    struct TestService;
113
114    impl Service for TestService {
115        fn call(&self, method: &str, _args: &[Value]) -> Result<Value, ServiceError> {
116            match method {
117                "ping" => Ok(Value::String("pong".into())),
118                _ => Err(ServiceError::UnknownMethod(method.into())),
119            }
120        }
121    }
122
123    #[test]
124    fn test_register_and_get() {
125        let mut registry = ServiceRegistry::new();
126        registry.register("test", Box::new(TestService)).unwrap();
127        let svc = registry.get("test").unwrap();
128        let result = svc.call("ping", &[]).unwrap();
129        assert_eq!(result, Value::String("pong".into()));
130    }
131
132    #[test]
133    fn test_get_unknown_domain() {
134        let registry = ServiceRegistry::new();
135        let result = registry.get("nonexistent");
136        assert!(result.is_err());
137        // ServiceError:DomainNotFound — checked by type
138    }
139
140    #[test]
141    fn test_register_duplicate() {
142        let mut registry = ServiceRegistry::new();
143        registry.register("test", Box::new(TestService)).unwrap();
144        let err = registry.register("test", Box::new(TestService)).unwrap_err();
145        assert!(matches!(err, ServiceError::Internal(..)));
146    }
147
148    #[test]
149    fn test_has() {
150        let mut registry = ServiceRegistry::new();
151        assert!(!registry.has("test"));
152        registry.register("test", Box::new(TestService)).unwrap();
153        assert!(registry.has("test"));
154    }
155
156    #[test]
157    fn test_unregister() {
158        let mut registry = ServiceRegistry::new();
159        registry.register("test", Box::new(TestService)).unwrap();
160        assert!(registry.unregister("test").is_some());
161        assert!(!registry.has("test"));
162    }
163
164    #[test]
165    fn test_domains_iter() {
166        let mut registry = ServiceRegistry::new();
167        registry.register("a", Box::new(TestService)).unwrap();
168        registry.register("b", Box::new(TestService)).unwrap();
169        let domains: Vec<&str> = registry.domains().collect();
170        assert_eq!(domains.len(), 2);
171        assert!(domains.contains(&"a"));
172        assert!(domains.contains(&"b"));
173    }
174}