apollo-compiler 2.0.0-beta.1

A compiler for the GraphQL query language.
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use crate::ast::Value;
use crate::collections::HashMap;
use crate::collections::HashSet;
use crate::collections::IndexMap;
use crate::executable::Field;
use crate::executable::Selection;
use crate::introspection::resolvers::SchemaMetaField;
use crate::parser::SourceMap;
use crate::parser::SourceSpan;
use crate::resolvers::input_coercion::coerce_argument_values;
use crate::resolvers::result_coercion::complete_value;
use crate::resolvers::ExecutionError;
use crate::resolvers::MaybeAsync;
use crate::resolvers::MaybeAsyncObject;
use crate::resolvers::MaybeAsyncResolved;
use crate::resolvers::ResolveInfo;
use crate::resolvers::ResolvedValue;
use crate::response::GraphQLError;
use crate::response::JsonMap;
use crate::response::JsonValue;
use crate::response::ResponseDataPathSegment;
use crate::schema::ExtendedType;
use crate::schema::FieldDefinition;
use crate::schema::Implementers;
use crate::schema::ObjectType;
use crate::schema::Type;
use crate::validation::operation::INCLUDE_DIRECTIVE_NAME;
use crate::validation::operation::SKIP_DIRECTIVE_NAME;
use crate::validation::SuspectedValidationBug;
use crate::validation::Valid;
use crate::ExecutableDocument;
use crate::Name;
use crate::Schema;
use std::sync::OnceLock;

/// <https://spec.graphql.org/September2025/#sec-Normal-and-Serial-Execution>
#[derive(Debug, Copy, Clone)]
pub(crate) enum ExecutionMode {
    /// Allowed to resolve fields in any order, including in parallel
    Normal,
    /// Top-level fields of a mutation operation must be executed in order
    Sequential,
}

/// Return in `Err` when an execution error occurred at some non-nullable place
///
/// <https://spec.graphql.org/September2025/#sec-Handling-Execution-Errors>
pub(crate) struct PropagateNull;

/// Linked-list version of `Vec<PathElement>`, taking advantage of the call stack
pub(crate) type LinkedPath<'a> = Option<&'a LinkedPathElement<'a>>;

pub(crate) struct LinkedPathElement<'a> {
    pub(crate) element: ResponseDataPathSegment,
    pub(crate) next: LinkedPath<'a>,
}

pub(crate) struct ExecutionContext<'a> {
    pub(crate) schema: &'a Valid<Schema>,
    pub(crate) document: &'a Valid<ExecutableDocument>,
    pub(crate) variable_values: &'a Valid<JsonMap>,
    pub(crate) errors: &'a mut Vec<GraphQLError>,
    pub(crate) implementers_map: MaybeLazy<'a, HashMap<Name, Implementers>>,
    pub(crate) enable_schema_introspection: bool,
}

pub(crate) enum MaybeLazy<'a, T> {
    Eager(&'a T),
    Lazy(&'a OnceLock<T>),
}

impl<'a, T> Clone for MaybeLazy<'a, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> Copy for MaybeLazy<'a, T> {}

/// <https://spec.graphql.org/September2025/#CollectFields()> followed by
/// <https://spec.graphql.org/September2025/#ExecuteCollectedFields()>
///
/// `object_value: None` is a special case for top-level of `introspection::partial_execute`
pub(crate) async fn execute_selection_set<'a>(
    ctx: &mut ExecutionContext<'a>,
    path: LinkedPath<'_>,
    mode: ExecutionMode,
    object_type: &ObjectType,
    object_value: MaybeAsyncObject<'_>,
    selections: impl IntoIterator<Item = &'a Selection>,
) -> Result<JsonMap, PropagateNull> {
    let mut grouped_field_set = IndexMap::default();
    collect_fields(
        ctx,
        path,
        object_type,
        selections,
        &mut HashSet::default(),
        &mut grouped_field_set,
    )?;

    match mode {
        ExecutionMode::Normal => {
            // If we want parallelism, use `StreamExt::buffer_unordered` (async)
            // or Rayon’s `par_iter` (sync) here.
        }
        ExecutionMode::Sequential => {}
    }

    let mut response_map = JsonMap::with_capacity(grouped_field_set.len());
    for (&response_name, fields) in &grouped_field_set {
        // Indexing should not panic: `collect_fields` only creates a `Vec` to push to it
        let field_name = &fields[0].name;
        let Ok(field_def) = ctx.schema.type_field(&object_type.name, field_name) else {
            // TODO: Return a `validation_bug`` execution error here?
            // The spec specifically has a “If fieldType is defined” condition,
            // but it being undefined would make the request invalid, right?
            continue;
        };
        let field_path = LinkedPathElement {
            element: ResponseDataPathSegment::Field(response_name.clone()),
            next: path,
        };
        if let Some(value) = execute_field(
            ctx,
            Some(&field_path),
            mode,
            object_type,
            object_value,
            field_def,
            fields,
        )
        .await?
        {
            response_map.insert(response_name.as_str(), value);
        }
    }
    Ok(response_map)
}

