summaryrefslogtreecommitdiffstats
path: root/crates/auth-service/src/state.rs
blob: 07bfda9a3849f237b9a4780d091882cde6b6e1d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::{ops::Deref, sync::Arc};

use sellershut_core::users::users_service_client::UsersServiceClient;
use sqlx::PgPool;
use stack_up::Configuration;
use tokio::task::JoinHandle;
use tonic::transport::Endpoint;
use tower_sessions::{CachingSessionStore, ExpiredDeletion, session_store};
use tower_sessions_moka_store::MokaStore;
use tower_sessions_sqlx_store::PostgresStore;
use tracing::error;

use crate::{
    client::{OauthClient, discord::discord_client},
    cnfg::LocalConfig,
    error::AppError,
    server::grpc::interceptor::{Intercepted, MyInterceptor},
};

#[derive(Clone)]
pub struct AppHandle(Arc<AppState>);

impl Deref for AppHandle {
    type Target = Arc<AppState>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Clone)]
pub struct Services {
    pub postgres: PgPool,
}

pub struct AppState {
    pub services: Services,
    pub local_config: LocalConfig,
    pub discord_client: OauthClient,
    pub http_client: reqwest::Client,
    pub session_store: CachingSessionStore<MokaStore, PostgresStore>,
    pub users_client: UsersServiceClient<Intercepted>,
}

impl AppState {
    pub async fn create(
        services: Services,
        configuration: &Configuration,
    ) -> Result<(AppHandle, JoinHandle<Result<(), session_store::Error>>), 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)?;

        let channel = Endpoint::new(local_config.profile_endpoint.to_string())?
            .connect()
            .await
            .inspect_err(|e| error!("could not connect to profile service: {e}"))?;

        let users_client = UsersServiceClient::with_interceptor(channel, MyInterceptor);

        Ok((
            AppHandle(Arc::new(Self {
                services,
                local_config,
                discord_client,
                http_client: reqwest::Client::new(),
                session_store: store,
                users_client,
            })),
            deletion_task,
        ))
    }
}