unit.rs (1522B)
1 use std::cell::RefCell; 2 use std::rc::Rc; 3 use std::sync::Arc; 4 5 use async_trait::async_trait; 6 use send_wrapper::SendWrapper; 7 8 use kanit_common::error::Result; 9 10 use crate::Dependencies; 11 12 // has to be async lock to allow querying without possible blocks 13 pub type RcUnit = SendWrapper<Rc<RefCell<dyn Unit>>>; 14 pub type UnitName = Arc<str>; 15 16 /// Unit lifecycle: 17 /// 18 /// 19 /// Startup: 20 /// ```rs 21 /// if !unit.prepare().await? { return; } 22 /// 23 /// unit.start().await?; 24 /// ``` 25 /// 26 /// Stop: 27 /// ```rs 28 /// unit.stop().await?; 29 /// unit.teardown().await?; 30 /// ``` 31 /// 32 /// Restart: 33 /// ```rs 34 /// unit.stop().await?; 35 /// unit.start().await?; 36 /// ``` 37 #[async_trait] 38 pub trait Unit: Send + Sync { 39 /// The name of the unit. 40 fn name(&self) -> UnitName; 41 42 /// A description of the unit. 43 fn description(&self) -> Option<&str> { 44 None 45 } 46 47 /// Dependencies of the unit. 48 fn dependencies(&self) -> Dependencies { 49 Dependencies::new() 50 } 51 52 /// Starts the unit. 53 async fn start(&mut self) -> Result<()> { 54 Ok(()) 55 } 56 57 /// Called when a unit is ordered to stop or as a step in restarting. 58 async fn stop(&mut self) -> Result<()> { 59 Ok(()) 60 } 61 62 /// Preconditions for starting a unit. 63 async fn prepare(&self) -> Result<bool> { 64 Ok(true) 65 } 66 67 /// Tearing down a unit once finished. 68 async fn teardown(&self) -> Result<()> { 69 Ok(()) 70 } 71 } 72 73 pub fn wrap_unit<U: Unit + 'static>(unit: U) -> RcUnit { 74 SendWrapper::new(Rc::new(RefCell::new(unit))) 75 }