Skip to main content

che_rest/
state.rs

1use std::{any::Any, future::Future, path::Path, pin::Pin, sync::Arc};
2
3use che_orm::Database;
4
5use crate::{AppConfig, AppResult, auth::User};
6use crate::{app_channels::AppChannels, channels::Channels, signals::SignalBus};
7
8pub type CurrentUserResolver = Arc<
9    dyn for<'a> Fn(
10            &'a AppState,
11            &'a User,
12        ) -> Pin<
13            Box<dyn Future<Output = AppResult<Option<Arc<dyn Any + Send + Sync>>>> + Send + 'a>,
14        > + Send
15        + Sync,
16>;
17
18#[derive(Clone)]
19pub struct AppState {
20    pub config: AppConfig,
21    database: Database,
22    app_channels: AppChannels,
23    signals: SignalBus,
24    current_user_resolver: Option<CurrentUserResolver>,
25    pub(crate) sync_effects_lock: Arc<tokio::sync::Mutex<()>>,
26    pub(crate) sync_lifecycle: Arc<
27        std::sync::RwLock<
28            std::collections::HashMap<String, Vec<Arc<dyn crate::sync::SyncLifecycle>>>,
29        >,
30    >,
31}
32
33impl AppState {
34    pub fn from_database(database: Database) -> Self {
35        Self {
36            config: AppConfig::default(),
37            database,
38            app_channels: AppChannels::new(),
39            signals: SignalBus::new(),
40            current_user_resolver: None,
41            sync_effects_lock: Arc::default(),
42            sync_lifecycle: Arc::default(),
43        }
44    }
45
46    pub async fn from_config_file(path: impl AsRef<Path>) -> AppResult<Self> {
47        let config = AppConfig::from_file(path)?;
48        let database = config.database.connect().await?;
49        Ok(Self {
50            config,
51            database,
52            app_channels: AppChannels::new(),
53            signals: SignalBus::new(),
54            current_user_resolver: None,
55            sync_effects_lock: Arc::default(),
56            sync_lifecycle: Arc::default(),
57        })
58    }
59
60    pub fn database(&self) -> &Database {
61        &self.database
62    }
63
64    /// Replace the database handle while preserving configuration and application services.
65    pub fn with_database(mut self, database: Database) -> Self {
66        self.database = database;
67        self
68    }
69
70    pub fn channels(&self) -> &Channels {
71        &self.signals
72    }
73
74    pub fn app_channels(&self) -> &AppChannels {
75        &self.app_channels
76    }
77
78    pub fn signals(&self) -> &SignalBus {
79        &self.signals
80    }
81
82    pub fn with_current_user_resolver<T, F>(mut self, resolver: F) -> Self
83    where
84        T: Send + Sync + 'static,
85        F: for<'a> Fn(&'a AppState, &'a User) -> CurrentUserResolverFuture<'a, T>
86            + Send
87            + Sync
88            + 'static,
89    {
90        self.current_user_resolver = Some(Arc::new(move |state, user| {
91            let future = resolver(state, user);
92            Box::pin(async move {
93                future
94                    .await
95                    .map(|user| user.map(|user| Arc::new(user) as Arc<dyn Any + Send + Sync>))
96            })
97        }));
98        self
99    }
100
101    pub(crate) async fn resolve_current_user(
102        &self,
103        user: &User,
104    ) -> AppResult<Option<Arc<dyn Any + Send + Sync>>> {
105        match &self.current_user_resolver {
106            Some(resolver) => resolver(self, user).await,
107            None => Ok(None),
108        }
109    }
110}
111
112pub type CurrentUserResolverFuture<'a, T> =
113    Pin<Box<dyn Future<Output = AppResult<Option<T>>> + Send + 'a>>;