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(&self.pool, &self.config.db_schemas).await?;
30        let mut guard = self.schema_cache.write().await;
31        *guard = new_cache;
32        Ok(())
33    }
34
35    /// Get the default schema.
36    pub fn default_schema(&self) -> &str {
37        self.config.default_schema()
38    }
39
40    /// Get exposed schemas.
41    pub fn schemas(&self) -> &[String] {
42        &self.config.db_schemas
43    }
44}