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;
62pub(crate) mod 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::{
113 Authorizer, FieldAuthorizer, FieldFilter, FieldFilterConfig, QueryValidatorConfig, RLSPolicy,
114};
115
116/// Runtime configuration for the FraiseQL query executor.
117///
118/// Controls safety limits, security policies, and performance tuning. All settings
119/// have production-safe defaults and can be overridden via the builder-style methods.
120///
121/// # Defaults
122///
123/// | Field | Default | Notes |
124/// |-------|---------|-------|
125/// | `cache_query_plans` | `true` | Caches parsed query plans for repeated queries |
126/// | `max_query_depth` | `10` | Prevents stack overflow on recursive GraphQL |
127/// | `max_query_complexity` | `1000` | Rough cost model; tune per workload |
128/// | `enable_tracing` | `false` | Emit `OpenTelemetry` spans for each query |
129/// | `query_timeout_ms` | `30 000` | Hard limit; 0 disables the timeout |
130/// | `field_filter` | `None` | No field-level access control |
131/// | `rls_policy` | `None` | No row-level security |
132/// | `authorizer` | `None` | No operation-level authorization |
133///
134/// # Example
135///
136/// ```
137/// use fraiseql_core::runtime::RuntimeConfig;
138/// use fraiseql_core::security::FieldFilterConfig;
139///
140/// let config = RuntimeConfig {
141/// max_query_depth: 5,
142/// max_query_complexity: 500,
143/// enable_tracing: true,
144/// query_timeout_ms: 5_000,
145/// ..RuntimeConfig::default()
146/// }
147/// .with_field_filter(
148/// FieldFilterConfig::new()
149/// .protect_field("User", "salary")
150/// .protect_field("User", "ssn"),
151/// );
152/// ```
153pub struct RuntimeConfig {
154 /// Enable query plan caching.
155 pub cache_query_plans: bool,
156
157 /// Maximum query depth (prevents deeply nested queries).
158 pub max_query_depth: usize,
159
160 /// Maximum query complexity score.
161 pub max_query_complexity: usize,
162
163 /// Maximum number of rows a top-level `first`/`last`/`limit` argument may
164 /// request, guarding against unbounded-pagination denial of service (#421):
165 /// the top-level row count is the one knob that sizes the database result set
166 /// and the serialized response. A request exceeding this is rejected with a
167 /// [`crate::FraiseQLError::Validation`]. `None` disables the ceiling. Default
168 /// `Some(1000)`.
169 pub max_page_size: Option<u32>,
170
171 /// Enable performance tracing.
172 pub enable_tracing: bool,
173
174 /// Optional field filter for access control.
175 /// When set, validates that users have required scopes to access fields.
176 pub field_filter: Option<FieldFilter>,
177
178 /// Optional row-level security (RLS) policy.
179 /// When set, evaluates access rules based on `SecurityContext` to determine
180 /// what rows a user can access (e.g., tenant isolation, owner-based access).
181 pub rls_policy: Option<Arc<dyn RLSPolicy>>,
182
183 /// Optional dynamic field-level authorizer.
184 ///
185 /// When set, fields marked policy-gated in the compiled schema
186 /// ([`FieldDefinition::authorize`](crate::schema::FieldDefinition)) are passed to
187 /// this authorizer per row, which returns an allow/deny decision based on the
188 /// principal, the parent row, and the field arguments. Composes as a logical AND
189 /// with the static `requires_scope` gate and is fail-closed (any error denies).
190 /// See [`FieldAuthorizer`].
191 pub field_authorizer: Option<Arc<dyn FieldAuthorizer>>,
192
193 /// Optional dynamic operation-level authorizer.
194 ///
195 /// When set, every operation (query, mutation, subscription) is passed to this
196 /// authorizer before dispatch, which returns an allow/deny decision based on the
197 /// principal (or `None` when anonymous), the operation kind and name, and the
198 /// request input. Composes as a logical AND with the static `requires_role` gate
199 /// and is fail-closed (any error or raise denies with HTTP 403 / `FORBIDDEN`).
200 /// See [`Authorizer`].
201 pub authorizer: Option<Arc<dyn Authorizer>>,
202
203 /// Query timeout in milliseconds (0 = no timeout).
204 pub query_timeout_ms: u64,
205
206 /// JSONB field optimization strategy options
207 pub jsonb_optimization: JsonbOptimizationOptions,
208
209 /// Optional query validation config.
210 ///
211 /// When `Some`, `QueryValidator::validate()` runs at the start of every
212 /// `Executor::execute()` call, before any parsing or SQL dispatch.
213 /// This provides `DoS` protection for direct `fraiseql-core` embedders that
214 /// do not route through `fraiseql-server` (which already runs `RequestValidator`
215 /// at the HTTP layer). Enforces: query size, depth, complexity, and alias count
216 /// (alias amplification protection).
217 ///
218 /// Set `None` to disable (default) — useful when the caller applies
219 /// validation at a higher layer, or when `fraiseql-server` is in use.
220 pub query_validation: Option<QueryValidatorConfig>,
221
222 /// Emit structured `tracing` events for every successfully-executed mutation.
223 ///
224 /// When `true`, a `tracing::info!` event with target `"fraiseql::mutation_audit"` is
225 /// emitted at the end of every successful `execute_mutation_query_with_security()` call.
226 /// The event carries fields: `mutation_name`, `entity_type`, `operation`, `tenant_id`.
227 ///
228 /// **Zero-cost when disabled**: the guard `if !self.config.audit_mutations { return }`
229 /// short-circuits before any string formatting or allocation occurs.
230 ///
231 /// Set to `true` when `audit_logging_enabled = true` in the compiled schema's
232 /// `[security.enterprise]` section (threaded through `Server::new()` at startup).
233 pub audit_mutations: bool,
234
235 /// Global switch for the Change-Spine change-log outbox write (default `true`).
236 ///
237 /// When `true`, every successful state-changing mutation writes one
238 /// `core.tb_entity_change_log` row in-transaction (the framework owns the
239 /// write). Set `false` to disable the outbox **globally** — e.g. for an
240 /// application that does not consume the Change Spine — so no mutation pays
241 /// the write. The per-mutation
242 /// [`MutationDefinition.changelog`](crate::schema::MutationDefinition) flag
243 /// composes as a logical AND on top of this: a row is written only when the
244 /// global switch is on **and** the mutation is not individually opted out.
245 ///
246 /// Sourced from `[changelog] enabled` in `fraiseql.toml`, overridable at
247 /// runtime by `FRAISEQL_CHANGELOG_ENABLED`.
248 pub changelog_enabled: bool,
249
250 /// Validate-bind-without-commit mode for mutations (default `false`).
251 ///
252 /// When `true`, every state-changing mutation is executed inside a database
253 /// transaction that is **rolled back** instead of committed: the function
254 /// binds and runs (so constraints, triggers, and the `mutation_response`
255 /// shape are all validated) but no writes persist and no change-log row is
256 /// emitted. Powers the `fraiseql query --dry-run` CLI smoke check and the
257 /// `doctor --runtime` mutation probes.
258 ///
259 /// Currently honoured only by the PostgreSQL adapter; other adapters return
260 /// a `Validation` error from `execute_function_call_dry_run` rather than
261 /// silently committing. Queries are unaffected (they never commit).
262 pub dry_run_mutations: bool,
263
264 /// Response-size guards for the typed cascade surface (graphql-cascade
265 /// `16_security`). A cascade mutation returning more affected entities than
266 /// [`CascadeLimits::max_updated_entities`] is truncated with `truncated`
267 /// metadata; one exceeding [`CascadeLimits::max_response_size_mb`] is
268 /// rejected. Same DoS-guard family as [`max_page_size`](Self::max_page_size).
269 pub cascade_limits: CascadeLimits,
270}
271
272/// Response-size limits for the typed cascade surface, per the graphql-cascade
273/// spec's security requirements (`specification/16_security.md`).
274///
275/// Defaults are the spec's: depth 3, 500 affected entities, 5 `MiB`.
276#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
277pub struct CascadeLimits {
278 /// Maximum relationship depth a cascade may traverse (spec default `3`).
279 pub max_depth: usize,
280 /// Maximum number of affected entities (`updated` + `deleted`) before the
281 /// cascade is truncated and flagged `truncated` in its metadata (spec
282 /// default `500`).
283 pub max_updated_entities: usize,
284 /// Maximum serialized cascade size in `MiB` before the mutation is rejected
285 /// (spec default `5`). A value of `0` **disables** the size ceiling — set it
286 /// only to intentionally lift the limit, never as an "unbounded" value reached
287 /// by accident.
288 pub max_response_size_mb: usize,
289}
290
291impl Default for CascadeLimits {
292 fn default() -> Self {
293 Self {
294 max_depth: 3,
295 max_updated_entities: 500,
296 max_response_size_mb: 5,
297 }
298 }
299}
300
301impl std::fmt::Debug for RuntimeConfig {
302 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303 f.debug_struct("RuntimeConfig")
304 .field("cache_query_plans", &self.cache_query_plans)
305 .field("max_query_depth", &self.max_query_depth)
306 .field("max_query_complexity", &self.max_query_complexity)
307 .field("max_page_size", &self.max_page_size)
308 .field("enable_tracing", &self.enable_tracing)
309 .field("field_filter", &self.field_filter.is_some())
310 .field("rls_policy", &self.rls_policy.is_some())
311 .field("field_authorizer", &self.field_authorizer.is_some())
312 .field("authorizer", &self.authorizer.is_some())
313 .field("query_timeout_ms", &self.query_timeout_ms)
314 .field("jsonb_optimization", &self.jsonb_optimization)
315 .field("query_validation", &self.query_validation)
316 .field("audit_mutations", &self.audit_mutations)
317 .field("changelog_enabled", &self.changelog_enabled)
318 .field("dry_run_mutations", &self.dry_run_mutations)
319 .field("cascade_limits", &self.cascade_limits)
320 .finish()
321 }
322}
323
324impl Default for RuntimeConfig {
325 fn default() -> Self {
326 Self {
327 cache_query_plans: true,
328 max_query_depth: 10,
329 max_query_complexity: 1000,
330 max_page_size: Some(1000),
331 enable_tracing: false,
332 field_filter: None,
333 rls_policy: None,
334 field_authorizer: None,
335 authorizer: None,
336 query_timeout_ms: 30_000, // 30 second default timeout
337 jsonb_optimization: JsonbOptimizationOptions::default(),
338 query_validation: None,
339 audit_mutations: false,
340 changelog_enabled: true,
341 dry_run_mutations: false,
342 cascade_limits: CascadeLimits::default(),
343 }
344 }
345}
346
347impl RuntimeConfig {
348 /// Create a new runtime config with a field filter.
349 ///
350 /// # Example
351 ///
352 /// ```
353 /// use fraiseql_core::runtime::RuntimeConfig;
354 /// use fraiseql_core::security::FieldFilterConfig;
355 ///
356 /// let config = RuntimeConfig::default()
357 /// .with_field_filter(
358 /// FieldFilterConfig::new()
359 /// .protect_field("User", "salary")
360 /// .protect_field("User", "ssn")
361 /// );
362 /// ```
363 #[must_use = "builder method returns modified builder"]
364 pub fn with_field_filter(mut self, config: FieldFilterConfig) -> Self {
365 self.field_filter = Some(FieldFilter::new(config));
366 self
367 }
368
369 /// Configure row-level security (RLS) policy for access control.
370 ///
371 /// When set, the executor will evaluate the RLS policy before executing queries,
372 /// applying WHERE clause filters based on the user's `SecurityContext`.
373 ///
374 /// # Example
375 ///
376 /// ```rust
377 /// use fraiseql_core::runtime::RuntimeConfig;
378 /// use fraiseql_core::security::DefaultRLSPolicy;
379 /// use std::sync::Arc;
380 ///
381 /// let config = RuntimeConfig::default()
382 /// .with_rls_policy(Arc::new(DefaultRLSPolicy::new()));
383 /// ```
384 #[must_use = "builder method returns modified builder"]
385 pub fn with_rls_policy(mut self, policy: Arc<dyn RLSPolicy>) -> Self {
386 self.rls_policy = Some(policy);
387 self
388 }
389
390 /// Configure a dynamic field-level authorizer.
391 ///
392 /// When set, fields marked policy-gated in the compiled schema
393 /// ([`FieldDefinition::authorize`](crate::schema::FieldDefinition)) are evaluated
394 /// per row by this authorizer. The decision composes as a logical AND with the
395 /// static `requires_scope` gate and is fail-closed (any error or raise denies
396 /// with HTTP 403 / `FORBIDDEN`). Parallel to [`with_rls_policy`](Self::with_rls_policy).
397 ///
398 /// # Example
399 ///
400 /// ```rust
401 /// use fraiseql_core::runtime::RuntimeConfig;
402 /// use fraiseql_core::security::{
403 /// FieldAuthorizer, FieldAuthzRequest, FieldAuthzDecision,
404 /// };
405 /// use fraiseql_core::error::Result;
406 /// use std::sync::Arc;
407 ///
408 /// struct AllowAll;
409 /// impl FieldAuthorizer for AllowAll {
410 /// fn authorize_field(&self, _req: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
411 /// Ok(FieldAuthzDecision::Allow)
412 /// }
413 /// }
414 ///
415 /// let config = RuntimeConfig::default().with_field_authorizer(Arc::new(AllowAll));
416 /// ```
417 #[must_use = "builder method returns modified builder"]
418 pub fn with_field_authorizer(mut self, authorizer: Arc<dyn FieldAuthorizer>) -> Self {
419 self.field_authorizer = Some(authorizer);
420 self
421 }
422
423 /// Override the cascade response-size limits (graphql-cascade `16_security`).
424 #[must_use = "builder method returns modified builder"]
425 pub const fn with_cascade_limits(mut self, limits: CascadeLimits) -> Self {
426 self.cascade_limits = limits;
427 self
428 }
429
430 /// Configure a dynamic operation-level authorizer.
431 ///
432 /// When set, every operation (query, mutation, subscription) is passed to this
433 /// authorizer before dispatch. The decision composes as a logical AND with the
434 /// static `requires_role` gate and is fail-closed (any error or raise denies with
435 /// HTTP 403 / `FORBIDDEN`). Parallel to
436 /// [`with_field_authorizer`](Self::with_field_authorizer) and
437 /// [`with_rls_policy`](Self::with_rls_policy).
438 ///
439 /// # Example
440 ///
441 /// ```rust
442 /// use fraiseql_core::runtime::RuntimeConfig;
443 /// use fraiseql_core::security::{Authorizer, AuthzRequest, AuthzDecision};
444 /// use fraiseql_core::error::Result;
445 /// use std::sync::Arc;
446 ///
447 /// struct AllowAll;
448 /// impl Authorizer for AllowAll {
449 /// fn authorize(&self, _req: &AuthzRequest<'_>) -> Result<AuthzDecision> {
450 /// Ok(AuthzDecision::Allow)
451 /// }
452 /// }
453 ///
454 /// let config = RuntimeConfig::default().with_authorizer(Arc::new(AllowAll));
455 /// ```
456 #[must_use = "builder method returns modified builder"]
457 pub fn with_authorizer(mut self, authorizer: Arc<dyn Authorizer>) -> Self {
458 self.authorizer = Some(authorizer);
459 self
460 }
461
462 /// Build a [`RuntimeConfig`] from a compiled schema, applying every
463 /// schema-derived runtime setting that an executor must honor.
464 ///
465 /// This is the **single seam** every server entry point routes through so
466 /// the config can never drift by constructor (H16): `Server::new`,
467 /// `with_relay_pagination`, and `with_flight_service` previously built the
468 /// executor with [`RuntimeConfig::default`], silently dropping the
469 /// compiled audit-logging flag, the #421 page-size ceiling, and the
470 /// change-log toggle, and skipping the schema-format-version check.
471 ///
472 /// Applied in order:
473 /// 1. **Schema-format-version validation** — a legacy schema (no version) warns; an
474 /// incompatible future version is rejected. Coupling the check into the constructor means a
475 /// caller cannot obtain a config while skipping the validation.
476 /// 2. **Audit logging** — `audit_mutations` from the compiled `[security.enterprise]
477 /// audit_logging_enabled`.
478 /// 3. **Page-size ceiling (#421)** — `FRAISEQL_MAX_PAGE_SIZE` overrides the compiled
479 /// `[validation] max_page_size`, which overrides the default.
480 /// 4. **Change-log outbox toggle** — `FRAISEQL_CHANGELOG_ENABLED` overrides the compiled
481 /// `[changelog] write_enabled` (default `true`).
482 ///
483 /// # Errors
484 ///
485 /// Returns the validation message when the schema's `schema_format_version`
486 /// is incompatible with this runtime.
487 pub fn from_compiled_schema(schema: &crate::schema::CompiledSchema) -> Result<Self, String> {
488 if schema.schema_format_version.is_none() {
489 tracing::warn!(
490 "Loaded schema has no schema_format_version (pre-v2.1 format). \
491 Re-compile with the current fraiseql-cli for version compatibility checking."
492 );
493 }
494 schema.validate_format_version()?;
495
496 // Audit logging: security.additional["enterprise"]["audit_logging_enabled"].
497 let audit_mutations = schema
498 .security
499 .as_ref()
500 .and_then(|s| s.additional.get("enterprise"))
501 .and_then(|e| e.get("audit_logging_enabled"))
502 .and_then(serde_json::Value::as_bool)
503 .unwrap_or(false);
504 if audit_mutations {
505 tracing::info!("Mutation audit logging enabled (target: fraiseql::mutation_audit)");
506 }
507
508 // #421: FRAISEQL_MAX_PAGE_SIZE > compiled [validation] max_page_size > default.
509 let max_page_size = page_size_precedence(
510 std::env::var("FRAISEQL_MAX_PAGE_SIZE").ok().as_deref(),
511 schema.validation_config.as_ref().and_then(|v| v.max_page_size),
512 );
513
514 // Change-Spine outbox write toggle (default on): FRAISEQL_CHANGELOG_ENABLED
515 // overrides the compiled [changelog] write_enabled.
516 let changelog_enabled = std::env::var("FRAISEQL_CHANGELOG_ENABLED")
517 .ok()
518 .map(|v| {
519 !matches!(v.trim().to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off")
520 })
521 .or_else(|| schema.changelog.as_ref().map(|c| c.write_enabled))
522 .unwrap_or(true);
523 if !changelog_enabled {
524 tracing::info!(
525 "Change-log outbox write disabled (FRAISEQL_CHANGELOG_ENABLED / [changelog] write_enabled)"
526 );
527 }
528
529 Ok(Self {
530 max_page_size,
531 audit_mutations,
532 changelog_enabled,
533 ..Self::default()
534 })
535 }
536}
537
538/// Resolve the top-level page-size ceiling (#421) by precedence.
539///
540/// `env` is the raw `FRAISEQL_MAX_PAGE_SIZE` value when set (a positive integer,
541/// or `"0"`/`"none"` to disable the ceiling). It overrides `compiled` (the
542/// `[validation] max_page_size` from the compiled schema), which overrides the
543/// runtime default (1000). Returns `None` only when explicitly disabled.
544#[must_use]
545pub fn page_size_precedence(env: Option<&str>, compiled: Option<u32>) -> Option<u32> {
546 if let Some(raw) = env {
547 let trimmed = raw.trim();
548 if trimmed.eq_ignore_ascii_case("none") || trimmed == "0" {
549 return None;
550 }
551 if let Ok(n) = trimmed.parse::<u32>() {
552 return Some(n);
553 }
554 // Unparseable env value: ignore it and fall through to compiled/default.
555 }
556 compiled.or(RuntimeConfig::default().max_page_size)
557}
558
559/// Execution context for query cancellation support.
560///
561/// This struct provides a mechanism for gracefully cancelling long-running queries
562/// via cancellation tokens, enabling proper cleanup and error reporting when:
563/// - A client connection closes
564/// - A user explicitly cancels a query
565/// - A system shutdown is initiated
566///
567/// # Example
568///
569/// ```no_run
570/// // Requires: a running tokio runtime and an Executor with a live database adapter.
571/// // See: tests/integration/ for runnable examples.
572/// use fraiseql_core::runtime::ExecutionContext;
573/// use std::time::Duration;
574///
575/// let ctx = ExecutionContext::new("query-123".to_string());
576///
577/// // Spawn a task that cancels after 5 seconds
578/// let cancel_token = ctx.cancellation_token().clone();
579/// tokio::spawn(async move {
580/// tokio::time::sleep(Duration::from_secs(5)).await;
581/// cancel_token.cancel();
582/// });
583///
584/// // Execute query with cancellation support
585/// // let result = executor.execute_with_context(query, None, &ctx).await;
586/// ```
587#[derive(Debug, Clone)]
588pub struct ExecutionContext {
589 /// Unique identifier for tracking the query execution
590 query_id: String,
591
592 /// Cancellation token for gracefully stopping the query
593 /// When cancelled, ongoing query execution should stop and return a Cancelled error
594 token: tokio_util::sync::CancellationToken,
595}
596
597impl ExecutionContext {
598 /// Create a new execution context with a cancellation token.
599 ///
600 /// # Arguments
601 ///
602 /// * `query_id` - Unique identifier for this query execution
603 ///
604 /// # Example
605 ///
606 /// ```rust
607 /// # use fraiseql_core::runtime::ExecutionContext;
608 /// let ctx = ExecutionContext::new("user-query-001".to_string());
609 /// assert_eq!(ctx.query_id(), "user-query-001");
610 /// ```
611 #[must_use]
612 pub fn new(query_id: String) -> Self {
613 Self {
614 query_id,
615 token: tokio_util::sync::CancellationToken::new(),
616 }
617 }
618
619 /// Get the query ID.
620 #[must_use]
621 pub fn query_id(&self) -> &str {
622 &self.query_id
623 }
624
625 /// Get a reference to the cancellation token.
626 ///
627 /// The returned token can be used to:
628 /// - Clone and pass to background tasks
629 /// - Check if cancellation was requested
630 /// - Propagate cancellation through the call stack
631 #[must_use]
632 pub const fn cancellation_token(&self) -> &tokio_util::sync::CancellationToken {
633 &self.token
634 }
635
636 /// Check if cancellation has been requested.
637 #[must_use]
638 pub fn is_cancelled(&self) -> bool {
639 self.token.is_cancelled()
640 }
641}
642
643#[cfg(test)]
644mod tests;