product_os_capabilities/
lib.rs

1#![no_std]
2extern crate no_std_compat as std;
3
4use std::prelude::v1::*;
5
6
7pub use async_trait::async_trait;
8
9use std::fmt::{Debug, Formatter};
10use std::sync::Arc;
11use parking_lot::Mutex;
12
13use serde::{Deserialize, Serialize};
14use chrono::{DateTime, Utc};
15
16mod features;
17mod services;
18
19pub use features::Features;
20use product_os_router::{Body, ProductOSRouter, Request, Response};
21use serde_json::Value;
22pub use services::Services;
23
24
25
26
27
28
29
30#[derive(Deserialize, Serialize)]
31#[serde(rename_all = "camelCase")]
32pub struct RegistryFeature {
33    pub identifier: String,
34    pub paths: Vec<String>,
35    #[serde(skip, default = "default_feature")]
36    pub feature: Option<Arc<dyn Feature>>,
37    #[serde(skip, default = "default_feature_mut")]
38    pub feature_mut: Option<Arc<Mutex<dyn Feature>>>
39}
40
41impl Debug for RegistryFeature {
42    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
43        write!(f, "Identifier: {}\nPaths: {:?}\n", self.identifier, self.paths)
44    }
45}
46
47impl RegistryFeature {
48
49}
50
51fn default_feature() -> Option<Arc<dyn Feature>> {
52    Some(Arc::new(DefaultFeature {}))
53}
54
55fn default_feature_mut() -> Option<Arc<Mutex<dyn Feature>>> {
56    Some(Arc::new(Mutex::new(DefaultFeature {})))
57}
58
59
60pub enum What {
61    Characteristic(String),
62    Id(u8)
63}
64
65
66#[derive(Deserialize, Serialize)]
67#[serde(rename_all = "camelCase")]
68pub struct RegistryService {
69    pub identifier: String,
70    pub key: String,
71    #[serde(rename = "type")]
72    pub kind: String,
73    pub active: bool,
74    pub enabled: bool,
75    pub created_at: DateTime<Utc>,
76    pub updated_at: DateTime<Utc>,
77    #[serde(skip, default = "default_service")]
78    pub service: Option<Arc<dyn Service>>,
79    #[serde(skip, default = "default_service_mut")]
80    pub service_mut: Option<Arc<Mutex<dyn Service>>>
81}
82
83impl Debug for RegistryService {
84    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
85        write!(f, "Identifier: {}\nKey: {}\nEnabled: {}\nActive:{:?}", self.identifier, self.key, self.enabled, self.active)
86    }
87}
88
89impl RegistryService {
90    pub fn identifier(&self) -> String {
91        self.identifier.to_owned()
92    }
93
94    pub fn key(&self) -> String {
95        self.key.to_owned()
96    }
97
98    pub fn is_enabled(&self) -> bool {
99        self.enabled
100    }
101
102    pub fn is_active(&self) -> bool {
103        self.active
104    }
105
106    pub async fn status(&self) -> Result<(), ()> {
107        match &self.service {
108            Some(service) => service.status().await,
109            None => {
110                match &self.service_mut {
111                    Some(service) => {
112                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
113
114                        match service_locked {
115                            None => Err(()),
116                            Some(service) => service.status().await
117                        }
118                    }
119                    None => Err(())
120                }
121            }
122        }
123    }
124
125    pub async fn init(&mut self) -> Result<(), ()> {
126        match &self.service {
127            Some(service) => service.init_service().await,
128            None => {
129                match &self.service_mut {
130                    Some(service) => {
131                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
132
133                        match service_locked {
134                            None => Err(()),
135                            Some(mut service) => service.init_service_mut().await
136                        }
137                    }
138                    None => Err(())
139                }
140            }
141        }
142    }
143
144    pub async fn start(&mut self) -> Result<(), ()> {
145        match &self.service {
146            Some(service) => service.start().await,
147            None => {
148                match &self.service_mut {
149                    Some(service) => {
150                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
151
152                        match service_locked {
153                            None => Err(()),
154                            Some(mut service) => service.start_mut().await
155                        }
156                    }
157                    None => Err(())
158                }
159            }
160        }
161    }
162
163    pub async fn stop(&mut self) -> Result<(), ()> {
164        match &self.service {
165            Some(service) => service.stop().await,
166            None => {
167                match &self.service_mut {
168                    Some(service) => {
169                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
170
171                        match service_locked {
172                            None => Err(()),
173                            Some(mut service) => service.stop_mut().await
174                        }
175                    }
176                    None => Err(())
177                }
178            }
179        }
180    }
181
182    pub async fn restart(&mut self) -> Result<(), ()> {
183        match &self.service {
184            Some(service) => service.restart().await,
185            None => {
186                match &self.service_mut {
187                    Some(service) => {
188                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
189
190                        match service_locked {
191                            None => Err(()),
192                            Some(mut service) => service.restart_mut().await
193                        }
194                    }
195                    None => Err(())
196                }
197            }
198        }
199    }
200
201    pub async fn call(&mut self, action: &What, input: &Option<serde_json::Value>) -> Result<Option<serde_json::Value>, ServiceError> {
202        match &self.service {
203            Some(service) => service.call(action, input).await,
204            None => {
205                match &self.service_mut {
206                    Some(service) => {
207                        let service_locked = service.try_lock_for(core::time::Duration::new(10, 0));
208
209                        match service_locked {
210                            None => Err(ServiceError::GenericError("Unable to lock service".to_string())),
211                            Some(mut service) => service.call_mut(action, input).await
212                        }
213                    }
214                    None => Err(ServiceError::GenericError("No service mutable set".to_string()))
215                }
216            }
217        }
218    }
219}
220
221
222fn default_service() -> Option<Arc<dyn Service>> {
223    Some(Arc::new(DefaultService {}))
224}
225
226
227fn default_service_mut() -> Option<Arc<Mutex<dyn Service>>> {
228    Some(Arc::new(Mutex::new(DefaultService {})))
229}
230
231
232
233#[async_trait]
234pub trait Feature: Send + Sync {
235    async fn register(&self, feature: Arc<dyn Feature>, base_path: String, router: &mut product_os_router::ProductOSRouter) -> RegistryFeature;
236    async fn register_mut(&self, feature: Arc<Mutex<dyn Feature>>, base_path: String, router: &mut product_os_router::ProductOSRouter) -> RegistryFeature;
237    fn identifier(&self) -> String;
238    async fn request(&self, action: &What, input: &Option<serde_json::Value>, semver: &str) -> Response<Body>;
239    async fn request_mut(&mut self, action: &What, input: &Option<serde_json::Value>, semver: &str) -> Response<Body>;
240    async fn init_feature(&self) -> Result<(), ()> { Ok(()) }
241    async fn init_feature_mut(&mut self) -> Result<(), ()> { Ok(()) }
242}
243
244
245pub struct DefaultFeature {}
246
247#[async_trait]
248impl Feature for DefaultFeature {
249    async fn register(&self, feature: Arc<dyn Feature>, _: String, _: &mut ProductOSRouter) -> RegistryFeature {
250        RegistryFeature {
251            identifier: "".to_string(),
252            paths: vec![],
253            feature: Some(feature),
254            feature_mut: None
255        }
256    }
257
258    async fn register_mut(&self, feature: Arc<Mutex<dyn Feature>>, _: String, _: &mut ProductOSRouter) -> RegistryFeature {
259        RegistryFeature {
260            identifier: "".to_string(),
261            paths: vec![],
262            feature: None,
263            feature_mut: Some(feature)
264        }
265    }
266
267    fn identifier(&self) -> String {
268        "default".to_string()
269    }
270
271    async fn request(&self, action: &What, input: &Option<Value>, semver: &str) -> Response<Body> {
272        Response::default()
273    }
274
275    async fn request_mut(&mut self, action: &What, input: &Option<Value>, semver: &str) -> Response<Body> {
276        Response::default()
277    }
278}
279
280
281pub enum ServiceError {
282    GenericError(String)
283}
284
285impl std::fmt::Display for ServiceError {
286    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
287        match self {
288            ServiceError::GenericError(s) => write!(f, "{}", s)
289        }
290    }
291}
292
293
294
295
296#[async_trait]
297pub trait Service: Send + Sync {
298    async fn register(&self, service: Arc<dyn Service>) -> RegistryService;
299    async fn register_mut(&self, service: Arc<Mutex<dyn Service>>) -> RegistryService;
300    fn identifier(&self) -> String;
301    fn key(&self) -> String;
302    fn is_enabled(&self) -> bool;
303    fn is_active(&self) -> bool;
304    async fn status(&self) -> Result<(), ()>;
305    async fn init_service(&self) -> Result<(), ()> { Ok(()) }
306    async fn start(&self) -> Result<(), ()>;
307    async fn stop(&self) -> Result<(), ()>;
308
309    async fn call(&self, action: &What, input: &Option<serde_json::Value>) -> Result<Option<serde_json::Value>, ServiceError> {
310        Ok(None)
311    }
312    async fn restart(&self) -> Result<(), ()>;
313    async fn init_service_mut(&mut self) -> Result<(), ()> { Ok(()) }
314    async fn start_mut(&mut self) -> Result<(), ()>;
315    async fn stop_mut(&mut self) -> Result<(), ()>;
316    async fn restart_mut(&mut self) -> Result<(), ()>;
317
318    async fn call_mut(&mut self, action: &What, input: &Option<serde_json::Value>) -> Result<Option<serde_json::Value>, ServiceError> {
319        Ok(None)
320    }
321}
322
323
324
325pub struct DefaultService {}
326
327#[async_trait]
328impl Service for DefaultService {
329    async fn register(&self, service: Arc<dyn Service>) -> RegistryService {
330        RegistryService {
331            identifier: "".to_string(),
332            key: "".to_string(),
333            kind: "".to_string(),
334            active: false,
335            enabled: false,
336            created_at: Utc::now(),
337            updated_at: Utc::now(),
338            service: Some(service),
339            service_mut: None
340        }
341    }
342
343    async fn register_mut(&self, service: Arc<Mutex<dyn Service>>) -> RegistryService {
344        RegistryService {
345            identifier: "".to_string(),
346            key: "".to_string(),
347            kind: "".to_string(),
348            active: false,
349            enabled: false,
350            created_at: Utc::now(),
351            updated_at: Utc::now(),
352            service: None,
353            service_mut: Some(service)
354        }
355    }
356
357    fn identifier(&self) -> String {
358        "default".to_string()
359    }
360
361    fn key(&self) -> String {
362        "key".to_string()
363    }
364
365    fn is_enabled(&self) -> bool {
366        false
367    }
368
369    fn is_active(&self) -> bool {
370        false
371    }
372
373    async fn status(&self) -> Result<(), ()> { Ok(()) }
374
375    async fn init_service(&self) -> Result<(), ()> { Ok(()) }
376
377    async fn start(&self) -> Result<(), ()> { Ok(()) }
378
379    async fn stop(&self) -> Result<(), ()> { Ok(()) }
380
381    async fn restart(&self) -> Result<(), ()> { Ok(()) }
382
383    async fn call(&self, action: &What, input: &Option<serde_json::Value>) -> Result<Option<serde_json::Value>, ServiceError> {
384        Ok(None)
385    }
386
387    async fn init_service_mut(&mut self) -> Result<(), ()> { Ok(()) }
388
389    async fn start_mut(&mut self) -> Result<(), ()> { Ok(()) }
390
391    async fn stop_mut(&mut self) -> Result<(), ()> { Ok(()) }
392
393    async fn restart_mut(&mut self) -> Result<(), ()> { Ok(()) }
394
395    async fn call_mut(&mut self, action: &What, input: &Option<serde_json::Value>) -> Result<Option<serde_json::Value>, ServiceError> {
396        Ok(None)
397    }
398}
399
400
401#[cfg(feature = "feature_service")]
402pub trait FeatureService: Feature + Service {}