Skip to main content

postrust_server/
state.rs

1//! Application state.
2
3use postrust_auth::{JwtCache, JwtConfig};
4use postrust_core::{AppConfig, SchemaCache};
5use postrust_engine::State;
6use sqlx::PgPool;
7use tokio::sync::{RwLock, RwLockReadGuard};
8
9/// Shared application state.
10pub struct AppState {
11    /// Database connection pool
12    pub pool: PgPool,
13    /// Cached schema metadata
14    pub schema_cache: RwLock<SchemaCache>,
15    /// Application configuration
16    pub config: AppConfig,
17    /// JWT configuration
18    pub jwt_config: JwtConfig,
19    /// Cache of validated tokens, when `jwt_cache_enabled` asks for one.
20    pub jwt_cache: Option<JwtCache>,
21}
22
23impl AppState {
24    /// Get a read lock on the schema cache.
25    pub async fn schema_cache(&self) -> RwLockReadGuard<'_, SchemaCache> {
26        self.schema_cache.read().await
27    }
28
29    /// Reload the schema cache. Used by the `db_channel_enabled` listener.
30    pub async fn reload_schema(&self) -> Result<(), postrust_core::Error> {
31        let new_cache = SchemaCache::load_with_search_path(
32            &self.pool,
33            &self.config.db_schemas,
34            &self.config.db_extra_search_path,
35        )
36        .await?;
37        let mut guard = self.schema_cache.write().await;
38        *guard = new_cache;
39        Ok(())
40    }
41
42    /// Get the default schema.
43    pub fn default_schema(&self) -> &str {
44        self.config.default_schema()
45    }
46
47    /// Get exposed schemas.
48    pub fn schemas(&self) -> &[String] {
49        &self.config.db_schemas
50    }
51}
52
53impl State for AppState {
54    type Db = PgPool;
55    type SchemaCache<'a> = RwLockReadGuard<'a, SchemaCache>;
56
57    fn db(&self) -> &PgPool {
58        &self.pool
59    }
60
61    async fn schema_cache(&self) -> RwLockReadGuard<'_, SchemaCache> {
62        self.schema_cache.read().await
63    }
64
65    fn config(&self) -> &AppConfig {
66        &self.config
67    }
68
69    fn jwt_config(&self) -> &JwtConfig {
70        &self.jwt_config
71    }
72
73    fn jwt_cache(&self) -> Option<&JwtCache> {
74        self.jwt_cache.as_ref()
75    }
76}