/// <https://spec.graphql.org/September2025/#CollectFields()>
///
/// Returns `Err` when the `if` argument of a `@skip` or `@include` directive
/// does not coerce to a Boolean, which is an execution error
/// for the selection set being collected.
fn collect_fields<'a>(
    ctx: &mut ExecutionContext<'a>,
    path: LinkedPath<'_>,
    object_type: &ObjectType,
    selections: impl IntoIterator<Item = &'a Selection>,
    visited_fragments: &mut HashSet<&'a Name>,
    grouped_fields: &mut IndexMap<&'a Name, Vec<&'a Field>>,
) -> Result<(), PropagateNull> {
    for selection in selections {
        match skipped_by_directives(selection, ctx.variable_values) {
            Ok(true) => continue,
            Ok(false) => {}
            Err(err) => {
                ctx.errors.push(GraphQLError::execution_error(
                    err.message,
                    path,
                    err.location,
                    &ctx.document.sources,
                ));
                return Err(PropagateNull);
            }
        }
        match selection {
            Selection::Field(field) => grouped_fields
                .entry(field.response_name())
                .or_default()
                .push(field.as_ref()),
            Selection::FragmentSpread(spread) => {
                let new = visited_fragments.insert(&spread.fragment_name);
                if !new {
                    continue;
                }
                let Some(fragment) = ctx.document.fragments.get(&spread.fragment_name) else {
                    continue;
                };
                if !does_fragment_type_apply(ctx.schema, object_type, fragment.type_condition()) {
                    continue;
                }
                collect_fields(
                    ctx,
                    path,
                    object_type,
                    &fragment.selection_set.selections,
                    visited_fragments,
                    grouped_fields,
                )?
            }
            Selection::InlineFragment(inline) => {
                if let Some(condition) = &inline.type_condition {
                    if !does_fragment_type_apply(ctx.schema, object_type, condition) {
                        continue;
                    }
                }
                collect_fields(
                    ctx,
                    path,
                    object_type,
                    &inline.selection_set.selections,
                    visited_fragments,
                    grouped_fields,
                )?
            }
        }
    }
    Ok(())
}

/// <https://spec.graphql.org/September2025/#DoesFragmentTypeApply()>
fn does_fragment_type_apply(
    schema: &Schema,
    object_type: &ObjectType,
    fragment_type: &Name,
) -> bool {
    match schema.types.get(fragment_type) {
        Some(ExtendedType::Object(_)) => *fragment_type == object_type.name,
        Some(ExtendedType::Interface(_)) => {
            object_type.implements_interfaces.contains(fragment_type)
        }
        Some(ExtendedType::Union(def)) => def.members.contains(&object_type.name),
        // Undefined or not an output type: validation should have caught this
        _ => false,
    }
}

/// An execution error raised while evaluating `@skip` or `@include`,
/// before its selection set is executed.
struct DirectiveError {
    message: String,
    location: Option<SourceSpan>,
}

