fraiseql_core/runtime/mod.rs
1//! Runtime query executor - executes compiled queries.
2//!
3//! # Architecture
4//!
5//! The runtime loads a `CompiledSchema` and executes incoming GraphQL queries by:
6//! 1. Parsing the GraphQL query
7//! 2. Matching it to a compiled query template
8//! 3. Binding variables
9//! 4. Executing the pre-compiled SQL
10//! 5. Projecting JSONB results to GraphQL response
11//!
12//! # Key Concepts
13//!
14//! - **Zero runtime compilation**: All SQL is pre-compiled
15//! - **Pattern matching**: Match incoming query structure to templates
16//! - **Variable binding**: Safe parameter substitution
17//! - **Result projection**: JSONB → GraphQL JSON transformation
18//!
19//! # Example
20//!
21//! ```no_run
22//! // Requires: a compiled schema file and a live PostgreSQL database.
23//! // See: tests/integration/ for runnable examples.
24//! use fraiseql_core::runtime::Executor;
25//! use fraiseql_core::schema::CompiledSchema;
26//! use fraiseql_core::db::postgres::PostgresAdapter;
27//! use std::sync::Arc;
28//!
29//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
30//! # let schema_json = r#"{"types":[],"queries":[]}"#;
31//! // Load compiled schema
32//! let schema = CompiledSchema::from_json(schema_json, false)?;
33//!
34//! // Create executor with a concrete adapter implementation
35//! let adapter = Arc::new(PostgresAdapter::new("postgresql://localhost/mydb").await?);
36//! let executor = Executor::new(schema, adapter);
37//!
38//! // Execute GraphQL query
39//! let query = r#"query { users { id name } }"#;
40//! let result = executor.execute(query, None).await?;
41//!
42//! println!("{}", result);
43//! # Ok(())
44//! # }
45//! ```
46
47mod aggregate_parser;
48mod aggregate_projector;
49pub mod aggregation;
50pub mod cascade;
51mod executor;
52pub mod executor_adapter;
53mod explain;
54pub mod field_filter;
55pub mod input_validator;
56pub mod jsonb_strategy;
57mod matcher;
58pub mod mutation_result;
59pub(crate) mod native_columns;
60pub mod partial_period;
61mod planner;
62mod projection;
63pub mod query_tracing;
64pub mod relay;
65pub mod sql_logger;
66pub mod subscription;
67pub mod tenant_enforcer;
68pub mod window;
69mod window_parser;
70mod window_projector;
71
72use std::sync::Arc;
73
74pub use aggregate_parser::AggregateQueryParser;
75pub use aggregate_projector::AggregationProjector;
76pub use aggregation::{AggregationSqlGenerator, ParameterizedAggregationSql};
77pub use executor::{
78 Executor,
79 pipeline::{extract_root_field_names, is_multi_root, multi_root_queries_total},
80};
81pub use executor_adapter::ExecutorAdapter;
82pub use explain::{ExplainPlan, ExplainResult};
83pub use field_filter::{FieldAccessResult, can_access_field, classify_field_access, filter_fields};
84pub use jsonb_strategy::{JsonbOptimizationOptions, JsonbStrategy};
85pub use matcher::{QueryMatch, QueryMatcher, suggest_similar};
86pub use planner::{ExecutionPlan, QueryPlanner};
87pub use projection::{FieldMapping, ProjectionMapper, ResultProjector, project_entity};
88pub use query_tracing::{
89 QueryExecutionTrace, QueryPhaseSpan, QueryTraceBuilder, create_phase_span, create_query_span,
90};
91pub use sql_logger::{SqlOperation, SqlQueryLog, SqlQueryLogBuilder, create_sql_span};
92pub use subscription::{
93 ActiveSubscription, DeliveryResult, KafkaAdapter, KafkaConfig, KafkaMessage, SubscriptionError,
94 SubscriptionEvent, SubscriptionId, SubscriptionManager, SubscriptionOperation,
95 SubscriptionPayload, TransportAdapter, TransportManager, WebhookAdapter, WebhookConfig,
96 WebhookPayload, extract_rls_conditions, protocol,
97};
98pub use tenant_enforcer::TenantEnforcer;
99
100/// Result of a bulk REST operation (collection-level PATCH/DELETE).
101#[derive(Debug, Clone)]
102pub struct BulkResult {
103 /// Number of rows affected.
104 pub affected_rows: u64,
105 /// Entities returned when `Prefer: return=representation` is set.
106 pub entities: Option<Vec<serde_json::Value>>,
107}
108pub use window::{WindowSql, WindowSqlGenerator};
109pub use window_parser::WindowQueryParser;
110pub use window_projector::WindowProjector;
111
112use crate::security::{FieldFilter, FieldFilterConfig, QueryValidatorConfig, RLSPolicy};
113
114/// Runtime configuration for the FraiseQL query executor.
115///
116/// Controls safety limits, security policies, and performance tuning. All settings
117/// have production-safe defaults and can be overridden via the builder-style methods.
118///
119/// # Defaults
120///
121/// | Field | Default | Notes |
122/// |-------|---------|-------|
123/// | `cache_query_plans` | `true` | Caches parsed query plans for repeated queries |
124/// | `max_query_depth` | `10` | Prevents stack overflow on recursive GraphQL |
125/// | `max_query_complexity` | `1000` | Rough cost model; tune per workload |
126/// | `enable_tracing` | `false` | Emit `OpenTelemetry` spans for each query |
127/// | `query_timeout_ms` | `30 000` | Hard limit; 0 disables the timeout |
128/// | `field_filter` | `None` | No field-level access control |
129/// | `rls_policy` | `None` | No row-level security |
130///
131/// # Example
132///
133/// ```
134/// use fraiseql_core::runtime::RuntimeConfig;
135/// use fraiseql_core::security::FieldFilterConfig;
136///
137/// let config = RuntimeConfig {
138/// max_query_depth: 5,
139/// max_query_complexity: 500,
140/// enable_tracing: true,
141/// query_timeout_ms: 5_000,
142/// ..RuntimeConfig::default()
143/// }
144/// .with_field_filter(
145/// FieldFilterConfig::new()
146/// .protect_field("User", "salary")
147/// .protect_field("User", "ssn"),
148/// );
149/// ```
150pub struct RuntimeConfig {
151 /// Enable query plan caching.
152 pub cache_query_plans: bool,
153
154 /// Maximum query depth (prevents deeply nested queries).
155 pub max_query_depth: usize,
156
157 /// Maximum query complexity score.
158 pub max_query_complexity: usize,
159
160 /// Enable performance tracing.
161 pub enable_tracing: bool,
162
163 /// Optional field filter for access control.
164 /// When set, validates that users have required scopes to access fields.
165 pub field_filter: Option<FieldFilter>,
166
167 /// Optional row-level security (RLS) policy.
168 /// When set, evaluates access rules based on `SecurityContext` to determine
169 /// what rows a user can access (e.g., tenant isolation, owner-based access).
170 pub rls_policy: Option<Arc<dyn RLSPolicy>>,
171
172 /// Query timeout in milliseconds (0 = no timeout).
173 pub query_timeout_ms: u64,
174
175 /// JSONB field optimization strategy options
176 pub jsonb_optimization: JsonbOptimizationOptions,
177
178 /// Optional query validation config.
179 ///
180 /// When `Some`, `QueryValidator::validate()` runs at the start of every
181 /// `Executor::execute()` call, before any parsing or SQL dispatch.
182 /// This provides `DoS` protection for direct `fraiseql-core` embedders that
183 /// do not route through `fraiseql-server` (which already runs `RequestValidator`
184 /// at the HTTP layer). Enforces: query size, depth, complexity, and alias count
185 /// (alias amplification protection).
186 ///
187 /// Set `None` to disable (default) — useful when the caller applies
188 /// validation at a higher layer, or when `fraiseql-server` is in use.
189 pub query_validation: Option<QueryValidatorConfig>,
190
191 /// Emit structured `tracing` events for every successfully-executed mutation.
192 ///
193 /// When `true`, a `tracing::info!` event with target `"fraiseql::mutation_audit"` is
194 /// emitted at the end of every successful `execute_mutation_query_with_security()` call.
195 /// The event carries fields: `mutation_name`, `entity_type`, `operation`, `tenant_id`.
196 ///
197 /// **Zero-cost when disabled**: the guard `if !self.config.audit_mutations { return }`
198 /// short-circuits before any string formatting or allocation occurs.
199 ///
200 /// Set to `true` when `audit_logging_enabled = true` in the compiled schema's
201 /// `[security.enterprise]` section (threaded through `Server::new()` at startup).
202 pub audit_mutations: bool,
203}
204
205impl std::fmt::Debug for RuntimeConfig {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 f.debug_struct("RuntimeConfig")
208 .field("cache_query_plans", &self.cache_query_plans)
209 .field("max_query_depth", &self.max_query_depth)
210 .field("max_query_complexity", &self.max_query_complexity)
211 .field("enable_tracing", &self.enable_tracing)
212 .field("field_filter", &self.field_filter.is_some())
213 .field("rls_policy", &self.rls_policy.is_some())
214 .field("query_timeout_ms", &self.query_timeout_ms)
215 .field("jsonb_optimization", &self.jsonb_optimization)
216 .field("query_validation", &self.query_validation)
217 .field("audit_mutations", &self.audit_mutations)
218 .finish()
219 }
220}
221
222impl Default for RuntimeConfig {
223 fn default() -> Self {
224 Self {
225 cache_query_plans: true,
226 max_query_depth: 10,
227 max_query_complexity: 1000,
228 enable_tracing: false,
229 field_filter: None,
230 rls_policy: None,
231 query_timeout_ms: 30_000, // 30 second default timeout
232 jsonb_optimization: JsonbOptimizationOptions::default(),
233 query_validation: None,
234 audit_mutations: false,
235 }
236 }
237}
238
239impl RuntimeConfig {
240 /// Create a new runtime config with a field filter.
241 ///
242 /// # Example
243 ///
244 /// ```
245 /// use fraiseql_core::runtime::RuntimeConfig;
246 /// use fraiseql_core::security::FieldFilterConfig;
247 ///
248 /// let config = RuntimeConfig::default()
249 /// .with_field_filter(
250 /// FieldFilterConfig::new()
251 /// .protect_field("User", "salary")
252 /// .protect_field("User", "ssn")
253 /// );
254 /// ```
255 #[must_use = "builder method returns modified builder"]
256 pub fn with_field_filter(mut self, config: FieldFilterConfig) -> Self {
257 self.field_filter = Some(FieldFilter::new(config));
258 self
259 }
260
261 /// Configure row-level security (RLS) policy for access control.
262 ///
263 /// When set, the executor will evaluate the RLS policy before executing queries,
264 /// applying WHERE clause filters based on the user's `SecurityContext`.
265 ///
266 /// # Example
267 ///
268 /// ```rust
269 /// use fraiseql_core::runtime::RuntimeConfig;
270 /// use fraiseql_core::security::DefaultRLSPolicy;
271 /// use std::sync::Arc;
272 ///
273 /// let config = RuntimeConfig::default()
274 /// .with_rls_policy(Arc::new(DefaultRLSPolicy::new()));
275 /// ```
276 #[must_use = "builder method returns modified builder"]
277 pub fn with_rls_policy(mut self, policy: Arc<dyn RLSPolicy>) -> Self {
278 self.rls_policy = Some(policy);
279 self
280 }
281}
282
283/// Execution context for query cancellation support.
284///
285/// This struct provides a mechanism for gracefully cancelling long-running queries
286/// via cancellation tokens, enabling proper cleanup and error reporting when:
287/// - A client connection closes
288/// - A user explicitly cancels a query
289/// - A system shutdown is initiated
290///
291/// # Example
292///
293/// ```no_run
294/// // Requires: a running tokio runtime and an Executor with a live database adapter.
295/// // See: tests/integration/ for runnable examples.
296/// use fraiseql_core::runtime::ExecutionContext;
297/// use std::time::Duration;
298///
299/// let ctx = ExecutionContext::new("query-123".to_string());
300///
301/// // Spawn a task that cancels after 5 seconds
302/// let cancel_token = ctx.cancellation_token().clone();
303/// tokio::spawn(async move {
304/// tokio::time::sleep(Duration::from_secs(5)).await;
305/// cancel_token.cancel();
306/// });
307///
308/// // Execute query with cancellation support
309/// // let result = executor.execute_with_context(query, None, &ctx).await;
310/// ```
311#[derive(Debug, Clone)]
312pub struct ExecutionContext {
313 /// Unique identifier for tracking the query execution
314 query_id: String,
315
316 /// Cancellation token for gracefully stopping the query
317 /// When cancelled, ongoing query execution should stop and return a Cancelled error
318 token: tokio_util::sync::CancellationToken,
319}
320
321impl ExecutionContext {
322 /// Create a new execution context with a cancellation token.
323 ///
324 /// # Arguments
325 ///
326 /// * `query_id` - Unique identifier for this query execution
327 ///
328 /// # Example
329 ///
330 /// ```rust
331 /// # use fraiseql_core::runtime::ExecutionContext;
332 /// let ctx = ExecutionContext::new("user-query-001".to_string());
333 /// assert_eq!(ctx.query_id(), "user-query-001");
334 /// ```
335 #[must_use]
336 pub fn new(query_id: String) -> Self {
337 Self {
338 query_id,
339 token: tokio_util::sync::CancellationToken::new(),
340 }
341 }
342
343 /// Get the query ID.
344 #[must_use]
345 pub fn query_id(&self) -> &str {
346 &self.query_id
347 }
348
349 /// Get a reference to the cancellation token.
350 ///
351 /// The returned token can be used to:
352 /// - Clone and pass to background tasks
353 /// - Check if cancellation was requested
354 /// - Propagate cancellation through the call stack
355 #[must_use]
356 pub const fn cancellation_token(&self) -> &tokio_util::sync::CancellationToken {
357 &self.token
358 }
359
360 /// Check if cancellation has been requested.
361 #[must_use]
362 pub fn is_cancelled(&self) -> bool {
363 self.token.is_cancelled()
364 }
365}
366
367#[cfg(test)]
368mod tests;