Skip to main content

postrust_server/
state.rs

1//! Application state.
2
3use postrust_auth::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}
19
20impl AppState {
21    /// Get a read lock on the schema cache.
22    pub async fn schema_cache(&self) -> tokio::sync::RwLockReadGuard<'_, SchemaCache> {
23        self.schema_cache.read().await
24    }
25
26    /// Reload the schema cache.
27    #[allow(dead_code)] // Public API for schema reload; wired up by the (optional) NOTIFY listener.
28    pub async fn reload_schema(&self) -> Result<(), postrust_core::Error> {
29        let new_cache = SchemaCache::load_with_search_path(
30            &self.pool,
31            &self.config.db_schemas,
32            &self.config.db_extra_search_path,
33        )
34        .await?;
35        let mut guard = self.schema_cache.write().await;
36        *guard = new_cache;
37        Ok(())
38    }
39
40    /// Get the default schema.
41    pub fn default_schema(&self) -> &str {
42        self.config.default_schema()
43    }
44
45    /// Get exposed schemas.
46    pub fn schemas(&self) -> &[String] {
47        &self.config.db_schemas
48    }
49}