diff --git a/juniper/src/executor/mod.rs b/juniper/src/executor/mod.rs index f1574a264..a49c67bfc 100644 --- a/juniper/src/executor/mod.rs +++ b/juniper/src/executor/mod.rs @@ -30,7 +30,9 @@ use crate::{ model::{RootNode, SchemaType, TypeType}, }, types::{ - async_await::{GraphQLTypeAsync, GraphQLValueAsync}, + async_await::{ + GraphQLTypeAsync, GraphQLValueAsync, resolve_selection_set_into_async_serial, + }, base::{GraphQLType, GraphQLValue}, name::Name, subscriptions::{GraphQLSubscriptionType, GraphQLSubscriptionValue}, @@ -991,10 +993,16 @@ where .resolve_into_value_async(&root_node.query_info, &root_node) .await } + // The root selection set of a `mutation` operation is executed serially. + // See https://spec.graphql.org/September2025#sec-Normal-and-Serial-Execution OperationType::Mutation => { - executor - .resolve_into_value_async(&root_node.mutation_info, &root_node.mutation_type) - .await + resolve_selection_set_into_async_serial( + &root_node.mutation_type, + &root_node.mutation_info, + &operation.item.selection_set[..], + &executor, + ) + .await } OperationType::Subscription => unreachable!(), }; diff --git a/juniper/src/types/async_await.rs b/juniper/src/types/async_await.rs index 0ee41f951..9460b239a 100644 --- a/juniper/src/types/async_await.rs +++ b/juniper/src/types/async_await.rs @@ -3,7 +3,7 @@ use std::future; use auto_enums::enum_derive; use crate::{ - ast::Selection, + ast::{Field, Selection}, executor::{ExecutionResult, Executor}, parser::Spanning, value::{DefaultScalarValue, Object, ScalarValue, Value}, @@ -448,3 +448,213 @@ where Value::Object(object) } + +/// [Field] of a `mutation`'s root [selection set], collected for serial execution. +/// +/// [Field]: https://spec.graphql.org/September2025#sec-Language.Fields +/// [selection set]: https://spec.graphql.org/September2025#sec-Selection-Sets +struct CollectedField<'a, S> { + /// Collected [`Field`] itself, along with its position in the query. + field: &'a Spanning>, + + /// Type condition and [selection set] of the fragment this [`Field`] was collected from, if it + /// was collected from one. + /// + /// [selection set]: https://spec.graphql.org/September2025#sec-Selection-Sets + fragment: Option<(Option<&'a str>, &'a [Selection<'a, S>])>, +} + +/// Collects [fields] of the provided `selection_set` in the order they appear in the query, +/// flattening [fragments] into the same sequence. +/// +/// Only correct for the root [selection set] of a `mutation` operation, where the type is always an +/// [object] one, and so any type condition resolves back to the very same `instance`. +/// +/// [fields]: https://spec.graphql.org/September2025#sec-Language.Fields +/// [fragments]: https://spec.graphql.org/September2025#sec-Language.Fragments +/// [object]: https://spec.graphql.org/September2025#sec-Objects +/// [selection set]: https://spec.graphql.org/September2025#sec-Selection-Sets +fn collect_root_fields<'a, T, S>( + instance: &'a T, + info: &'a T::TypeInfo, + selection_set: &'a [Selection<'a, S>], + executor: &'a Executor<'a, 'a, T::Context, S>, + fragment: Option<(Option<&'a str>, &'a [Selection<'a, S>])>, + out: &mut Vec>, +) where + T: GraphQLValue + ?Sized, + S: ScalarValue, +{ + for selection in selection_set { + match *selection { + Selection::Field(ref f) => { + if is_excluded(&f.item.directives, executor.variables()) { + continue; + } + + out.push(CollectedField { field: f, fragment }); + } + + Selection::FragmentSpread(Spanning { + item: ref spread, .. + }) => { + if is_excluded(&spread.directives, executor.variables()) { + continue; + } + + let frag = executor + .fragment_by_name(spread.name.item) + .expect("Fragment could not be found"); + let concrete_type_name = instance.concrete_type_name(executor.context(), info); + + if executor + .schema() + .is_named_subtype(&concrete_type_name, frag.type_condition.item) + { + collect_root_fields( + instance, + info, + &frag.selection_set[..], + executor, + Some((Some(frag.type_condition.item), &frag.selection_set[..])), + out, + ); + } + } + + Selection::InlineFragment(Spanning { item: ref frag, .. }) => { + if is_excluded(&frag.directives, executor.variables()) { + continue; + } + + match &frag.type_condition { + Some(type_condition) => { + let concrete_type_name = + instance.concrete_type_name(executor.context(), info); + + if executor + .schema() + .is_named_subtype(&concrete_type_name, type_condition.item) + { + collect_root_fields( + instance, + info, + &frag.selection_set[..], + executor, + Some((Some(type_condition.item), &frag.selection_set[..])), + out, + ); + } + } + None => collect_root_fields( + instance, + info, + &frag.selection_set[..], + executor, + Some((None, &frag.selection_set[..])), + out, + ), + } + } + } + } +} + +/// Resolves the provided `selection_set` against the `instance` serially, as required for the root +/// [selection set] of a [mutation] operation. +/// +/// [mutation]: https://spec.graphql.org/September2025#sec-Mutation +/// [selection set]: https://spec.graphql.org/September2025#sec-Selection-Sets +pub(crate) async fn resolve_selection_set_into_async_serial<'a, T, S>( + instance: &'a T, + info: &'a T::TypeInfo, + selection_set: &'a [Selection<'a, S>], + executor: &'a Executor<'a, 'a, T::Context, S>, +) -> Value +where + T: GraphQLValueAsync + ?Sized, + T::TypeInfo: Sync, + T::Context: Sync, + S: ScalarValue + Send + Sync, +{ + let meta_type = executor + .schema() + .concrete_type_by_name( + instance + .type_name(info) + .expect("Resolving named type's selection set"), + ) + .expect("Type not found in schema"); + + let mut fields = Vec::with_capacity(selection_set.len()); + collect_root_fields(instance, info, selection_set, executor, None, &mut fields); + + let mut object = Object::with_capacity(fields.len()); + + for CollectedField { field, fragment } in fields { + let Spanning { item: f, span } = field; + + let response_name = f.alias.as_ref().unwrap_or(&f.name).item; + + if f.name.item == "__typename" { + object.add_field( + response_name, + Value::Scalar(instance.concrete_type_name(executor.context(), info).into()), + ); + continue; + } + + let meta_field = meta_type.field_by_name(f.name.item).unwrap_or_else(|| { + panic!( + "Field {} not found on type {:?}", + f.name.item, + meta_type.name(), + ) + }); + + let exec_vars = executor.variables(); + + // Fields collected through a fragment must be resolved against a sub-executor of that + // fragment, so that `Executor::look_ahead()` still finds them in its parent selection set. + let fragment_exec = fragment.map(|(ty, set)| executor.type_sub_executor(ty, Some(set))); + let parent_exec = fragment_exec.as_ref().unwrap_or(executor); + + let sub_exec = parent_exec.field_sub_executor( + response_name, + f.name.item, + span.start, + f.selection_set.as_ref().map(|v| &v[..]), + ); + let args = Arguments::new( + f.arguments.as_ref().map(|m| { + m.item + .iter() + .filter_map(|(k, v)| { + let val = v.item.clone().into_const(exec_vars)?; + Some((k.item, Spanning::new(v.span, val))) + }) + .collect() + }), + &meta_field.arguments, + ); + + match instance + .resolve_field_async(info, f.name.item, &args, &sub_exec) + .await + { + Ok(Value::Null) if meta_field.field_type.is_non_null() => return Value::null(), + Ok(v) => merge_key_into(&mut object, response_name, v), + Err(e) => { + sub_exec.push_error_at(e, span.start); + + if meta_field.field_type.is_non_null() { + return Value::null(); + } + + merge_key_into(&mut object, response_name, Value::null()); + } + } + } + + Value::Object(object) +} diff --git a/tests/integration/tests/mutation_fragment_ordering.rs b/tests/integration/tests/mutation_fragment_ordering.rs new file mode 100644 index 000000000..69ef18b20 --- /dev/null +++ b/tests/integration/tests/mutation_fragment_ordering.rs @@ -0,0 +1,209 @@ +//! Checks that root fields of a `mutation` operation execute in document order when +//! spread through fragments, per [§6.3.1] of the GraphQL spec. +//! See [#1398](https://github.com/graphql-rust/juniper/issues/1398) for details. +//! +//! [§6.3.1]: https://spec.graphql.org/September2025/#sec-Normal-and-Serial-Execution + +use std::sync::Mutex; + +use juniper::{ + EmptySubscription, Executor, RootNode, ScalarValue, execute, execute_sync, graphql_object, + graphql_vars, +}; + +#[derive(Default)] +pub struct Context { + resolved: Mutex>, +} + +impl juniper::Context for Context {} + +impl Context { + fn resolve(&self, field: &'static str) -> bool { + self.resolved.lock().unwrap().push(field); + true + } + + fn into_resolved(self) -> Vec<&'static str> { + self.resolved.into_inner().unwrap() + } +} + +pub struct Query; + +#[graphql_object(context = Context)] +impl Query { + fn some() -> bool { + true + } +} + +pub struct Mutation; + +#[graphql_object(context = Context)] +impl Mutation { + fn a(context: &Context) -> bool { + context.resolve("a") + } + + fn b(context: &Context) -> bool { + context.resolve("b") + } + + fn c<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> bool { + let lh = executor.look_ahead(); + + assert_eq!(lh.field_original_name(), "c"); + assert_eq!(lh.field_alias(), Some("aliased")); + + executor.context().resolve("c") + } +} + +type Schema = RootNode>; + +#[tokio::test] +async fn fragment_spread_executes_in_document_order() { + // language=GraphQL + let doc = r" + mutation { + a + ...F + } + + fragment F on Mutation { + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute_sync(doc, None, &schema, &graphql_vars! {}, &ctx).unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["a", "b"], "sync execution order"); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["a", "b"], "async execution order"); +} + +#[tokio::test] +async fn typed_inline_fragment_executes_in_document_order() { + // language=GraphQL + let doc = r" + mutation { + a + ... on Mutation { + b + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute_sync(doc, None, &schema, &graphql_vars! {}, &ctx).unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["a", "b"], "sync execution order"); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["a", "b"], "async execution order"); +} + +#[tokio::test] +async fn look_ahead_sees_field_inside_untyped_inline_fragment() { + // language=GraphQL + let doc = r" + mutation { + ... { + aliased: c + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute_sync(doc, None, &schema, &graphql_vars! {}, &ctx).unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "sync execution"); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "async execution"); +} + +#[tokio::test] +async fn look_ahead_sees_field_inside_typed_inline_fragment() { + // language=GraphQL + let doc = r" + mutation { + ... on Mutation { + aliased: c + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute_sync(doc, None, &schema, &graphql_vars! {}, &ctx).unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "sync execution"); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "async execution"); +} + +#[tokio::test] +async fn look_ahead_sees_field_spread_through_fragment() { + // language=GraphQL + let doc = r" + mutation { + ...F + } + + fragment F on Mutation { + aliased: c + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute_sync(doc, None, &schema, &graphql_vars! {}, &ctx).unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "sync execution"); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!(ctx.into_resolved(), ["c"], "async execution"); +} diff --git a/tests/integration/tests/serial_mutation_execution.rs b/tests/integration/tests/serial_mutation_execution.rs new file mode 100644 index 000000000..36afa6b9d --- /dev/null +++ b/tests/integration/tests/serial_mutation_execution.rs @@ -0,0 +1,413 @@ +//! Checks that the root selection set of a `mutation` operation executes serially, +//! per [§6.3.1] of the GraphQL spec. +//! See [#1398](https://github.com/graphql-rust/juniper/issues/1398) for details. +//! +//! [§6.3.1]: https://spec.graphql.org/September2025/#sec-Normal-and-Serial-Execution + +mod spec_example { + use std::sync::atomic::{AtomicI32, Ordering}; + + use juniper::{ + EmptySubscription, GraphQLObject, RootNode, execute, graphql_object, graphql_value, + graphql_vars, + }; + + #[derive(Default)] + pub struct Context { + number: AtomicI32, + } + + impl juniper::Context for Context {} + + #[derive(GraphQLObject)] + #[graphql(context = Context)] + pub struct NumberHolder { + the_number: i32, + } + + pub struct Query; + + #[graphql_object(context = Context)] + impl Query { + fn some() -> bool { + true + } + } + + pub struct Mutation; + + #[graphql_object(context = Context)] + impl Mutation { + async fn change_the_number(new_number: i32, context: &Context) -> NumberHolder { + context.number.store(new_number, Ordering::SeqCst); + // Without an actual suspension point the field futures complete on first poll, + // making concurrent execution indistinguishable from serial. + tokio::task::yield_now().await; + NumberHolder { + the_number: context.number.load(Ordering::SeqCst), + } + } + } + + type Schema = RootNode>; + + #[tokio::test] + async fn root_fields_execute_serially() { + // language=GraphQL + let doc = r" + mutation { + first: changeTheNumber(newNumber: 1) { theNumber } + second: changeTheNumber(newNumber: 3) { theNumber } + third: changeTheNumber(newNumber: 2) { theNumber } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + assert_eq!( + execute(doc, None, &schema, &graphql_vars! {}, &Context::default()).await, + Ok(( + graphql_value!({ + "first": {"theNumber": 1}, + "second": {"theNumber": 3}, + "third": {"theNumber": 2}, + }), + vec![], + )), + ); + } +} + +mod execution_order { + use std::sync::Mutex; + + use juniper::{ + EmptySubscription, RootNode, execute, graphql_object, graphql_value, graphql_vars, + }; + + #[derive(Default)] + pub struct Context { + log: Mutex>, + } + + impl juniper::Context for Context {} + + impl Context { + fn push(&self, entry: &'static str) { + self.log.lock().unwrap().push(entry); + } + + async fn resolve(&self, start: &'static str, end: &'static str) { + self.push(start); + tokio::task::yield_now().await; + self.push(end); + } + + fn into_log(self) -> Vec<&'static str> { + self.log.into_inner().unwrap() + } + } + + pub struct Query; + + #[graphql_object(context = Context)] + impl Query { + async fn a(context: &Context) -> bool { + context.resolve("a:start", "a:end").await; + true + } + + async fn b(context: &Context) -> bool { + context.resolve("b:start", "b:end").await; + true + } + } + + pub struct Nested; + + #[graphql_object(context = Context)] + impl Nested { + async fn x(context: &Context) -> bool { + context.resolve("x:start", "x:end").await; + true + } + + async fn y(context: &Context) -> bool { + context.resolve("y:start", "y:end").await; + true + } + } + + pub struct Mutation; + + #[graphql_object(context = Context)] + impl Mutation { + async fn a(context: &Context) -> bool { + context.resolve("a:start", "a:end").await; + true + } + + async fn b(context: &Context) -> bool { + context.resolve("b:start", "b:end").await; + true + } + + async fn failing(context: &Context) -> Result { + context.push("failing:start"); + tokio::task::yield_now().await; + Err("this field always errors") + } + + async fn nullable_failing(context: &Context) -> Result, &'static str> { + context + .resolve("nullableFailing:start", "nullableFailing:end") + .await; + Err("this field always errors") + } + + async fn nested() -> Nested { + Nested + } + } + + type Schema = RootNode>; + + #[tokio::test] + async fn non_null_root_field_failure_stops_later_fields() { + // language=GraphQL + let doc = r" + mutation { + a + failing + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (res, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(res, graphql_value!(null)); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].path(), ["failing"]); + + let log = ctx.into_log(); + + assert_eq!( + &log[..2], + ["a:start", "a:end"], + "root fields must execute serially, got {log:?}", + ); + assert!( + !log.iter().any(|entry| entry.starts_with("b:")), + "`b` must not start once `failing` errors, got {log:?}", + ); + } + + #[tokio::test] + async fn nullable_root_field_failure_does_not_stop_later_fields() { + // language=GraphQL + let doc = r" + mutation { + nullableFailing + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (res, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(res, graphql_value!({"nullableFailing": null, "b": true})); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].path(), ["nullableFailing"]); + + let log = ctx.into_log(); + + assert_eq!( + log, + [ + "nullableFailing:start", + "nullableFailing:end", + "b:start", + "b:end", + ], + "root fields must execute serially", + ); + } + + #[tokio::test] + async fn untyped_inline_fragment_executes_in_document_order() { + // language=GraphQL + let doc = r" + mutation { + a + ... { + b + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + assert_eq!( + ctx.into_log(), + ["a:start", "a:end", "b:start", "b:end"], + "root fields must execute serially", + ); + } + + #[tokio::test] + async fn skipped_root_field_is_not_resolved() { + // language=GraphQL + let doc = r" + mutation { + a @skip(if: true) + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (res, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(res, graphql_value!({"b": true})); + assert_eq!(errors.len(), 0); + assert_eq!( + ctx.into_log(), + ["b:start", "b:end"], + "a skipped root field must not resolve", + ); + } + + #[tokio::test] + async fn skipped_fragment_spread_is_not_resolved() { + // language=GraphQL + let doc = r" + mutation { + a + ...F @skip(if: true) + } + + fragment F on Mutation { + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (res, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(res, graphql_value!({"a": true})); + assert_eq!(errors.len(), 0); + assert_eq!( + ctx.into_log(), + ["a:start", "a:end"], + "a skipped fragment spread must not resolve", + ); + } + + #[tokio::test] + async fn skipped_inline_fragment_is_not_resolved() { + // language=GraphQL + let doc = r" + mutation { + a + ... on Mutation @skip(if: true) { + b + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (res, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(res, graphql_value!({"a": true})); + assert_eq!(errors.len(), 0); + assert_eq!( + ctx.into_log(), + ["a:start", "a:end"], + "a skipped inline fragment must not resolve", + ); + } + + #[tokio::test] + async fn nested_selections_resolve_concurrently() { + // language=GraphQL + let doc = r" + mutation { + nested { + x + y + } + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + + let log = ctx.into_log(); + + assert_eq!( + &log[..2], + ["x:start", "y:start"], + "sub-selections of a root `mutation` field must not be serialized, got {log:?}", + ); + } + + #[tokio::test] + async fn query_root_fields_resolve_concurrently() { + // language=GraphQL + let doc = r" + query { + a + b + } + "; + + let schema = Schema::new(Query, Mutation, EmptySubscription::new()); + + let ctx = Context::default(); + let (_, errors) = execute(doc, None, &schema, &graphql_vars! {}, &ctx) + .await + .unwrap(); + + assert_eq!(errors.len(), 0); + + let log = ctx.into_log(); + + assert_eq!( + &log[..2], + ["a:start", "b:start"], + "`query` root fields resolve concurrently, which §6.3.1 permits but does not require", + ); + } +}