//! Essential data passed to routes. Used in axum's [State][axum-state] //! //! The state object holds essential data passed to every route that needs //! access to connectors or the database or things of such nature. //! //! The main struct here is [SplormState] //! //! [axum-state]: https://docs.rs/axum/latest/axum/extract/struct.State.html use std::sync::Arc; use somethings::DatabaseHandle; use tokio::sync::{Mutex, MutexGuard}; use crate::{config::Settings, connector::GathererConnector}; /// Main state structure. /// /// Holds the state for the application. It is cheap to clone as all /// of it's fields are wrapped in an [Arc]. #[derive(Clone)] pub struct SplormState { connectors: ConnectorsState, dbh: DatabaseHandle, } impl SplormState { pub fn new(connectors: ConnectorsState, settings: &Settings) -> Self { Self { connectors, dbh: DatabaseHandle::open(settings.database_path().as_std_path()).unwrap(), } } pub async fn gatherer_thread<'s>(&'s self) -> MutexGuard<'s, GathererConnector> { self.connectors.gatherer.lock().await } pub fn database(&self) -> &DatabaseHandle { &self.dbh } pub async fn init_database(&self) { knowing::create_table(self.database()).await.unwrap(); } } /// Connectors to outside services. /// /// Routes access this structure if they want to call services not within /// splorm itself. Connectors are wrapped in `Arc>` as needed. #[derive(Clone)] pub struct ConnectorsState { gatherer: Arc>, } impl ConnectorsState { pub fn new(gatherer: GathererConnector) -> Self { Self { gatherer: Arc::new(Mutex::new(gatherer)), } } }