gql 0.3.2

A GraphQL reference implementation for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Execution of documents that were prepared ahead of time.
//!
//! The public [`crate::prepared`] module owns the self-referential cell and the prepared-query
//! API. This module only contains the pieces the executor needs: the dependent document type and
//! the two entry points that replace parsing/validation with a borrow of an already parsed
//! document.

use std::{sync::Arc, time::Instant};

use crate::{
    Value,
    ast::{self, OperationKind},
    complexity::{self, StaticComplexity},
    error::{GraphQLError, Response},
    fragments::{FragmentIndex, Fragments},
    schema::Schema,
    types::ObjectType,
};

use super::{
    ExecutionContext, ExecutionOptions, coerce, executor,
    plan::{self, PreparedPlan},
    subscription::{EventHandler, subscribe_document},
};

/// A parsed document plus the index of the operation selected when it was prepared.
///
/// This is the dependent half of the self-referential cell in [`crate::prepared`]. It borrows the
/// source text owned by the cell's owner and is therefore never exposed outside the crate.
pub(crate) struct PreparedDocument<'a> {
    /// The parsed document, borrowing the owner's source text.
    pub(crate) document: ast::Document<'a>,
    /// Position of the selected operation among `document.definitions`.
    pub(crate) operation_index: usize,
    /// The errors normal validation would report for introspection fields when introspection is
    /// disabled, in discovery order. Empty when the document does not use `__schema` or `__type`.
    pub(crate) introspection_errors: Vec<GraphQLError>,
    /// A conservative upper bound on the selected operation's cost, depth and breadth, computed
    /// once because the document is fixed. `None` when no bound can be proven, in which case every
    /// request runs the exact analysis.
    pub(crate) static_complexity: Option<StaticComplexity>,
    /// The selected operation's variable definitions, compiled once. `None` when they could not be
    /// compiled, in which case the general per-request coercion path is used.
    pub(crate) variables: Option<coerce::CompiledVariables>,
    /// The precompiled field collection plan for the selected operation.
    pub(crate) plan: PreparedPlan<'a>,
    /// The document's fragment lookup, indexed once at preparation.
    ///
    /// Per-request and per-event execution pairs it with a borrow of the document instead of
    /// scanning the definitions again.
    pub(crate) fragment_index: FragmentIndex<'a>,
}

impl<'a> PreparedDocument<'a> {
    /// The operation selected during preparation.
    ///
    /// The index always points at an operation: it is produced by scanning for one during
    /// preparation. Returning an option keeps this type free of panics without exposing the
    /// internal invariant to the public API.
    pub(crate) fn operation(&self) -> Option<&ast::OperationDefinition<'a>> {
        match self.document.definitions.get(self.operation_index) {
            Some(ast::Definition::Operation(operation)) => Some(operation),
            _ => None,
        }
    }
}

/// Execute a prepared document through the normal execution tail.
pub(crate) async fn execute<'a>(
    schema: &'a Schema,
    prepared: &'a PreparedDocument<'a>,
    operation_name: Option<Arc<str>>,
    root_type: &'a ObjectType,
    request_variables: Option<&crate::Object>,
    options: &ExecutionOptions,
) -> Response {
    if !options.introspection && !prepared.introspection_errors.is_empty() {
        return introspection_rejection(&prepared.introspection_errors, options.max_errors);
    }
    let Some(operation) = prepared.operation() else {
        return Response::error(GraphQLError::new(
            "Internal error: the prepared query has no selected operation.",
        ));
    };
    executor::execute_prepared_operation(
        schema,
        &prepared.document,
        operation,
        operation_name,
        &prepared.plan,
        &prepared.fragment_index,
        root_type,
        prepared.static_complexity.as_ref(),
        prepared.variables.as_ref(),
        request_variables,
        options,
    )
    .await
}

/// Execute one subscription event against the prepared document.
pub(crate) async fn execute_event<'a>(
    context: &'a ExecutionContext,
    prepared: &'a PreparedDocument<'a>,
    event: Value,
    deadline: Option<Instant>,
) -> Response {
    let Some(operation) = prepared.operation() else {
        return Response::error(GraphQLError::new(
            "Internal error: the prepared query has no selected operation.",
        ));
    };
    let Some(root_type) = context.schema.subscription_type() else {
        return Response::error(GraphQLError::new(
            "Schema is not configured for subscriptions.",
        ));
    };
    let fragments = Fragments::prepared(&prepared.document, &prepared.fragment_index);
    executor::run_operation(
        context,
        fragments,
        Some(&prepared.plan),
        root_type,
        operation,
        event,
        deadline,
        true,
        true,
    )
    .await
}

