use std::sync::RwLock; use super::{InvalidTransition, LifecycleState}; pub struct AppState { lifecycle: RwLock, } impl AppState { pub fn new() -> Self { Self::default() } pub fn lifecycle(&self) -> eros::Result { self.lifecycle .read() .map(|lifecycle| *lifecycle) .map_err(|_| { eros::error!("application lifecycle lock poisoned").context("read app state") }) } pub fn transition(&self, next: LifecycleState) -> eros::Result<()> { let mut current = self.lifecycle.write().map_err(|_| { eros::error!("application lifecycle lock poisoned").context("write app state") })?; if !current.can_transition(next) { return Err(eros::error!(InvalidTransition { from: *current, to: next, }) .context("advance application lifecycle")); } *current = next; Ok(()) } } impl Default for AppState { fn default() -> Self { Self { lifecycle: RwLock::new(LifecycleState::Created), } } }