/// Whether this selection is excluded by its `@skip` or `@include` directives.
///
/// <https://spec.graphql.org/September2025/#CollectFields()>
fn skipped_by_directives(
    selection: &Selection,
    variable_values: &Valid<JsonMap>,
) -> Result<bool, DirectiveError> {
    if eval_if_arg(selection, SKIP_DIRECTIVE_NAME, variable_values)? == Some(true) {
        return Ok(true);
    }
    Ok(eval_if_arg(selection, INCLUDE_DIRECTIVE_NAME, variable_values)? == Some(false))
}

/// Returns the value of the `if` argument of the given directive on this selection,
/// or `Ok(None)` if the directive is not present.
///
/// `if` is a non-null `Boolean!` argument, so a value that does not coerce
/// to a Boolean is an execution error. That includes a nullable variable
/// (valid there per the exception for variables with a non-null default value,
/// <https://spec.graphql.org/September2025/#sec-All-Variable-Usages-Are-Allowed>)
/// whose runtime value is null.
fn eval_if_arg(
    selection: &Selection,
    directive_name: &str,
    variable_values: &Valid<JsonMap>,
) -> Result<Option<bool>, DirectiveError> {
    let Some(directive) = selection.directives().get(directive_name) else {
        return Ok(None);
    };
    let Some(arg) = directive.specified_argument_by_name("if") else {
        // `if` is a required argument, so validation rejects its absence
        return Err(DirectiveError {
            message: format!(
                "missing value for required argument if of directive @{directive_name}"
            ),
            location: directive.location(),
        });
    };
    match arg.as_ref() {
        Value::Boolean(value) => Ok(Some(*value)),
        Value::Variable(var) => match variable_values.get(var.as_str()) {
            Some(JsonValue::Bool(value)) => Ok(Some(*value)),
            Some(JsonValue::Null) => Err(DirectiveError {
                message: format!(
                    "null value for non-null argument if of directive @{directive_name}"
                ),
                location: arg.location(),
            }),
            None => Err(DirectiveError {
                message: format!(
                    "missing variable for non-null argument if of directive @{directive_name}"
                ),
                location: arg.location(),
            }),
            // Validation restricts variables used here to Boolean types
            Some(_) => Err(DirectiveError {
                message: format!(
                    "non-boolean value for argument if of directive @{directive_name}"
                ),
                location: arg.location(),
            }),
        },
        // Validation restricts literals used here to Boolean values
        _ => Err(DirectiveError {
            message: format!("non-boolean value for argument if of directive @{directive_name}"),
            location: arg.location(),
        }),
    }
}

/// <https://spec.graphql.org/September2025/#ExecuteField()>
///
/// `object_value: None` is a special case for top-level of `introspection::partial_execute`
///
/// Return `Ok(None)` for silently skipping that field.
async fn execute_field<'a>(
    ctx: &mut ExecutionContext<'a>,
    path: LinkedPath<'_>,
    mode: ExecutionMode,
    object_type: &ObjectType,
    object_value: MaybeAsyncObject<'_>,
    field_def: &FieldDefinition,
    fields: &[&'a Field],
) -> Result<Option<JsonValue>, PropagateNull> {
    let field = fields[0];
    let argument_values = match coerce_argument_values(ctx, path, field_def, field) {
        Ok(argument_values) => argument_values,
        Err(PropagateNull) if field_def.ty.is_non_null() => return Err(PropagateNull),
        Err(PropagateNull) => return Ok(Some(JsonValue::Null)),
    };
    let is_field_of_root_query = || {
        ctx.schema
            .schema_definition
            .query
            .as_ref()
            .is_some_and(|q| **q == object_type.name)
    };
    let info = ResolveInfo {
        schema: ctx.schema,
        implementers_map: ctx.implementers_map,
        document: ctx.document,
        fields,
        arguments: &argument_values,
    };
    let resolved_result = match field.name.as_str() {
        "__typename" => Ok(MaybeAsync::Sync(ResolvedValue::leaf(
            object_type.name.as_str(),
        ))),
        "__schema" if is_field_of_root_query() => resolve_schema_meta_field(ctx),
        "__type" if is_field_of_root_query() => resolve_type_meta_field(ctx, &info),
        _ => match object_value {
            MaybeAsync::Async(obj) => obj.resolve_field(&info).await.map(MaybeAsync::Async),
            MaybeAsync::Sync(obj) => obj.resolve_field(&info).map(MaybeAsync::Sync),
        },
    };
    let completed_result = match resolved_result {
        Ok(resolved) => complete_value(ctx, path, mode, field.ty(), resolved, fields).await,
        Err(ExecutionError { message }) => {
            ctx.errors.push(GraphQLError::execution_error(
                format!("resolver error: {message}"),
                path,
                field.name.location(),
                &ctx.document.sources,
            ));
            Err(PropagateNull)
        }
    };
    try_nullify(&field_def.ty, completed_result)
}

