Skip to main content

postrust_server/
state.rs

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