/// An error produced while preparing a document.
pub(crate) enum BuildPreparedError {
    /// The source could not be parsed.
    Parse(GraphQLError),
    /// The document parsed but failed validation.
    Validation(Vec<GraphQLError>),
    /// The document is valid but has no usable selected operation.
    Operation(GraphQLError),
}

/// Prepare the document for execution against a schema.
///
/// Parsing, validation and operation selection happen here, once. The operation index and the
/// introspection compatibility errors are stored alongside the document so per-request execution
/// only has to borrow them.
#[cfg_attr(
    feature = "tracing",
    tracing::instrument(
        skip_all,
        level = "info",
        name = "gql.prepare",
        fields(source_bytes = source.len(), operation = operation_name.unwrap_or("<anonymous>"))
    )
)]
pub(crate) fn build<'a>(
    schema: &Schema,
    source: &'a str,
    operation_name: Option<&str>,
) -> Result<PreparedDocument<'a>, BuildPreparedError> {
    use crate::validation::{self, ValidationOptions};

    let document = match crate::parser::parse_query(source) {
        Ok(document) => document,
        Err(error) => return Err(BuildPreparedError::Parse(error)),
    };

    // Preparation is schema-time work, so it validates with introspection enabled. Whether a
    // particular execution may use introspection is an execution option; the exact error normal
    // validation would report is recorded here so a prepared query can reproduce it without
    // re-validating.
    let validation_errors = validation::validate(
        schema,
        &document,
        &ValidationOptions {
            introspection: true,
            max_depth: 0,
            max_errors: 100,
        },
    );
    if !validation_errors.is_empty() {
        return Err(BuildPreparedError::Validation(validation_errors));
    }

    let operation_index = match select_operation_index(&document, operation_name) {
        Ok(index) => index,
        Err(error) => return Err(BuildPreparedError::Operation(error)),
    };

    // The document's expansion cannot change between requests, so derive the conservative
    // complexity bound once and store it next to the document.
    let static_complexity = match document.definitions.get(operation_index) {
        Some(ast::Definition::Operation(operation)) => {
            complexity::static_bound(schema, &document, operation)
        }
        _ => None,
    };
    let variables = match document.definitions.get(operation_index) {
        Some(ast::Definition::Operation(operation)) => {
            coerce::CompiledVariables::compile(schema, operation).ok()
        }
        _ => None,
    };

    // The document is fixed, so the field collection it implies (fragment expansion, directive
    // conditions, merged selections and resolved schema fields) is computed once here. Anything
    // the plan cannot model exactly stays unplanned and execution falls back to dynamic
    // collection for it.
    let plan = match document.definitions.get(operation_index) {
        Some(ast::Definition::Operation(operation)) => match root_type(schema, operation.kind) {
            Ok(root) => plan::build(schema, &document, operation, &root),
            Err(_) => plan::build_empty(),
        },
        _ => plan::build_empty(),
    };

    let fragment_index = FragmentIndex::new(&document);

    let introspection_errors = if uses_introspection(&document) {
        // Normal validation reports every introspection field it finds (bounded by the request's
        // error limit). Storing all of them here lets a prepared request reproduce that exact
        // response instead of collapsing to a single error.
        validation::validate(
            schema,
            &document,
            &ValidationOptions {
                introspection: false,
                max_depth: 0,
                max_errors: MAX_STORED_INTROSPECTION_ERRORS,
            },
        )
    } else {
        Vec::new()
    };

    Ok(PreparedDocument {
        document,
        operation_index,
        introspection_errors,
        static_complexity,
        variables,
        plan,
        fragment_index,
    })
}

/// Upper bound on the introspection-disabled validation errors kept at preparation.
///
/// Validation itself stops at this count, and replay truncates to the request's own
/// [`ExecutionOptions::max_errors`], so a prepared response still matches normal execution.
const MAX_STORED_INTROSPECTION_ERRORS: usize = 100;

/// Build the response normal validation would produce when introspection is disabled.
fn introspection_rejection(errors: &[GraphQLError], max_errors: usize) -> Response {
    let limit = if max_errors == 0 {
        errors.len()
    } else {
        max_errors.min(errors.len())
    };
    Response {
        data: None,
        errors: errors[..limit].to_vec(),
        extensions: None,
    }
}

