use std::{ops::Deref, sync::Arc}; use stack_up::{Configuration, Services}; use tokio::task::JoinHandle; use tower_sessions::{CachingSessionStore, ExpiredDeletion, session_store}; use tower_sessions_moka_store::MokaStore; use tower_sessions_sqlx_store::PostgresStore; use crate::{ client::{OauthClient, discord::discord_client}, cnfg::LocalConfig, error::AppError, }; #[derive(Clone)] pub struct AppHandle(Arc); impl Deref for AppHandle { type Target = Arc; fn deref(&self) -> &Self::Target { &self.0 } } pub struct AppState { pub services: Services, pub local_config: LocalConfig, pub discord_client: OauthClient, pub http_client: reqwest::Client, pub session_store: CachingSessionStore, } impl AppState { pub async fn create( services: Services, configuration: &Configuration, ) -> Result<(AppHandle, JoinHandle>), AppError> { let local_config: LocalConfig = serde_json::from_value(configuration.misc.clone())?; let session_store_db = tower_sessions_sqlx_store::PostgresStore::new(services.postgres.clone()); session_store_db.migrate().await?; let deletion_task = tokio::task::spawn( session_store_db .clone() .continuously_delete_expired(tokio::time::Duration::from_secs(60)), ); let session_store_mem = MokaStore::new(Some(100)); let store = CachingSessionStore::new(session_store_mem, session_store_db); let discord_client = discord_client(&local_config.oauth.discord)?; Ok(( AppHandle(Arc::new(Self { services, local_config, discord_client, http_client: reqwest::Client::new(), session_store: store, })), deletion_task, )) } }