1use postrust_auth::{JwtCache, JwtConfig};
4use postrust_core::{AppConfig, SchemaCache};
5use postrust_engine::State;
6use sqlx::PgPool;
7use tokio::sync::{RwLock, RwLockReadGuard};
8
9pub struct AppState {
11 pub pool: PgPool,
13 pub schema_cache: RwLock<SchemaCache>,
15 pub config: AppConfig,
17 pub jwt_config: JwtConfig,
19 pub jwt_cache: Option<JwtCache>,
21}
22
23impl AppState {
24 pub async fn schema_cache(&self) -> RwLockReadGuard<'_, SchemaCache> {
26 self.schema_cache.read().await
27 }
28
29 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 pub fn default_schema(&self) -> &str {
44 self.config.default_schema()
45 }
46
47 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}