/// Select the operation and return its index in `document.definitions`.
fn select_operation_index(
    document: &ast::Document<'_>,
    operation_name: Option<&str>,
) -> Result<usize, GraphQLError> {
    let mut operations = document.definitions.iter().enumerate().filter_map(
        |(index, definition)| match definition {
            ast::Definition::Operation(operation) => Some((index, operation)),
            _ => None,
        },
    );

    let Some((first_index, first)) = operations.next() else {
        return Err(GraphQLError::new("Must provide an operation."));
    };

    match operation_name {
        Some(name) => {
            if first.name == Some(name) {
                return Ok(first_index);
            }
            operations
                .find(|(_, operation)| operation.name == Some(name))
                .map(|(index, _)| index)
                .ok_or_else(|| GraphQLError::new(format!("Unknown operation named \"{name}\".")))
        }
        None => {
            if operations.next().is_some() {
                Err(GraphQLError::new(
                    "Must provide an operation name if the document contains multiple operations.",
                ))
            } else {
                Ok(first_index)
            }
        }
    }
}

/// Whether a document uses `__schema` or `__type` anywhere.
///
/// `__typename` is allowed regardless of the introspection setting, so it is deliberately not
/// counted.
fn uses_introspection(document: &ast::Document<'_>) -> bool {
    fn selection_set_uses(selection_set: &ast::SelectionSet<'_>) -> bool {
        selection_set.items.iter().any(|selection| match selection {
            ast::Selection::Field(field) => {
                matches!(field.name, "__schema" | "__type")
                    || field.selection_set.as_ref().is_some_and(selection_set_uses)
            }
            ast::Selection::InlineFragment(fragment) => selection_set_uses(&fragment.selection_set),
            // Fragment spreads are checked where the fragment is defined.
            ast::Selection::FragmentSpread(_) => false,
        })
    }

    document
        .definitions
        .iter()
        .any(|definition| match definition {
            ast::Definition::Operation(operation) => selection_set_uses(&operation.selection_set),
            ast::Definition::Fragment(fragment) => selection_set_uses(&fragment.selection_set),
            ast::Definition::TypeSystem(_) => false,
        })
}

/// The root type an operation of `kind` executes against.
pub(crate) fn root_type(
    schema: &Schema,
    kind: OperationKind,
) -> Result<Arc<ObjectType>, GraphQLError> {
    match kind {
        OperationKind::Query => Ok(Arc::clone(schema.query_type())),
        OperationKind::Mutation => schema
            .mutation_name()
            .and_then(|name| schema.object_type(name.as_ref()))
            .cloned()
            .ok_or_else(|| GraphQLError::new("Schema is not configured for mutations.")),
        OperationKind::Subscription => schema
            .subscription_type()
            .cloned()
            .ok_or_else(|| GraphQLError::new("Schema is not configured for subscriptions.")),
    }
}

/// Precomputed metadata a prepared document can lend to the shared subscription setup.
pub(crate) struct PreparedExecution<'a> {
    /// The selected operation's name, interned once at preparation.
    pub(crate) operation_name: Option<Arc<str>>,
    /// The conservative limit bound computed at preparation.
    pub(crate) static_complexity: Option<&'a StaticComplexity>,
    /// The selected operation's compiled variable definitions.
    pub(crate) variables: Option<&'a coerce::CompiledVariables>,
    /// The precompiled field collection plan.
    pub(crate) plan: &'a PreparedPlan<'a>,
    /// The document's precomputed fragment lookup.
    pub(crate) fragments: Fragments<'a>,
}

/// Start a subscription from a prepared document.
#[allow(clippy::result_large_err)]
pub(crate) async fn subscribe<'a>(
    schema: &'a Schema,
    prepared: &'a PreparedDocument<'a>,
    operation_name: Option<Arc<str>>,
    request_variables: Option<&crate::Object>,
    options: &ExecutionOptions,
    make_event_handler: impl FnOnce(Arc<ExecutionContext>, Option<std::time::Duration>) -> EventHandler,
) -> Result<crate::SubscriptionResponse, Response> {
    if !options.introspection && !prepared.introspection_errors.is_empty() {
        return Err(introspection_rejection(
            &prepared.introspection_errors,
            options.max_errors,
        ));
    }
    let Some(operation) = prepared.operation() else {
        return Err(Response::error(GraphQLError::new(
            "Internal error: the prepared query has no selected operation.",
        )));
    };
    let execution = PreparedExecution {
        operation_name,
        static_complexity: prepared.static_complexity.as_ref(),
        variables: prepared.variables.as_ref(),
        plan: &prepared.plan,
        fragments: Fragments::prepared(&prepared.document, &prepared.fragment_index),
    };
    subscribe_document(
        schema,
        &prepared.document,
        operation,
        request_variables,
        options,
        Some(execution),
        make_event_handler,
    )
    .await
}