Skip to main content

fraiseql_server/server/
extensions.rs

1//! Server extensions: relay pagination, Arrow Flight service, and observer runtime
2//! initialization.
3
4use std::sync::Arc;
5
6#[cfg(feature = "arrow")]
7use fraiseql_arrow::FraiseQLFlightService;
8#[cfg(all(feature = "arrow", feature = "auth"))]
9use fraiseql_core::security::OidcValidator;
10use fraiseql_core::{
11    cache::{CacheConfig, CachedDatabaseAdapter, QueryResultCache},
12    db::traits::{DatabaseAdapter, RelayDatabaseAdapter},
13    runtime::{Executor, SubscriptionManager},
14    schema::CompiledSchema,
15};
16#[cfg(feature = "observers")]
17use tokio::sync::RwLock;
18use tracing::info;
19#[cfg(feature = "observers")]
20use tracing::warn;
21
22#[cfg(feature = "arrow")]
23use super::RateLimiter;
24#[cfg(all(feature = "arrow", feature = "auth"))]
25use super::ServerError;
26#[cfg(feature = "observers")]
27use super::{ObserverRuntime, ObserverRuntimeConfig};
28use super::{Result, Server, ServerConfig};
29
30impl<A: DatabaseAdapter + RelayDatabaseAdapter + Clone + Send + Sync + 'static>
31    Server<CachedDatabaseAdapter<A>>
32{
33    /// Create a server with relay pagination support enabled.
34    ///
35    /// The adapter must implement [`RelayDatabaseAdapter`]. Currently, only
36    /// `PostgresAdapter` and `CachedDatabaseAdapter<PostgresAdapter>` satisfy this bound.
37    ///
38    /// Relay queries issued against a server created with [`Server::new`] return a
39    /// `Validation` error at runtime; those issued against a server created with this
40    /// constructor succeed.
41    ///
42    /// # Arguments
43    ///
44    /// * `config` - Server configuration
45    /// * `schema` - Compiled GraphQL schema
46    /// * `adapter` - Database adapter (must implement `RelayDatabaseAdapter`)
47    /// * `db_pool` - Database connection pool (optional, required for observers)
48    ///
49    /// # Errors
50    ///
51    /// Returns error if OIDC validator initialization fails.
52    ///
53    /// # Panics
54    ///
55    /// Panics if the `adapter` `Arc` has been cloned before calling this constructor
56    /// (refcount > 1). The builder must have exclusive ownership to unwrap the adapter
57    /// for `CachedDatabaseAdapter` construction.
58    ///
59    /// # Example
60    ///
61    /// ```text
62    /// // Requires: running PostgreSQL database and compiled schema file.
63    /// let adapter = Arc::new(PostgresAdapter::new(db_url).await?);
64    /// let server = Server::with_relay_pagination(config, schema, adapter, None).await?;
65    /// server.serve().await?;
66    /// ```
67    pub async fn with_relay_pagination(
68        config: ServerConfig,
69        schema: CompiledSchema,
70        adapter: Arc<A>,
71        db_pool: Option<sqlx::PgPool>,
72    ) -> Result<Self> {
73        // Validate cache + RLS safety (mirrors Server::new).
74        if config.cache_enabled && !schema.has_rls_configured() {
75            if schema.is_multi_tenant() {
76                return Err(super::ServerError::ConfigError(
77                    "Cache is enabled in a multi-tenant schema but no Row-Level Security \
78                     policies are declared. This would allow cross-tenant cache hits and \
79                     data leakage. In fraiseql.toml, either disable caching with \
80                     [cache] enabled = false, declare [security.rls] policies, or set \
81                     [security] multi_tenant = false to acknowledge single-tenant mode."
82                        .to_string(),
83                ));
84            }
85            tracing::warn!(
86                "Query-result caching is enabled but no Row-Level Security policies are \
87                 declared in the compiled schema. This is safe for single-tenant deployments."
88            );
89        }
90
91        // Read security configs from compiled schema BEFORE schema is moved.
92        #[cfg(feature = "federation")]
93        let circuit_breaker = schema.federation.as_ref().and_then(
94            crate::federation::circuit_breaker::FederationCircuitBreakerManager::from_config,
95        );
96        #[cfg(not(feature = "federation"))]
97        let circuit_breaker: Option<()> = None;
98        #[cfg(not(feature = "federation"))]
99        let _ = &schema.federation;
100        let error_sanitizer = Self::error_sanitizer_from_schema(&schema);
101        #[cfg(feature = "auth")]
102        let state_encryption = Self::state_encryption_from_schema(&schema)?;
103        #[cfg(not(feature = "auth"))]
104        let state_encryption: Option<
105            std::sync::Arc<crate::auth::state_encryption::StateEncryptionService>,
106        > = None;
107        #[cfg(feature = "auth")]
108        let pkce_store = Self::pkce_store_from_schema(&schema, state_encryption.as_ref()).await?;
109        #[cfg(not(feature = "auth"))]
110        let pkce_store: Option<std::sync::Arc<crate::auth::PkceStateStore>> = None;
111        #[cfg(feature = "auth")]
112        let oidc_server_client = Self::oidc_server_client_from_schema(&schema);
113        #[cfg(not(feature = "auth"))]
114        let oidc_server_client: Option<std::sync::Arc<crate::auth::OidcServerClient>> = None;
115        let schema_rate_limiter = Self::rate_limiter_from_schema(&schema).await?;
116        let api_key_authenticator = crate::api_key::api_key_authenticator_from_schema(&schema);
117        let revocation_manager = crate::token_revocation::revocation_manager_from_schema(&schema)?;
118        let mut tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
119        let trusted_docs = Self::trusted_docs_from_schema(&schema, &mut tasks);
120
121        let cache_config = CacheConfig::from(config.cache_enabled);
122        let cache = QueryResultCache::new(cache_config);
123        // Unwrap Arc: refcount is 1 here — adapter has not been cloned since being passed in.
124        let inner = Arc::into_inner(adapter)
125            .expect("CachedDatabaseAdapter wrapping requires exclusive Arc ownership at startup");
126        let cached = CachedDatabaseAdapter::new(inner, cache, schema.content_hash())
127            .with_ttl_overrides_from_schema(&schema);
128        let executor = Arc::new(Executor::new_with_relay(schema.clone(), Arc::new(cached)));
129        let subscription_manager = Arc::new(SubscriptionManager::new(Arc::new(schema)));
130
131        let mut server = Self::from_executor(
132            config,
133            executor,
134            subscription_manager,
135            circuit_breaker,
136            error_sanitizer,
137            state_encryption,
138            pkce_store,
139            oidc_server_client,
140            schema_rate_limiter,
141            api_key_authenticator,
142            revocation_manager,
143            trusted_docs,
144            db_pool,
145            tasks,
146        )
147        .await?;
148
149        server.adapter_cache_enabled = cache_config.enabled;
150
151        // Initialize MCP config from compiled schema when the feature is compiled in.
152        #[cfg(feature = "mcp")]
153        if let Some(ref cfg) = server.executor.schema().mcp_config {
154            if cfg.enabled {
155                let tool_count =
156                    crate::mcp::tools::schema_to_tools(server.executor.schema(), cfg).len();
157                info!(
158                    path = %cfg.path,
159                    transport = %cfg.transport,
160                    tools = tool_count,
161                    "MCP server configured"
162                );
163                server.mcp_config = Some(cfg.clone());
164            }
165        }
166
167        // Initialize APQ store when enabled.
168        if server.config.apq_enabled {
169            let apq_store: fraiseql_core::apq::ArcApqStorage =
170                Arc::new(fraiseql_core::apq::InMemoryApqStorage::default());
171            server.apq_store = Some(apq_store);
172            info!("APQ (Automatic Persisted Queries) enabled — in-memory backend");
173        }
174
175        Ok(server)
176    }
177}
178
179impl<A: DatabaseAdapter + Clone + Send + Sync + 'static> Server<A> {
180    /// Create new server with pre-configured Arrow Flight service.
181    ///
182    /// Use this constructor when you want to provide a Flight service with a real database adapter.
183    ///
184    /// # Arguments
185    ///
186    /// * `config` - Server configuration
187    /// * `schema` - Compiled GraphQL schema
188    /// * `adapter` - Database adapter
189    /// * `db_pool` - Database connection pool (optional, required for observers)
190    /// * `flight_service` - Pre-configured Flight service (only available with arrow feature)
191    ///
192    /// # Errors
193    ///
194    /// Returns error if OIDC validator initialization fails.
195    #[cfg(feature = "arrow")]
196    pub async fn with_flight_service(
197        config: ServerConfig,
198        schema: CompiledSchema,
199        adapter: Arc<A>,
200        #[allow(unused_variables)]
201        // Reason: used inside #[cfg(feature = "observers")] block; unused when feature is off
202        db_pool: Option<sqlx::PgPool>,
203        flight_service: Option<FraiseQLFlightService>,
204    ) -> Result<Self> {
205        // Read security configs from compiled schema BEFORE schema is moved.
206        #[cfg(feature = "federation")]
207        let circuit_breaker = schema.federation.as_ref().and_then(
208            crate::federation::circuit_breaker::FederationCircuitBreakerManager::from_config,
209        );
210        // Non-federation builds construct the `Server` struct literal below with the
211        // `circuit_breaker` field cfg'd out, so there is no placeholder to bind here —
212        // just mark `schema.federation` read to mirror the federation branch.
213        #[cfg(not(feature = "federation"))]
214        let _ = &schema.federation;
215        let error_sanitizer = Self::error_sanitizer_from_schema(&schema);
216        #[cfg(feature = "auth")]
217        let state_encryption = Self::state_encryption_from_schema(&schema)?;
218        #[cfg(not(feature = "auth"))]
219        let _state_encryption: Option<
220            std::sync::Arc<crate::auth::state_encryption::StateEncryptionService>,
221        > = None;
222        #[cfg(feature = "auth")]
223        let pkce_store = Self::pkce_store_from_schema(&schema, state_encryption.as_ref()).await?;
224        #[cfg(not(feature = "auth"))]
225        let _pkce_store: Option<std::sync::Arc<crate::auth::PkceStateStore>> = None;
226        #[cfg(feature = "auth")]
227        let oidc_server_client = Self::oidc_server_client_from_schema(&schema);
228        #[cfg(not(feature = "auth"))]
229        let _oidc_server_client: Option<std::sync::Arc<crate::auth::OidcServerClient>> = None;
230        let schema_rate_limiter = Self::rate_limiter_from_schema(&schema).await?;
231        let api_key_authenticator = crate::api_key::api_key_authenticator_from_schema(&schema);
232        let revocation_manager = crate::token_revocation::revocation_manager_from_schema(&schema)?;
233        let mut tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
234        let trusted_docs = Self::trusted_docs_from_schema(&schema, &mut tasks);
235
236        let executor = Arc::new(Executor::new(schema.clone(), adapter));
237        let subscription_manager = Arc::new(SubscriptionManager::new(Arc::new(schema)));
238
239        // Initialize OIDC validator if auth is configured
240        #[cfg(feature = "auth")]
241        let oidc_validator = if let Some(ref auth_config) = config.auth {
242            info!(
243                issuer = %auth_config.issuer,
244                "Initializing OIDC authentication"
245            );
246            let validator = OidcValidator::new(auth_config.clone())
247                .await
248                .map_err(|e| ServerError::ConfigError(format!("Failed to initialize OIDC: {e}")))?;
249            Some(Arc::new(validator))
250        } else {
251            None
252        };
253        #[cfg(not(feature = "auth"))]
254        let oidc_validator: Option<Arc<fraiseql_core::security::OidcValidator>> = None;
255
256        // Initialize HS256 validator if configured (mutually exclusive with OIDC).
257        let hs256_auth = super::builder::build_hs256_auth(&config)?;
258
259        // Initialize rate limiter: compiled schema config takes priority over server config.
260        let rate_limiter = if let Some(rl) = schema_rate_limiter {
261            Some(rl)
262        } else if let Some(ref rate_config) = config.rate_limiting {
263            if rate_config.enabled {
264                info!(
265                    rps_per_ip = rate_config.rps_per_ip,
266                    rps_per_user = rate_config.rps_per_user,
267                    "Initializing rate limiting from server config"
268                );
269                Some(Arc::new(RateLimiter::new(rate_config.clone())))
270            } else {
271                info!("Rate limiting disabled by configuration");
272                None
273            }
274        } else {
275            None
276        };
277
278        // Initialize observer runtime
279        #[cfg(feature = "observers")]
280        let observer_runtime = Self::init_observer_runtime(&config, db_pool.as_ref()).await?;
281
282        // Warn if PKCE is configured but [auth] is missing.
283        #[cfg(feature = "auth")]
284        if pkce_store.is_some() && oidc_server_client.is_none() {
285            tracing::error!(
286                "pkce.enabled = true but [auth] is not configured or OIDC client init failed. \
287                 Auth routes will NOT be mounted."
288            );
289        }
290
291        // Refuse to start if FRAISEQL_REQUIRE_REDIS is set and PKCE store is in-memory.
292        #[cfg(feature = "auth")]
293        Self::check_redis_requirement(pkce_store.as_ref())?;
294
295        // Spawn background PKCE state cleanup task (every 5 minutes).
296        #[cfg(feature = "auth")]
297        Self::spawn_pkce_cleanup(pkce_store.as_ref(), &mut tasks);
298
299        let apq_enabled = config.apq_enabled;
300
301        Ok(Self {
302            config,
303            executor,
304            subscription_manager,
305            subscription_lifecycle: Arc::new(crate::subscriptions::NoopLifecycle),
306            max_subscriptions_per_connection: None,
307            oidc_validator,
308            hs256_auth,
309            rate_limiter,
310            #[cfg(feature = "secrets")]
311            secrets_manager: None,
312            #[cfg(feature = "federation")]
313            circuit_breaker,
314            error_sanitizer,
315            #[cfg(feature = "auth")]
316            state_encryption,
317            #[cfg(feature = "auth")]
318            pkce_store,
319            #[cfg(feature = "auth")]
320            oidc_server_client,
321            #[cfg(feature = "auth")]
322            social_login: None,
323            #[cfg(feature = "auth")]
324            anon_signup_state: None,
325            #[cfg(feature = "auth")]
326            mfa_state: None,
327            api_key_authenticator,
328            revocation_manager,
329            apq_store: if apq_enabled {
330                Some(Arc::new(fraiseql_core::apq::InMemoryApqStorage::default())
331                    as fraiseql_core::apq::ArcApqStorage)
332            } else {
333                None
334            },
335            trusted_docs,
336            #[cfg(feature = "mcp")]
337            mcp_config: None,
338            pool_tuning_config: None,
339            #[cfg(feature = "observers")]
340            observer_runtime,
341            #[cfg(feature = "auth")]
342            enrichment_pool: db_pool.clone(),
343            #[cfg(feature = "observers")]
344            db_pool,
345            storage_state: None,
346            realtime_state: None,
347            tenant_executor_factory: None,
348            #[cfg(feature = "arrow")]
349            flight_service,
350            adapter_cache_enabled: false,
351            broadcast_manager: None,
352            presence_manager: None,
353            storage_backend: None,
354            storage_max_upload_bytes: 100 * 1024 * 1024, // 100 MiB default
355            #[cfg(feature = "functions")]
356            function_store: None,
357            #[cfg(feature = "functions")]
358            function_runtime: None,
359            usage: Arc::clone(crate::usage::aggregator::global_aggregator()),
360            tasks,
361        })
362    }
363
364    /// Initialize observer runtime from configuration.
365    ///
366    /// # Errors
367    ///
368    /// Returns `ServerError::ConfigError` when a non-Postgres observer transport
369    /// is selected that this binary cannot run (feature not compiled in, or NATS
370    /// without a URL) while in production mode (#350), or when the transport
371    /// configuration is otherwise invalid. In development such a selection is
372    /// downgraded to a warning and the runtime falls back to PostgreSQL.
373    #[cfg(feature = "observers")]
374    pub(super) async fn init_observer_runtime(
375        config: &ServerConfig,
376        pool: Option<&sqlx::PgPool>,
377    ) -> crate::Result<Option<Arc<RwLock<ObserverRuntime>>>> {
378        use fraiseql_observers::config::TransportKind;
379
380        // Check if enabled
381        let observer_config = match &config.observers {
382            Some(cfg) if cfg.enabled => cfg,
383            _ => {
384                info!("Observer runtime disabled");
385                return Ok(None);
386            },
387        };
388
389        let Some(pool) = pool else {
390            warn!("No database pool provided for observers");
391            return Ok(None);
392        };
393
394        info!("Initializing observer runtime");
395
396        // Resolve the event transport from compiled config + env overrides, then
397        // fail loud (#350) on a selection this binary cannot run before validating
398        // the finer NATS/JetStream bounds — never a silent fallback to PostgreSQL.
399        let mut transport = observer_config.runtime.transport.clone().with_env_overrides();
400        let compiled_in = cfg!(feature = "observers-nats");
401        let nats_url_present = !transport.nats.url.is_empty();
402        crate::server::initialization::observer_transport_check(
403            transport.transport,
404            compiled_in,
405            nats_url_present,
406            crate::ServerConfig::is_production_mode(),
407        )?;
408
409        // In production an unrunnable selection already returned above; the only
410        // way past the guard with an unrunnable transport is development, where it
411        // was downgraded to a warning — fall back to PostgreSQL so local boot works.
412        let usable = match transport.transport {
413            TransportKind::Postgres | TransportKind::InMemory => true,
414            TransportKind::Nats => compiled_in && nats_url_present,
415            _ => false,
416        };
417        if !usable {
418            transport.transport = TransportKind::Postgres;
419        }
420
421        transport.validate().map_err(|e| {
422            crate::ServerError::ConfigError(format!("invalid observer transport config: {e}"))
423        })?;
424
425        let runtime_config = ObserverRuntimeConfig::new(pool.clone())
426            .with_poll_interval(observer_config.runtime.poll_interval_ms)
427            .with_batch_size(observer_config.runtime.batch_size)
428            .with_channel_capacity(observer_config.runtime.channel_capacity)
429            .with_max_dlq_size(observer_config.runtime.max_dlq_size)
430            .with_transport(transport)
431            .with_email(observer_config.runtime.email.clone());
432
433        let runtime = ObserverRuntime::new(runtime_config);
434        Ok(Some(Arc::new(RwLock::new(runtime))))
435    }
436}