fn resolve_schema_meta_field<'a>(
    ctx: &ExecutionContext<'a>,
) -> Result<MaybeAsyncResolved<'a>, ExecutionError> {
    check_schema_introspection_enabled(ctx)?;
    Ok(MaybeAsync::Sync(ResolvedValue::object(SchemaMetaField)))
}

fn resolve_type_meta_field<'a>(
    ctx: &ExecutionContext<'a>,
    info: &'a ResolveInfo<'a>,
) -> Result<MaybeAsyncResolved<'a>, ExecutionError> {
    check_schema_introspection_enabled(ctx)?;
    if let Some(name) = info.arguments().get("name").and_then(|v| v.as_str()) {
        Ok(MaybeAsync::Sync(crate::introspection::resolvers::type_def(
            info, name,
        )))
    } else {
        // This should never happen: `coerce_argument_values()` returns a map that conforms
        // to the `__type(name: String!): __Type` definition
        // Still, in case of a bug prefer returning an error than panicking
        Err(ExecutionError {
            message: "expected string argument `name`".into(),
        })
    }
}

fn check_schema_introspection_enabled<'a>(
    ctx: &ExecutionContext<'a>,
) -> Result<(), ExecutionError> {
    if ctx.enable_schema_introspection {
        Ok(())
    } else {
        // Disabled by default in the `apollo_compiler::resolvers::Excecution` builder,
        // use `.enable_schema_introspection(true)` to enable
        Err(ExecutionError {
            message: "schema introspection is disabled".into(),
        })
    }
}

/// Try to insert a propagated null if possible, or keep propagating it.
///
/// <https://spec.graphql.org/September2025/#sec-Handling-Execution-Errors>
pub(crate) fn try_nullify(
    ty: &Type,
    result: Result<Option<JsonValue>, PropagateNull>,
) -> Result<Option<JsonValue>, PropagateNull> {
    match result {
        Ok(json) => Ok(json),
        Err(PropagateNull) => {
            if ty.is_non_null() {
                Err(PropagateNull)
            } else {
                Ok(Some(JsonValue::Null))
            }
        }
    }
}

pub(crate) fn path_to_vec(mut link: LinkedPath<'_>) -> Vec<ResponseDataPathSegment> {
    let mut path = Vec::new();
    while let Some(node) = link {
        path.push(node.element.clone());
        link = node.next;
    }
    path.reverse();
    path
}

impl GraphQLError {
    pub(crate) fn execution_error(
        message: impl Into<String>,
        path: LinkedPath<'_>,
        location: Option<SourceSpan>,
        sources: &SourceMap,
    ) -> Self {
        let mut err = Self::new(message, location, sources);
        err.path = path_to_vec(path);
        err
    }
}

impl SuspectedValidationBug {
    pub(crate) fn into_execution_error(
        self,
        sources: &SourceMap,
        path: LinkedPath<'_>,
    ) -> GraphQLError {
        let Self { message, location } = self;
        let mut err = GraphQLError::execution_error(message, path, location, sources);
        err.extensions
            .insert("APOLLO_SUSPECTED_VALIDATION_BUG", true.into());
        err
    }
}