Skip to main content

fraiseql_server/server/
mod.rs

1//! HTTP server implementation.
2
3use std::sync::Arc;
4
5#[cfg(feature = "arrow")]
6use fraiseql_arrow::FraiseQLFlightService;
7use fraiseql_core::{
8    db::traits::DatabaseAdapter,
9    runtime::{Executor, SubscriptionManager},
10    security::{AuthMiddleware, OidcValidator},
11};
12#[cfg(feature = "observers")]
13use {
14    crate::observers::{ObserverRuntime, ObserverRuntimeConfig},
15    tokio::sync::RwLock,
16};
17
18#[cfg(feature = "auth")]
19use crate::routes::{AuthMeState, AuthPkceState, auth_callback, auth_me, auth_start};
20use crate::{
21    Result, ServerError,
22    middleware::{
23        BearerAuthState, OidcAuthState, RateLimiter, bearer_auth_middleware, cors_layer_restricted,
24        metrics_middleware, oidc_auth_middleware, require_json_content_type, trace_layer,
25    },
26    routes::{
27        BroadcastState, PlaygroundState, SubscriptionState, api, broadcast_handler,
28        graphql_get_handler, graphql_handler, health_handler, introspection_handler,
29        metrics_handler, metrics_json_handler, playground_handler, readiness_handler,
30        subscription_handler,
31    },
32    server_config::ServerConfig,
33    tls::TlsSetup,
34};
35
36mod builder;
37mod extensions;
38mod initialization;
39mod lifecycle;
40mod routing;
41
42#[cfg(test)]
43mod routing_tests;
44
45#[cfg(test)]
46mod tests;
47
48/// FraiseQL HTTP Server.
49///
50/// `Server<A>` is generic over a `DatabaseAdapter` implementation, which allows
51/// swapping database backends and injecting mock adapters in tests.
52///
53/// # Feature: `observers`
54///
55/// When compiled with the `observers` Cargo feature, the server mounts observer
56/// management and runtime-health API endpoints under `/api/observers`. These
57/// endpoints require a live **PostgreSQL** connection pool (`sqlx::PgPool`).
58///
59/// Pass `Some(pg_pool)` as the `db_pool` argument to [`Server::new`] when the
60/// `observers` feature is enabled. Passing `None` causes the observer routes to
61/// be skipped at startup (an error is logged) rather than panicking, but the
62/// rest of the server continues to function normally.
63///
64/// The PostgreSQL pool is distinct from the generic `DatabaseAdapter`: the
65/// adapter handles application queries, while the pool is used exclusively by
66/// the observer subsystem to store and retrieve reactive rule metadata.
67pub struct Server<A: DatabaseAdapter> {
68    pub(super) config: ServerConfig,
69    pub(super) executor: Arc<Executor<A>>,
70    pub(super) subscription_manager: Arc<SubscriptionManager>,
71    pub(super) subscription_lifecycle: Arc<dyn crate::subscriptions::SubscriptionLifecycle>,
72    pub(super) max_subscriptions_per_connection: Option<u32>,
73    pub(super) oidc_validator: Option<Arc<OidcValidator>>,
74    /// Local HS256 JWT validator (alternative to `oidc_validator`).
75    ///
76    /// When set, the GraphQL endpoint is protected by shared-secret JWT
77    /// validation instead of OIDC. Intended for integration testing and
78    /// internal service-to-service auth.
79    pub(super) hs256_auth: Option<Arc<AuthMiddleware>>,
80    pub(super) rate_limiter: Option<Arc<RateLimiter>>,
81    #[cfg(feature = "secrets")]
82    pub(super) secrets_manager: Option<Arc<crate::secrets_manager::SecretsManager>>,
83    #[cfg(feature = "federation")]
84    pub(super) circuit_breaker:
85        Option<Arc<crate::federation::circuit_breaker::FederationCircuitBreakerManager>>,
86    pub(super) error_sanitizer: Arc<crate::config::error_sanitization::ErrorSanitizer>,
87    #[cfg(feature = "auth")]
88    pub(super) state_encryption: Option<Arc<crate::auth::state_encryption::StateEncryptionService>>,
89    #[cfg(feature = "auth")]
90    pub(super) pkce_store: Option<Arc<crate::auth::PkceStateStore>>,
91    #[cfg(feature = "auth")]
92    pub(super) oidc_server_client: Option<Arc<crate::auth::OidcServerClient>>,
93    /// Unified social login provider registry.
94    ///
95    /// When `Some`, the server mounts `GET /auth/v1/authorize` and uses the
96    /// registry to look up `OAuth` providers by name.  Set via
97    /// [`Server::with_social_login`].
98    #[cfg(feature = "auth")]
99    pub(super) social_login: Option<Arc<crate::auth::social::SocialLoginState>>,
100    /// Anonymous session signup state.
101    ///
102    /// When `Some`, mounts `POST /auth/v1/signup`.  Set via [`Server::with_anon_signup`].
103    #[cfg(feature = "auth")]
104    pub(super) anon_signup_state: Option<Arc<crate::auth::AnonSignupState>>,
105    /// `TOTP` `MFA` route state.
106    ///
107    /// When `Some`, the server mounts the four `MFA` endpoints under
108    /// `/auth/v1/mfa/`.  Set via [`Server::with_mfa`].
109    #[cfg(feature = "auth")]
110    pub(super) mfa_state: Option<Arc<crate::auth::MfaRouteState>>,
111    pub(super) api_key_authenticator: Option<Arc<crate::api_key::ApiKeyAuthenticator>>,
112    // Reason: only read inside #[cfg(feature = "auth")] blocks in routing.rs
113    #[allow(dead_code)] // Reason: field kept for API completeness; may be used in future features
114    pub(super) revocation_manager: Option<Arc<crate::token_revocation::TokenRevocationManager>>,
115    pub(super) apq_store: Option<fraiseql_core::apq::ArcApqStorage>,
116    pub(super) trusted_docs: Option<Arc<crate::trusted_documents::TrustedDocumentStore>>,
117
118    #[cfg(feature = "observers")]
119    pub(super) observer_runtime: Option<Arc<RwLock<ObserverRuntime>>>,
120
121    #[cfg(feature = "observers")]
122    pub(super) db_pool: Option<sqlx::PgPool>,
123
124    /// PostgreSQL pool for claims enrichment queries (independent of observers).
125    #[cfg(feature = "auth")]
126    #[allow(dead_code)] // Reason: read by enrichment routing code (ported in sub-phase 4e)
127    pub(super) enrichment_pool: Option<sqlx::PgPool>,
128
129    #[cfg(feature = "arrow")]
130    pub(super) flight_service: Option<FraiseQLFlightService>,
131
132    #[cfg(feature = "mcp")]
133    pub(super) mcp_config: Option<fraiseql_core::schema::McpConfig>,
134
135    /// Pre-built storage state for mounting storage routes.
136    ///
137    /// Populated during server construction when `[storage]` is configured and
138    /// a PostgreSQL pool is available for metadata tracking.
139    pub(super) storage_state: Option<fraiseql_storage::StorageState>,
140
141    /// Pre-built realtime state for mounting the `WebSocket` endpoint.
142    ///
143    /// When `Some`, `build_base_router` merges `realtime_router(state)` at
144    /// `/realtime/v1`. Set via [`Server::with_realtime`].
145    pub(super) realtime_state: Option<crate::realtime::server::RealtimeState>,
146
147    /// Factory for building per-tenant executors at registration time.
148    ///
149    /// Set by the binary's PostgreSQL boot path (where the concrete adapter
150    /// implements [`FromPoolConfig`](crate::tenancy::FromPoolConfig)) via
151    /// [`Server::with_tenant_executor_factory`]. When the multi-tenant runtime is
152    /// enabled, `build_app_state` installs it into `AppState` so
153    /// `PUT /api/v1/admin/tenants/{key}` can provision tenants. `None` leaves
154    /// runtime provisioning unavailable (dispatch to pre-registered tenants still
155    /// works).
156    pub(super) tenant_executor_factory: Option<crate::tenancy::TenantExecutorFactory<A>>,
157
158    /// Pool pressure monitoring configuration (loaded from `[pool_tuning]` in `fraiseql.toml`).
159    pub(super) pool_tuning_config: Option<crate::config::pool_tuning::PoolPressureMonitorConfig>,
160
161    /// Whether the adapter-level query result cache (`CachedDatabaseAdapter`) is active.
162    ///
163    /// Set to `true` when `ServerConfig::cache_enabled = true` and the server was built
164    /// with `Server::new` or `Server::with_relay_pagination`.
165    pub(super) adapter_cache_enabled: bool,
166
167    /// Broadcast channel manager for ephemeral realtime pub/sub.
168    pub(super) broadcast_manager: Option<Arc<crate::subscriptions::BroadcastManager>>,
169
170    /// Presence manager for room-based member tracking.
171    pub(super) presence_manager: Option<Arc<crate::subscriptions::PresenceManager>>,
172
173    /// Object storage backend for the `/storage/v1/` routes.
174    ///
175    /// Set via [`Server::with_storage`]. When `None`, storage routes are not mounted.
176    pub(super) storage_backend:          Option<Arc<dyn crate::storage::StorageBackend>>,
177    /// Maximum allowed upload size for the storage backend (bytes).
178    ///
179    /// Defaults to 100 `MiB`. Applied as a per-request body limit on upload routes.
180    pub(super) storage_max_upload_bytes: usize,
181
182    /// Function deployment store for the `/functions/v1/` routes.
183    ///
184    /// Set via [`Server::with_functions`]. When `None`, function routes are not mounted.
185    #[cfg(feature = "functions")]
186    pub(super) function_store: Option<Arc<dyn fraiseql_functions::FunctionStore>>,
187
188    /// Function execution runtime for the `/functions/v1/` routes.
189    ///
190    /// Set via [`Server::with_functions`]. When `None`, function routes are not mounted.
191    #[cfg(feature = "functions")]
192    pub(super) function_runtime: Option<Arc<dyn fraiseql_functions::runtime::SendFunctionRuntime>>,
193
194    /// Shared usage aggregator — written by [`MutationAuditLayer`] and read by
195    /// the `GET /api/v1/admin/usage` endpoint via [`AppState::usage`].
196    ///
197    /// [`MutationAuditLayer`]: crate::usage::layer::MutationAuditLayer
198    /// [`AppState::usage`]: crate::routes::graphql::AppState::usage
199    pub(super) usage: Arc<crate::usage::aggregator::UsageAggregator>,
200
201    /// Background lifecycle tasks owned by the server.
202    ///
203    /// Long-running tasks spawned during server construction or `serve_with_shutdown`
204    /// (e.g. SIGUSR1 schema reload, PKCE state cleanup, trusted-documents manifest
205    /// reload, usage persistence flush, Arrow Flight gRPC server) are tracked on
206    /// this [`tokio::task::JoinSet`]. On graceful shutdown the server aborts and
207    /// awaits the set so per-process state is not abandoned mid-flight.
208    pub(super) tasks: tokio::task::JoinSet<()>,
209}