diff options
Diffstat (limited to 'crates/users-service/src/state.rs')
-rw-r--r-- | crates/users-service/src/state.rs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/crates/users-service/src/state.rs b/crates/users-service/src/state.rs new file mode 100644 index 0000000..3f5ac7b --- /dev/null +++ b/crates/users-service/src/state.rs @@ -0,0 +1,65 @@ +use std::sync::Arc; + +use sqlx::PgPool; +use stack_up::{ + Configuration, + cache::{RedisConnection, RedisManager}, +}; +use tonic::Status; +use tracing::error; + +use crate::cnfg::LocalConfig; + +#[derive(Clone)] +pub struct AppHandle(Arc<AppState>); + +impl std::ops::Deref for AppHandle { + type Target = Arc<AppState>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[derive(Clone)] +pub struct Services { + pub postgres: PgPool, + pub cache: RedisManager, +} + +impl Services { + pub fn new(postgres: PgPool, cache: RedisManager) -> Self { + Self { postgres, cache } + } +} + +pub struct AppState { + pub services: Services, + pub local_config: LocalConfig, +} + +impl AppState { + pub async fn create( + services: Services, + configuration: &Configuration, + ) -> Result<AppHandle, anyhow::Error> { + let local_config: LocalConfig = serde_json::from_value(configuration.misc.clone())?; + + Ok(AppHandle(Arc::new(Self { + services, + local_config, + }))) + } + + pub async fn cache(&self) -> Result<RedisConnection, tonic::Status> { + let cache = self + .services + .cache + .get() + .await + .inspect_err(|e| error!("{e}")) + .map_err(|_e| Status::internal("storage not ready"))?; + + Ok(cache) + } +} |