Skip to main content

fraiseql_server/server/
builder.rs

1//! Server constructors and builder methods.
2
3use std::sync::Arc;
4
5#[cfg(feature = "arrow")]
6use fraiseql_arrow::FraiseQLFlightService;
7use fraiseql_core::{
8    cache::{CacheConfig, CachedDatabaseAdapter, QueryResultCache},
9    db::traits::DatabaseAdapter,
10    runtime::{Executor, RuntimeConfig, SubscriptionManager},
11    schema::CompiledSchema,
12    security::{AuthConfig, AuthMiddleware, OidcValidator},
13};
14use tracing::{info, warn};
15
16use super::{RateLimiter, Result, Server, ServerConfig, ServerError};
17
18/// Build an HS256 validator from the server config, if configured.
19pub(super) fn build_hs256_auth(config: &ServerConfig) -> Result<Option<Arc<AuthMiddleware>>> {
20    let Some(ref hs) = config.auth_hs256 else {
21        return Ok(None);
22    };
23    // Reject incompatible config shapes *before* loading the secret, so a
24    // dev environment with a real secret env-var but missing audience still
25    // surfaces the audience error rather than silently booting.  Closes the
26    // cross-service token-confusion gap for the HS256 path (#359).
27    hs.validate()
28        .map_err(|e| ServerError::ConfigError(format!("Failed to initialize HS256 auth: {e}")))?;
29    let secret = hs
30        .load_secret()
31        .map_err(|e| ServerError::ConfigError(format!("Failed to initialize HS256 auth: {e}")))?;
32    let mut auth_config = AuthConfig::with_hs256(&secret);
33    if let Some(ref iss) = hs.issuer {
34        auth_config = auth_config.with_issuer(iss);
35    }
36    if let Some(ref aud) = hs.audience {
37        auth_config = auth_config.with_audience(aud);
38    }
39    info!(
40        secret_env = %hs.secret_env,
41        issuer = ?hs.issuer,
42        audience = ?hs.audience,
43        "Initializing HS256 authentication (local validation, no network)"
44    );
45    Ok(Some(Arc::new(AuthMiddleware::from_config(auth_config))))
46}
47
48impl<A: DatabaseAdapter + Clone + Send + Sync + 'static> Server<CachedDatabaseAdapter<A>> {
49    /// Create new server.
50    ///
51    /// Relay pagination queries will return a `Validation` error at runtime. Use
52    /// [`Server::with_relay_pagination`] when the adapter implements
53    /// [`RelayDatabaseAdapter`](fraiseql_core::db::traits::RelayDatabaseAdapter)
54    /// and relay support is required.
55    ///
56    /// # Arguments
57    ///
58    /// * `config` - Server configuration
59    /// * `schema` - Compiled GraphQL schema
60    /// * `adapter` - Database adapter
61    /// * `db_pool` — forwarded to the observer runtime; `None` when observers are disabled.
62    ///
63    /// # Errors
64    ///
65    /// Returns error if OIDC validator initialization fails (e.g., unable to
66    /// fetch discovery document or JWKS).
67    ///
68    /// # Panics
69    ///
70    /// Panics if the `adapter` `Arc` has been cloned before calling this constructor
71    /// (refcount > 1). The builder must have exclusive ownership to unwrap the adapter
72    /// for `CachedDatabaseAdapter` construction.
73    ///
74    /// # Example
75    ///
76    /// ```text
77    /// // Requires: running PostgreSQL database and compiled schema file.
78    /// let config = ServerConfig::default();
79    /// let schema = CompiledSchema::from_json(schema_json, false)?;
80    /// let adapter = Arc::new(PostgresAdapter::new(db_url).await?);
81    ///
82    /// let server = Server::new(config, schema, adapter, None).await?;
83    /// server.serve().await?;
84    /// ```
85    #[allow(clippy::cognitive_complexity)] // Reason: server construction with subsystem initialization (auth, rate-limit, observers, etc.)
86    pub async fn new(
87        config: ServerConfig,
88        schema: CompiledSchema,
89        adapter: Arc<A>,
90        db_pool: Option<sqlx::PgPool>,
91    ) -> Result<Self> {
92        // Build the runtime config from the compiled schema. This is the single
93        // seam every server constructor routes through (H16): it validates the
94        // schema format version (warns on legacy, rejects incompatible), reads the
95        // audit-logging flag, applies the #421 page-size ceiling, and the
96        // change-log toggle. Doing it first preserves "reject bad version before
97        // any further setup".
98        let executor_config = RuntimeConfig::from_compiled_schema(&schema).map_err(|msg| {
99            ServerError::ConfigError(format!("Incompatible compiled schema: {msg}"))
100        })?;
101
102        // Refuse to boot if any field is marked for at-rest encryption: the write path does
103        // not encrypt (H12), so those fields would be stored in plaintext. Fail loud rather
104        // than silently storing sensitive data unencrypted.
105        crate::server::initialization::field_encryption_unsupported_check(&schema)?;
106
107        // Read security configs from compiled schema BEFORE schema is moved.
108        #[cfg(feature = "federation")]
109        let circuit_breaker = schema.federation.as_ref().and_then(
110            crate::federation::circuit_breaker::FederationCircuitBreakerManager::from_config,
111        );
112        #[cfg(not(feature = "federation"))]
113        let circuit_breaker: Option<()> = None;
114        #[cfg(not(feature = "federation"))]
115        let _ = &schema.federation;
116        let error_sanitizer = Self::error_sanitizer_from_schema(&schema);
117        #[cfg(feature = "auth")]
118        let state_encryption = Self::state_encryption_from_schema(&schema)?;
119        #[cfg(not(feature = "auth"))]
120        let state_encryption: Option<
121            std::sync::Arc<crate::auth::state_encryption::StateEncryptionService>,
122        > = None;
123        #[cfg(feature = "auth")]
124        let pkce_store = Self::pkce_store_from_schema(&schema, state_encryption.as_ref()).await?;
125        #[cfg(not(feature = "auth"))]
126        let pkce_store: Option<std::sync::Arc<crate::auth::PkceStateStore>> = None;
127        #[cfg(feature = "auth")]
128        let oidc_server_client = Self::oidc_server_client_from_schema(&schema);
129        #[cfg(not(feature = "auth"))]
130        let oidc_server_client: Option<std::sync::Arc<crate::auth::OidcServerClient>> = None;
131        let schema_rate_limiter = Self::rate_limiter_from_schema(&schema).await?;
132        let api_key_authenticator = crate::api_key::api_key_authenticator_from_schema(&schema);
133        if api_key_authenticator.is_some() {
134            info!("API key authentication enabled");
135        }
136        let revocation_manager = crate::token_revocation::revocation_manager_from_schema(&schema)?;
137        if revocation_manager.is_some() {
138            info!("Token revocation enabled");
139        }
140        // Collect lifecycle task handles into a JoinSet that will be moved onto
141        // the `Server` so graceful shutdown can await them.
142        let mut tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
143        let trusted_docs = Self::trusted_docs_from_schema(&schema, &mut tasks);
144
145        // Validate cache + RLS safety at startup.
146        // Cache isolation relies entirely on per-user WHERE clauses in the cache key.
147        // Without RLS, users with the same query and variables share the same cached
148        // response, which can leak data across tenants.
149        if config.cache_enabled && !schema.has_rls_configured() {
150            if schema.is_multi_tenant() {
151                // Multi-tenant + cache + no RLS is a hard safety violation.
152                return Err(ServerError::ConfigError(
153                    "Cache is enabled in a multi-tenant schema but no Row-Level Security \
154                     policies are declared. This would allow cross-tenant cache hits and \
155                     data leakage. In fraiseql.toml, either disable caching with \
156                     [cache] enabled = false, declare [security.rls] policies, or set \
157                     [security] multi_tenant = false to acknowledge single-tenant mode."
158                        .to_string(),
159                ));
160            }
161            // Single-tenant with cache and no RLS: safe, but warn in case of misconfiguration.
162            warn!(
163                "Query-result caching is enabled but no Row-Level Security policies are \
164                 declared in the compiled schema. This is safe for single-tenant deployments. \
165                 For multi-tenant deployments, declare RLS policies and set \
166                 `security.multi_tenant = true` in your schema."
167            );
168        }
169
170        // Build cache from config.
171        let cache_config = CacheConfig::from(config.cache_enabled);
172        let cache = QueryResultCache::new(cache_config);
173
174        // Log cache state before consuming config.
175        if cache_config.enabled {
176            tracing::info!(
177                max_entries   = cache_config.max_entries,
178                ttl_seconds   = cache_config.ttl_seconds,
179                rls_enforcement = ?cache_config.rls_enforcement,
180                "Query result cache: active"
181            );
182        } else {
183            tracing::info!("Query result cache: disabled");
184        }
185
186        // Read subscription config from compiled schema (hooks, limits).
187        let subscriptions_config = schema.subscriptions_config.clone();
188
189        // Unwrap Arc: refcount is 1 here — adapter has not been cloned since being passed in.
190        let inner = Arc::into_inner(adapter)
191            .expect("CachedDatabaseAdapter wrapping requires exclusive Arc ownership at startup");
192        let cached = CachedDatabaseAdapter::new(inner, cache, schema.content_hash())
193            .with_ttl_overrides_from_schema(&schema)
194            .with_rls(schema.has_rls_configured());
195
196        // `executor_config` was built from the compiled schema at the top of this
197        // constructor (the H16 seam — audit flag, #421 page-size, change-log toggle).
198        let executor =
199            Arc::new(Executor::with_config(schema.clone(), Arc::new(cached), executor_config));
200        let subscription_manager = Arc::new(SubscriptionManager::new(Arc::new(schema)));
201
202        let mut server = Self::from_executor(
203            config,
204            executor,
205            subscription_manager,
206            circuit_breaker,
207            error_sanitizer,
208            state_encryption,
209            pkce_store,
210            oidc_server_client,
211            schema_rate_limiter,
212            api_key_authenticator,
213            revocation_manager,
214            trusted_docs,
215            db_pool,
216            tasks,
217        )
218        .await?;
219
220        server.adapter_cache_enabled = cache_config.enabled;
221
222        // Apply pool tuning config from ServerConfig (if present).
223        if let Some(pt) = server.config.pool_tuning.clone() {
224            if pt.enabled {
225                server = server
226                    .with_pool_tuning(pt)
227                    .map_err(|e| ServerError::ConfigError(format!("pool_tuning: {e}")))?;
228            }
229        }
230
231        // Initialize MCP config from compiled schema when the feature is compiled in.
232        #[cfg(feature = "mcp")]
233        if let Some(ref cfg) = server.executor.schema().mcp_config {
234            if cfg.enabled {
235                let tool_count =
236                    crate::mcp::tools::schema_to_tools(server.executor.schema(), cfg).len();
237                info!(
238                    path = %cfg.path,
239                    transport = %cfg.transport,
240                    tools = tool_count,
241                    "MCP server configured"
242                );
243                server.mcp_config = Some(cfg.clone());
244            }
245        }
246
247        // Initialize APQ store when enabled.
248        if server.config.apq_enabled {
249            let apq_store: fraiseql_core::apq::ArcApqStorage =
250                Arc::new(fraiseql_core::apq::InMemoryApqStorage::default());
251            server.apq_store = Some(apq_store);
252            info!("APQ (Automatic Persisted Queries) enabled — in-memory backend");
253        }
254
255        // Apply subscription lifecycle/limits from compiled schema.
256        if let Some(ref subs) = subscriptions_config {
257            if let Some(max) = subs.max_subscriptions_per_connection {
258                server.max_subscriptions_per_connection = Some(max);
259            }
260            if let Some(lifecycle) = crate::subscriptions::WebhookLifecycle::from_config(subs) {
261                server.subscription_lifecycle = Arc::new(lifecycle);
262            }
263        }
264
265        Ok(server)
266    }
267}
268
269impl<A: DatabaseAdapter + Clone + Send + Sync + 'static> Server<A> {
270    /// Shared initialization path used by both `new` and `with_relay_pagination`.
271    ///
272    /// Accepts a pre-built executor so that relay vs. non-relay constructors can supply
273    /// the appropriate variant without duplicating auth/rate-limiter/observer setup.
274    #[allow(clippy::too_many_arguments)]
275    // Reason: internal constructor collects all pre-built subsystems; a builder struct would not
276    // reduce call-site clarity
277    #[allow(clippy::cognitive_complexity)] // Reason: internal constructor that assembles server from pre-built subsystems
278    pub(super) async fn from_executor(
279        config: ServerConfig,
280        executor: Arc<Executor<A>>,
281        subscription_manager: Arc<SubscriptionManager>,
282        #[cfg(feature = "federation")] circuit_breaker: Option<
283            Arc<crate::federation::circuit_breaker::FederationCircuitBreakerManager>,
284        >,
285        #[cfg(not(feature = "federation"))] _circuit_breaker: Option<()>,
286        error_sanitizer: Arc<crate::config::error_sanitization::ErrorSanitizer>,
287        state_encryption: Option<Arc<crate::auth::state_encryption::StateEncryptionService>>,
288        pkce_store: Option<Arc<crate::auth::PkceStateStore>>,
289        oidc_server_client: Option<Arc<crate::auth::OidcServerClient>>,
290        schema_rate_limiter: Option<Arc<RateLimiter>>,
291        api_key_authenticator: Option<Arc<crate::api_key::ApiKeyAuthenticator>>,
292        revocation_manager: Option<Arc<crate::token_revocation::TokenRevocationManager>>,
293        trusted_docs: Option<Arc<crate::trusted_documents::TrustedDocumentStore>>,
294        // `db_pool` is forwarded to the observer runtime and/or auth enrichment.
295        #[cfg_attr(
296            not(any(feature = "observers", feature = "auth")),
297            allow(unused_variables)
298        )]
299        db_pool: Option<sqlx::PgPool>,
300        mut tasks: tokio::task::JoinSet<()>,
301    ) -> Result<Self> {
302        // Initialize OIDC validator if auth is configured
303        let oidc_validator = if let Some(ref auth_config) = config.auth {
304            info!(
305                issuer = %auth_config.issuer,
306                "Initializing OIDC authentication"
307            );
308            let validator = OidcValidator::new(auth_config.clone())
309                .await
310                .map_err(|e| ServerError::ConfigError(format!("Failed to initialize OIDC: {e}")))?;
311            Some(Arc::new(validator))
312        } else {
313            None
314        };
315
316        // Initialize HS256 validator if configured (mutually exclusive with OIDC).
317        let hs256_auth = build_hs256_auth(&config)?;
318
319        // Initialize rate limiter: compiled schema config takes priority over server config.
320        let rate_limiter = if let Some(rl) = schema_rate_limiter {
321            Some(rl)
322        } else if let Some(ref rate_config) = config.rate_limiting {
323            if rate_config.enabled {
324                info!(
325                    rps_per_ip = rate_config.rps_per_ip,
326                    rps_per_user = rate_config.rps_per_user,
327                    "Initializing rate limiting from server config"
328                );
329                Some(Arc::new(RateLimiter::new(rate_config.clone())))
330            } else {
331                info!("Rate limiting disabled by configuration");
332                None
333            }
334        } else {
335            None
336        };
337
338        // Initialize observer runtime
339        #[cfg(feature = "observers")]
340        let observer_runtime = Self::init_observer_runtime(&config, db_pool.as_ref()).await?;
341
342        // Initialize Flight service with OIDC authentication if configured
343        #[cfg(feature = "arrow")]
344        let flight_service = {
345            let mut service = FraiseQLFlightService::new();
346            if let Some(ref validator) = oidc_validator {
347                info!("Enabling OIDC authentication for Arrow Flight");
348                service.set_oidc_validator(validator.clone());
349            } else {
350                info!("Arrow Flight initialized without authentication (dev mode)");
351            }
352            Some(service)
353        };
354
355        // Warn if PKCE is configured but [auth] is missing (no OidcServerClient).
356        #[cfg(feature = "auth")]
357        if pkce_store.is_some() && oidc_server_client.is_none() {
358            tracing::error!(
359                "pkce.enabled = true but [auth] is not configured or OIDC client init failed. \
360                 Auth routes (/auth/start, /auth/callback) will NOT be mounted. \
361                 Add [auth] with discovery_url, client_id, client_secret_env, and \
362                 server_redirect_uri to fraiseql.toml and recompile the schema."
363            );
364        }
365
366        // Refuse to start if FRAISEQL_REQUIRE_REDIS is set and PKCE store is in-memory.
367        #[cfg(feature = "auth")]
368        Self::check_redis_requirement(pkce_store.as_ref())?;
369
370        // Spawn background PKCE state cleanup task (every 5 minutes).
371        #[cfg(feature = "auth")]
372        Self::spawn_pkce_cleanup(pkce_store.as_ref(), &mut tasks);
373
374        // Reason: state_encryption/pkce_store/oidc_server_client are only stored when
375        //         feature = "auth" is enabled; without it they are legitimately unused.
376        #[cfg(not(feature = "auth"))]
377        let _ = (state_encryption, pkce_store, oidc_server_client);
378        Ok(Self {
379            config,
380            executor,
381            subscription_manager,
382            subscription_lifecycle: Arc::new(crate::subscriptions::NoopLifecycle),
383            max_subscriptions_per_connection: None,
384            oidc_validator,
385            hs256_auth,
386            rate_limiter,
387            #[cfg(feature = "secrets")]
388            secrets_manager: None,
389            #[cfg(feature = "federation")]
390            circuit_breaker,
391            error_sanitizer,
392            #[cfg(feature = "auth")]
393            state_encryption,
394            #[cfg(feature = "auth")]
395            pkce_store,
396            #[cfg(feature = "auth")]
397            oidc_server_client,
398            #[cfg(feature = "auth")]
399            social_login: None,
400            #[cfg(feature = "auth")]
401            mfa_state: None,
402            #[cfg(feature = "auth")]
403            anon_signup_state: None,
404            api_key_authenticator,
405            revocation_manager,
406            apq_store: None,
407            trusted_docs,
408            #[cfg(feature = "observers")]
409            observer_runtime,
410            #[cfg(feature = "auth")]
411            enrichment_pool: db_pool.clone(),
412            #[cfg(feature = "observers")]
413            db_pool,
414            storage_state: None,
415            realtime_state: None,
416            tenant_executor_factory: None,
417            #[cfg(feature = "arrow")]
418            flight_service,
419            #[cfg(feature = "mcp")]
420            mcp_config: None,
421            pool_tuning_config: None,
422            adapter_cache_enabled: false,
423            broadcast_manager: None,
424            presence_manager: None,
425            storage_backend: None,
426            storage_max_upload_bytes: 100 * 1024 * 1024, // 100 MiB default
427            #[cfg(feature = "functions")]
428            function_store: None,
429            #[cfg(feature = "functions")]
430            function_runtime: None,
431            usage: Arc::clone(crate::usage::aggregator::global_aggregator()),
432            tasks,
433        })
434    }
435
436    /// Spawn the periodic PKCE state-cleanup task into the server's [`JoinSet`].
437    ///
438    /// Cleanup runs every 5 minutes for the lifetime of the server. The handle
439    /// is owned by `tasks` so graceful shutdown awaits its termination.
440    #[cfg(feature = "auth")]
441    pub(super) fn spawn_pkce_cleanup(
442        pkce_store: Option<&Arc<crate::auth::PkceStateStore>>,
443        tasks: &mut tokio::task::JoinSet<()>,
444    ) {
445        use std::time::Duration;
446
447        use tokio::time::MissedTickBehavior;
448
449        if let Some(store) = pkce_store {
450            let store_clone = Arc::clone(store);
451            tasks.spawn(async move {
452                let mut ticker = tokio::time::interval(Duration::from_secs(300));
453                ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
454                loop {
455                    ticker.tick().await;
456                    store_clone.cleanup_expired().await;
457                }
458            });
459        }
460    }
461
462    /// Set lifecycle hooks for `WebSocket` subscriptions.
463    #[must_use]
464    pub fn with_subscription_lifecycle(
465        mut self,
466        lifecycle: Arc<dyn crate::subscriptions::SubscriptionLifecycle>,
467    ) -> Self {
468        self.subscription_lifecycle = lifecycle;
469        self
470    }
471
472    /// Set maximum subscriptions allowed per `WebSocket` connection.
473    #[must_use]
474    pub const fn with_max_subscriptions_per_connection(mut self, max: u32) -> Self {
475        self.max_subscriptions_per_connection = Some(max);
476        self
477    }
478
479    /// Attach the per-tenant executor factory used to provision tenants at
480    /// runtime (`PUT /api/v1/admin/tenants/{key}`).
481    ///
482    /// Build it with
483    /// [`make_executor_factory`](crate::tenancy::make_executor_factory) from the
484    /// concrete adapter type (which must implement
485    /// [`FromPoolConfig`](crate::tenancy::FromPoolConfig)). When the multi-tenant
486    /// runtime is enabled (`[tenancy.runtime] enabled = true`), `build_app_state`
487    /// installs it into `AppState`. Call this before `serve`.
488    #[must_use]
489    pub fn with_tenant_executor_factory(
490        mut self,
491        factory: crate::tenancy::TenantExecutorFactory<A>,
492    ) -> Self {
493        self.tenant_executor_factory = Some(factory);
494        self
495    }
496
497    /// Attach a pre-built realtime `WebSocket` state to the server.
498    ///
499    /// When set, `build_base_router` will merge `realtime_router(state)` at
500    /// `/realtime/v1`.  Call this after constructing the server but before
501    /// calling `serve` or `serve_with_shutdown`.
502    #[must_use]
503    pub fn with_realtime(mut self, state: crate::realtime::server::RealtimeState) -> Self {
504        self.realtime_state = Some(state);
505        self
506    }
507
508    /// Enable ephemeral broadcast channels (`POST /realtime/v1/broadcast`).
509    #[must_use]
510    pub fn with_broadcast(mut self, config: crate::subscriptions::BroadcastConfig) -> Self {
511        self.broadcast_manager =
512            Some(Arc::new(crate::subscriptions::BroadcastManager::new(config)));
513        self
514    }
515
516    /// Enable room-based presence tracking.
517    #[must_use]
518    pub fn with_presence(mut self, config: crate::subscriptions::PresenceConfig) -> Self {
519        self.presence_manager = Some(Arc::new(crate::subscriptions::PresenceManager::new(config)));
520        self
521    }
522
523    /// Enable adaptive connection pool sizing.
524    ///
525    /// When `config.enabled` is `true`, the server will spawn a background
526    /// polling task that samples pool metrics and recommends or applies resizes.
527    ///
528    /// # Errors
529    ///
530    /// Returns an error string if the configuration fails validation (e.g. `min >= max`).
531    pub fn with_pool_tuning(
532        mut self,
533        config: crate::config::pool_tuning::PoolPressureMonitorConfig,
534    ) -> std::result::Result<Self, String> {
535        config.validate()?;
536        self.pool_tuning_config = Some(config);
537        Ok(self)
538    }
539
540    /// Attach a unified social-login provider registry.
541    ///
542    /// When set, the server mounts `GET /auth/v1/authorize` which redirects
543    /// users to the specified `OAuth` provider's authorization URL with a `CSRF`
544    /// state token.
545    ///
546    /// # Example
547    ///
548    /// ```ignore
549    /// use fraiseql_auth::social::{SocialLoginState, SocialProviderRegistry};
550    /// let state = Arc::new(SocialLoginState { ... });
551    /// let server = server.with_social_login(state);
552    /// ```
553    #[cfg(feature = "auth")]
554    #[must_use]
555    pub fn with_social_login(
556        mut self,
557        social_login: Arc<crate::auth::social::SocialLoginState>,
558    ) -> Self {
559        self.social_login = Some(social_login);
560        self
561    }
562
563    /// Attach anonymous signup state to mount `POST /auth/v1/signup`.
564    ///
565    /// When set, any client can obtain a guest session without credentials.
566    /// The returned `user_id` carries an `anon_` prefix and the session lasts
567    /// 7 days.  Signups are rate-limited per client IP.
568    #[cfg(feature = "auth")]
569    #[must_use]
570    pub fn with_anon_signup(mut self, state: Arc<crate::auth::AnonSignupState>) -> Self {
571        self.anon_signup_state = Some(state);
572        self
573    }
574
575    /// Attach `TOTP` `MFA` state to mount the `/auth/v1/mfa/` endpoints.
576    ///
577    /// Mounts four routes:
578    /// - `POST /auth/v1/mfa/enroll` — begin enrollment, returns `otpauth://` `URI`
579    /// - `POST /auth/v1/mfa/confirm` — confirm enrollment with a live `TOTP` code
580    /// - `POST /auth/v1/mfa/challenge` — issue a short-lived challenge token
581    /// - `POST /auth/v1/mfa/verify` — verify code and issue session
582    /// - `POST /auth/v1/mfa/unenroll` — remove `MFA` from an account
583    #[cfg(feature = "auth")]
584    #[must_use]
585    pub fn with_mfa(mut self, mfa_state: Arc<crate::auth::MfaRouteState>) -> Self {
586        self.mfa_state = Some(mfa_state);
587        self
588    }
589
590    /// Attach an object storage backend and mount `/storage/v1/` routes.
591    ///
592    /// When set, the server mounts `GET`, `POST`, `DELETE /storage/v1/object/*key`
593    /// and `GET /storage/v1/object/sign/*key` endpoints backed by the given backend.
594    ///
595    /// Use [`StorageConfig`](crate::config::StorageConfig) and
596    /// [`create_backend`](crate::storage::create_backend) to construct the backend
597    /// from a TOML configuration block.
598    #[must_use]
599    pub fn with_storage(mut self, backend: Arc<dyn crate::storage::StorageBackend>) -> Self {
600        self.storage_backend = Some(backend);
601        self
602    }
603
604    /// Override the maximum allowed upload size for storage endpoints.
605    ///
606    /// Defaults to 100 `MiB`. Uploads exceeding this size are rejected with HTTP 413
607    /// before the body is forwarded to the storage backend.
608    #[must_use]
609    pub const fn with_storage_max_upload_bytes(mut self, bytes: usize) -> Self {
610        self.storage_max_upload_bytes = bytes;
611        self
612    }
613
614    /// Attach a pre-built [`StorageState`](fraiseql_storage::StorageState) and
615    /// mount the bucket-scoped `/storage/v1/*` routes (object upload/download/
616    /// delete, list, presign) with per-bucket access policy and RLS.
617    ///
618    /// This is the full storage path (metadata-backed, bucket-aware); it differs
619    /// from [`with_storage`](Self::with_storage), which mounts the simpler legacy
620    /// object router. Authentication is applied by `mount_storage_state`: a
621    /// configured `storage_token` acts as an admin bearer and, when an OIDC
622    /// validator is present, per-user tokens populate the request's
623    /// `StorageUser` for RLS.
624    #[must_use]
625    pub fn with_storage_state(mut self, state: fraiseql_storage::StorageState) -> Self {
626        self.storage_state = Some(state);
627        self
628    }
629
630    /// Install a pre-built token-revocation manager, replacing whatever the generic
631    /// construction path produced.
632    ///
633    /// Used by the PostgreSQL runtime path to install the Postgres-backed store
634    /// (#357): `revocation_manager_from_schema` defers the `postgres` backend because
635    /// it needs a database connection, so `main.rs` builds it with
636    /// `build_postgres_revocation_manager` and installs it here.
637    #[must_use]
638    pub fn with_revocation_manager(
639        mut self,
640        manager: Arc<crate::token_revocation::TokenRevocationManager>,
641    ) -> Self {
642        self.revocation_manager = Some(manager);
643        self
644    }
645
646    /// Attach a function deployment store and runtime, mounting `/functions/v1/` routes.
647    ///
648    /// When set, the server mounts `POST /functions/v1/{name}` which loads the
649    /// function bytecode from `store`, executes it via `runtime`, and returns the
650    /// JSON-encoded [`FunctionResult`](fraiseql_functions::FunctionResult).
651    #[cfg(feature = "functions")]
652    #[must_use]
653    pub fn with_functions(
654        mut self,
655        store: Arc<dyn fraiseql_functions::FunctionStore>,
656        runtime: Arc<dyn fraiseql_functions::runtime::SendFunctionRuntime>,
657    ) -> Self {
658        self.function_store = Some(store);
659        self.function_runtime = Some(runtime);
660        self
661    }
662
663    /// Set secrets manager for the server.
664    ///
665    /// This allows attaching a secrets manager after server creation for credential management.
666    #[cfg(feature = "secrets")]
667    pub fn set_secrets_manager(&mut self, manager: Arc<crate::secrets_manager::SecretsManager>) {
668        self.secrets_manager = Some(manager);
669        info!("Secrets manager attached to server");
670    }
671
672    /// Serve MCP over stdio (stdin/stdout) instead of HTTP.
673    ///
674    /// This is used when `FRAISEQL_MCP_STDIO=1` is set.  The server reads JSON-RPC
675    /// messages from stdin and writes responses to stdout, following the MCP stdio
676    /// transport specification.
677    ///
678    /// # Errors
679    ///
680    /// Returns an error if MCP is not configured or the stdio transport fails.
681    #[cfg(feature = "mcp")]
682    pub async fn serve_mcp_stdio(self) -> Result<()> {
683        use rmcp::ServiceExt;
684
685        let mcp_cfg = self.mcp_config.ok_or_else(|| {
686            ServerError::ConfigError(
687                "FRAISEQL_MCP_STDIO=1 but MCP is not configured. \
688                 Add [mcp] enabled = true to fraiseql.toml and recompile the schema."
689                    .into(),
690            )
691        })?;
692
693        let schema = Arc::new(self.executor.schema().clone());
694        let executor = self.executor.clone();
695
696        let service = crate::mcp::handler::FraiseQLMcpService::new(schema, executor, mcp_cfg)
697            .with_oidc_validator(self.oidc_validator.clone());
698
699        info!("MCP stdio transport starting — reading from stdin, writing to stdout");
700
701        let running = service
702            .serve((tokio::io::stdin(), tokio::io::stdout()))
703            .await
704            .map_err(|e| ServerError::ConfigError(format!("MCP stdio init failed: {e}")))?;
705
706        running
707            .waiting()
708            .await
709            .map_err(|e| ServerError::ConfigError(format!("MCP stdio error: {e}")))?;
710
711        Ok(())
712    }
713}