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