Skip to main content

fraiseql_core/runtime/executor/
execution.rs

1//! Core query execution — `execute()`, `execute_internal()`, `execute_with_scopes()`.
2
3use std::{sync::Arc, time::Duration};
4
5use super::{Executor, QueryType, pipeline, support};
6use crate::{
7    db::traits::DatabaseAdapter,
8    error::{FraiseQLError, Result},
9    security::QueryValidator,
10};
11
12impl<A: DatabaseAdapter> Executor<A> {
13    /// Execute a GraphQL query string and return a serialized JSON response.
14    ///
15    /// Applies the configured query timeout if one is set. Handles queries,
16    /// mutations, introspection, federation, and node lookups.
17    ///
18    /// If `RuntimeConfig::query_validation` is set, `QueryValidator::validate()`
19    /// runs first (before parsing or SQL dispatch) to enforce size, depth, and
20    /// complexity limits. This protects direct `fraiseql-core` embedders that do
21    /// not route through `fraiseql-server`.
22    ///
23    /// # Errors
24    ///
25    /// - `FraiseQLError::Validation` — query violates configured depth/complexity/alias limits
26    ///   (only when `RuntimeConfig::query_validation` is `Some`).
27    /// - `FraiseQLError::Timeout` — query exceeded `RuntimeConfig::query_timeout_ms`.
28    /// - Any error returned by `execute_internal`.
29    pub async fn execute(
30        &self,
31        query: &str,
32        variables: Option<&serde_json::Value>,
33    ) -> Result<serde_json::Value> {
34        // GATE 1: Query structure validation (DoS protection for direct embedders).
35        if let Some(ref cfg) = self.ctx.config.query_validation {
36            QueryValidator::from_config(cfg.clone()).validate(query).map_err(|e| {
37                FraiseQLError::Validation {
38                    message: e.to_string(),
39                    path:    Some("query".to_string()),
40                }
41            })?;
42        }
43
44        // Apply query timeout if configured
45        if self.ctx.config.query_timeout_ms > 0 {
46            let timeout_duration = Duration::from_millis(self.ctx.config.query_timeout_ms);
47            tokio::time::timeout(timeout_duration, self.execute_internal(query, variables))
48                .await
49                .map_err(|_| {
50                    // Truncate query if too long for error reporting
51                    let query_snippet = if query.len() > 100 {
52                        format!("{}...", &query[..100])
53                    } else {
54                        query.to_string()
55                    };
56                    FraiseQLError::Timeout {
57                        timeout_ms: self.ctx.config.query_timeout_ms,
58                        query:      Some(query_snippet),
59                    }
60                })?
61        } else {
62            self.execute_internal(query, variables).await
63        }
64    }
65
66    /// Internal execution logic (called by `execute` with the timeout wrapper).
67    ///
68    /// # Errors
69    ///
70    /// - [`FraiseQLError::Parse`] — GraphQL query string is not valid GraphQL syntax.
71    /// - [`FraiseQLError::NotFound`] — the query name does not match any compiled query template.
72    /// - [`FraiseQLError::Database`] — the underlying database returned an error.
73    /// - [`FraiseQLError::Internal`] — response serialisation failed.
74    /// - [`FraiseQLError::Authorization`] — field-level access control denied a field.
75    pub(super) async fn execute_internal(
76        &self,
77        query: &str,
78        variables: Option<&serde_json::Value>,
79    ) -> Result<serde_json::Value> {
80        // 1. Classify query type — also returns the ParsedQuery for Regular
81        // queries so we do not parse the same string twice.
82        //
83        // The parse result is memoised in `parse_cache` (keyed by xxHash64 of
84        // the query string) so repeated identical queries skip re-parsing.
85        let cache_key = xxhash_rust::xxh3::xxh3_64(query.as_bytes());
86        let (query_type, maybe_parsed) = if let Some(arc) = self.ctx.parse_cache.get(&cache_key) {
87            arc.as_ref().clone()
88        } else {
89            let pair = self.classify_query_with_parse(query)?;
90            self.ctx.parse_cache.insert(cache_key, Arc::new(pair.clone()));
91            pair
92        };
93
94        // 1b. Operation-level authorization (#422): anonymous path (no principal →
95        //     `None`). Runs before single- AND multi-root dispatch so a deny
96        //     short-circuits the parallel pipeline. Mutations are gated downstream at
97        //     `execute_mutation_impl`. Fail-closed: a `Deny` or any policy error → 403.
98        if let Some(authorizer) = self.ctx.config.authorizer.as_ref() {
99            let ops = support::authz::collect_authz_ops(&query_type, maybe_parsed.as_ref());
100            crate::security::authorizer::enforce_authz(authorizer.as_ref(), None, &ops, variables)?;
101        }
102
103        // 2. Route to appropriate handler
104        match query_type {
105            QueryType::Regular => {
106                // Detect multi-root queries and dispatch them in parallel.
107                // `maybe_parsed` is always Some for Regular queries (see
108                // classify_query_with_parse).
109                let parsed = maybe_parsed.ok_or_else(|| FraiseQLError::Internal {
110                    message: "classifier returned Regular without a parsed query — this is a bug"
111                        .to_string(),
112                    source:  None,
113                })?;
114                if pipeline::is_multi_root(&parsed) {
115                    let pr = self.execute_parallel(&parsed, variables).await?;
116                    let data = pr.merge_into_data_map();
117                    return Ok(serde_json::json!({ "data": data }));
118                }
119                self.query_runner().execute_regular_query(query, variables).await
120            },
121            QueryType::Aggregate(query_name) => {
122                self.aggregate_runner()
123                    .execute_aggregate_dispatch(&query_name, variables, None)
124                    .await
125            },
126            QueryType::Window(query_name) => {
127                self.aggregate_runner()
128                    .execute_window_dispatch(&query_name, variables, None)
129                    .await
130            },
131            #[cfg(feature = "federation")]
132            QueryType::Federation(query_name) => {
133                self.execute_federation_query(&query_name, query, variables).await
134            },
135            #[cfg(not(feature = "federation"))]
136            QueryType::Federation(_) => {
137                let _ = (query, variables);
138                Err(FraiseQLError::Validation {
139                    message: "Federation is not enabled in this build".to_string(),
140                    path:    None,
141                })
142            },
143            QueryType::IntrospectionSchema => {
144                // Return pre-built __schema response (zero-cost at runtime)
145                Ok(self.ctx.introspection.schema_response.as_ref().clone())
146            },
147            QueryType::IntrospectionType(type_name) => {
148                // Return pre-built __type response (zero-cost at runtime)
149                Ok(self.ctx.introspection.get_type_response(&type_name))
150            },
151            QueryType::Mutation { name, selections } => {
152                self.execute_mutation_query(&name, variables, &selections).await
153            },
154            QueryType::NodeQuery { selections } => {
155                self.query_runner().execute_node_query(query, variables, &selections).await
156            },
157        }
158    }
159
160    /// Execute a GraphQL query with user context for field-level access control.
161    ///
162    /// This method validates that the user has permission to access all requested
163    /// fields before executing the query. If field filtering is enabled in the
164    /// `RuntimeConfig` and the user lacks required scopes, this returns an error.
165    ///
166    /// # Arguments
167    ///
168    /// * `query` - GraphQL query string
169    /// * `variables` - Query variables (optional)
170    /// * `user_scopes` - User's scopes from JWT token (pass empty slice if unauthenticated)
171    ///
172    /// # Returns
173    ///
174    /// GraphQL response as JSON string, or error if access denied
175    ///
176    /// # Errors
177    ///
178    /// * [`FraiseQLError::Validation`] — query validation fails, or the user's scopes do not
179    ///   include a field required by the `field_filter` policy.
180    /// * Propagates errors from query classification and execution.
181    ///
182    /// # Example
183    ///
184    /// ```no_run
185    /// // Requires: a live database adapter and authenticated user context.
186    /// // See: tests/integration/ for runnable examples.
187    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
188    /// let query = r#"query { users { id name salary } }"#;
189    /// // let user_scopes = user.scopes.clone();
190    /// // let result = executor.execute_with_scopes(query, None, &user_scopes).await?;
191    /// # Ok(()) }
192    /// ```
193    pub async fn execute_with_scopes(
194        &self,
195        query: &str,
196        variables: Option<&serde_json::Value>,
197        user_scopes: &[String],
198    ) -> Result<serde_json::Value> {
199        // GATE 1: Query structure validation (mirrors execute() — DoS protection).
200        if let Some(ref cfg) = self.ctx.config.query_validation {
201            QueryValidator::from_config(cfg.clone()).validate(query).map_err(|e| {
202                FraiseQLError::Validation {
203                    message: e.to_string(),
204                    path:    Some("query".to_string()),
205                }
206            })?;
207        }
208
209        // 2. Classify query type
210        let query_type = self.classify_query(query)?;
211
212        // 3. Validate field access if filter is configured
213        if let Some(ref filter) = self.ctx.config.field_filter {
214            // Only validate for regular queries (not introspection)
215            if matches!(query_type, QueryType::Regular) {
216                self.validate_field_access(query, variables, user_scopes, filter)?;
217            }
218        }
219
220        // 4. Delegate to execute_internal — single source of routing truth. Field-access validation
221        //    (step 3) has already run for Regular queries; all other query types (introspection,
222        //    aggregate, federation, …) are routed correctly via execute_internal without
223        //    duplication.
224        self.execute_internal(query, variables).await
225    }
226}