From 186e643f15c822dbaeea30d11b4afdea5b7f297c Mon Sep 17 00:00:00 2001 From: Andreas Marek Date: Fri, 6 Nov 2026 19:59:11 +1000 Subject: [PATCH] Coerce conditional directive arguments and preserve execution error context --- .../java/graphql/execution/Execution.java | 15 +- .../graphql/execution/ExecutionStrategy.java | 21 + .../SubscriptionExecutionStrategy.java | 17 +- ...ConditionalDirectiveCoercionException.java | 26 ++ .../conditional/ConditionalNodes.java | 56 ++- .../incremental/DeferredFragmentCall.java | 4 +- .../ConditionalDirectiveCoercionTest.groovy | 400 ++++++++++++++++++ 7 files changed, 507 insertions(+), 32 deletions(-) create mode 100644 src/main/java/graphql/execution/conditional/ConditionalDirectiveCoercionException.java create mode 100644 src/test/groovy/graphql/execution/ConditionalDirectiveCoercionTest.groovy diff --git a/src/main/java/graphql/execution/Execution.java b/src/main/java/graphql/execution/Execution.java index df7a0f6aeb..dc983c5041 100644 --- a/src/main/java/graphql/execution/Execution.java +++ b/src/main/java/graphql/execution/Execution.java @@ -14,6 +14,7 @@ import graphql.GraphQLException; import graphql.Internal; import graphql.Profiler; +import graphql.execution.conditional.ConditionalDirectiveCoercionException; import graphql.execution.directives.OperationDirectivesResolver; import graphql.execution.directives.QueryAppliedDirective; import graphql.execution.incremental.IncrementalCallState; @@ -212,11 +213,15 @@ private CompletableFuture executeOperation(ExecutionContext exe .graphQLContext(graphQLContext) .build(); - MergedSelectionSet fields = fieldCollector.collectFields( - collectorParameters, - operationDefinition.getSelectionSet(), - executionContext.hasIncrementalSupport() - ); + MergedSelectionSet fields; + try { + fields = fieldCollector.collectFields(collectorParameters, operationDefinition.getSelectionSet(), executionContext.hasIncrementalSupport()); + } catch (ConditionalDirectiveCoercionException exception) { + ExecutionResult errorResult = new ExecutionResultImpl(null, Collections.singletonList(exception)); + executeOperationCtx.onDispatched(); + executeOperationCtx.onCompleted(errorResult, exception); + return completedFuture(errorResult); + } ResultPath path = ResultPath.rootPath(); ExecutionStepInfo executionStepInfo = newExecutionStepInfo().type(operationRootType).path(path).build(); diff --git a/src/main/java/graphql/execution/ExecutionStrategy.java b/src/main/java/graphql/execution/ExecutionStrategy.java index 9402c65c8f..864d240dd6 100644 --- a/src/main/java/graphql/execution/ExecutionStrategy.java +++ b/src/main/java/graphql/execution/ExecutionStrategy.java @@ -6,12 +6,14 @@ import graphql.ExecutionResult; import graphql.ExecutionResultImpl; import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; import graphql.Internal; import graphql.PublicSpi; import graphql.SerializationError; import graphql.TrivialDataFetcher; import graphql.TypeMismatchError; import graphql.UnresolvedTypeError; +import graphql.execution.conditional.ConditionalDirectiveCoercionException; import graphql.execution.directives.QueryDirectives; import graphql.execution.directives.QueryDirectivesImpl; import graphql.execution.incremental.AlternativeCallContext; @@ -800,6 +802,8 @@ protected FieldValueInfo completeValue(ExecutionContext executionContext, Execut try { resolvedObjectType = resolveType(executionContext, parameters, fieldType); fieldValue = completeValueForObject(executionContext, parameters, resolvedObjectType, result); + } catch (ConditionalDirectiveCoercionException ex) { + return completeConditionalDirectiveError(executionContext, parameters, ex); } catch (UnresolvedTypeException ex) { // consider the result to be null and add the error on the context handleUnresolvedTypeProblem(executionContext, parameters, ex); @@ -809,6 +813,23 @@ protected FieldValueInfo completeValue(ExecutionContext executionContext, Execut return new FieldValueInfo(OBJECT, fieldValue); } + private FieldValueInfo completeConditionalDirectiveError(ExecutionContext context, ExecutionStrategyParameters parameters, ConditionalDirectiveCoercionException exception) { + GraphQLError error = GraphqlErrorBuilder.newError() + .message("%s", exception.getMessage()) + .locations(exception.getLocations()) + .path(parameters.getPath()) + .errorType(exception.getErrorType()) + .build(); + addErrorToRightContext(error, parameters, context); + // The coercion error is already recorded, including in subscription and deferred contexts. + // Propagate null without reporting a second error for the same response position. + if (parameters.getExecutionStepInfo().isNonNullType() && context.propagateErrorsOnNonNullContractFailure()) { + return new FieldValueInfo(NULL, exceptionallyCompletedFuture( + new NonNullableFieldWasNullException(parameters.getExecutionStepInfo(), parameters.getPath()))); + } + return new FieldValueInfo(NULL, null); + } + private void handleUnresolvedTypeProblem(ExecutionContext context, ExecutionStrategyParameters parameters, UnresolvedTypeException e) { UnresolvedTypeError error = new UnresolvedTypeError(parameters.getPath(), parameters.getExecutionStepInfo(), e); diff --git a/src/main/java/graphql/execution/SubscriptionExecutionStrategy.java b/src/main/java/graphql/execution/SubscriptionExecutionStrategy.java index b0b049ecd2..6380e3a761 100644 --- a/src/main/java/graphql/execution/SubscriptionExecutionStrategy.java +++ b/src/main/java/graphql/execution/SubscriptionExecutionStrategy.java @@ -24,6 +24,7 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.Flow; import java.util.function.Function; @@ -191,8 +192,7 @@ private CompletableFuture executeSubscriptionEvent(ExecutionCon executionContext.getDataLoaderDispatcherStrategy().subscriptionEventCompletionDone(alternativeCallContext); CompletableFuture overallResult = fieldValueInfo .getFieldValueFuture() - .thenApply(val -> new ExecutionResultImpl(val, alternativeCallContext.getErrors(), eventExtensions)) - .thenApply(executionResult -> wrapWithRootFieldName(newParameters, executionResult)) + .handle((value, throwable) -> completeSubscriptionEvent(newParameters, alternativeCallContext, eventExtensions, value, throwable)) .whenComplete((executionResult, throwable) -> { executionContext.getDataLoaderDispatcherStrategy().subscriptionEventExecutionDone(alternativeCallContext); }); @@ -209,6 +209,19 @@ private CompletableFuture executeSubscriptionEvent(ExecutionCon return overallResult; } + private ExecutionResult completeSubscriptionEvent(ExecutionStrategyParameters parameters, AlternativeCallContext alternativeCallContext, + @Nullable Map extensions, @Nullable Object value, @Nullable Throwable throwable) { + if (throwable == null) { + return wrapWithRootFieldName(parameters, new ExecutionResultImpl(value, alternativeCallContext.getErrors(), extensions)); + } + Throwable cause = throwable instanceof CompletionException ? throwable.getCause() : throwable; + if (cause instanceof NonNullableFieldWasNullException) { + // A non-null root field makes this event's data null; subsequent source events can still execute. + return new ExecutionResultImpl(null, alternativeCallContext.getErrors(), extensions); + } + throw new CompletionException(cause); + } + private ExecutionResult wrapWithRootFieldName(ExecutionStrategyParameters parameters, ExecutionResult executionResult) { String rootFieldName = getRootFieldName(parameters); return new ExecutionResultImpl( diff --git a/src/main/java/graphql/execution/conditional/ConditionalDirectiveCoercionException.java b/src/main/java/graphql/execution/conditional/ConditionalDirectiveCoercionException.java new file mode 100644 index 0000000000..3c1f97ea84 --- /dev/null +++ b/src/main/java/graphql/execution/conditional/ConditionalDirectiveCoercionException.java @@ -0,0 +1,26 @@ +package graphql.execution.conditional; + +import graphql.GraphqlErrorException; +import graphql.Internal; +import graphql.language.Argument; +import graphql.language.Directive; +import graphql.language.SourceLocation; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +@Internal +@NullMarked +public class ConditionalDirectiveCoercionException extends GraphqlErrorException { + + public ConditionalDirectiveCoercionException(Directive directive, RuntimeException cause) { + super(GraphqlErrorException.newErrorException() + .message("Invalid argument for directive '@" + directive.getName() + "': " + cause.getMessage()) + .sourceLocation(argumentLocation(directive)) + .cause(cause)); + } + + private static @Nullable SourceLocation argumentLocation(Directive directive) { + Argument argument = directive.getArgument("if"); + return argument != null ? argument.getValue().getSourceLocation() : directive.getSourceLocation(); + } +} diff --git a/src/main/java/graphql/execution/conditional/ConditionalNodes.java b/src/main/java/graphql/execution/conditional/ConditionalNodes.java index e922eeb427..4abf469a82 100644 --- a/src/main/java/graphql/execution/conditional/ConditionalNodes.java +++ b/src/main/java/graphql/execution/conditional/ConditionalNodes.java @@ -2,18 +2,22 @@ import graphql.Assert; import graphql.GraphQLContext; +import graphql.GraphQLError; import graphql.Internal; import graphql.execution.CoercedVariables; +import graphql.execution.ValuesResolver; import graphql.language.Argument; import graphql.language.BooleanValue; import graphql.language.Directive; import graphql.language.DirectivesContainer; import graphql.language.NodeUtil; import graphql.language.VariableReference; +import graphql.schema.GraphQLDirective; import graphql.schema.GraphQLSchema; import org.jspecify.annotations.Nullable; import java.util.List; +import java.util.Locale; import java.util.Map; import static graphql.Directives.IncludeDirective; @@ -26,7 +30,7 @@ public class ConditionalNodes { * return null if skip/include argument contains a variable and therefore could not be resolved */ public Boolean shouldIncludeWithoutVariables(DirectivesContainer element) { - return shouldInclude(null, element.getDirectives()); + return shouldInclude(null, element.getDirectives(), null); } public boolean shouldInclude(DirectivesContainer element, @@ -36,7 +40,7 @@ public boolean shouldInclude(DirectivesContainer element, ) { // // call the base @include / @skip first - if (!shouldInclude(variables, element.getDirectives())) { + if (!shouldInclude(variables, element.getDirectives(), graphQLContext)) { return false; } // @@ -83,12 +87,12 @@ public GraphQLContext getGraphQLContext() { } - private @Nullable Boolean shouldInclude(Map variables, List directives) { + private @Nullable Boolean shouldInclude(@Nullable Map variables, List directives, @Nullable GraphQLContext graphQLContext) { // shortcut on no directives if (directives.isEmpty()) { return true; } - Boolean skip = getDirectiveResult(variables, directives, SkipDirective.getName(), false); + Boolean skip = getDirectiveResult(variables, directives, SkipDirective, false, graphQLContext); if (skip == null) { return null; } @@ -96,7 +100,7 @@ public GraphQLContext getGraphQLContext() { return false; } - return getDirectiveResult(variables, directives, IncludeDirective.getName(), true); + return getDirectiveResult(variables, directives, IncludeDirective, true, graphQLContext); } public boolean containsSkipOrIncludeDirective(DirectivesContainer directivesContainer) { @@ -130,27 +134,33 @@ public String getIncludeVariableName(DirectivesContainer directivesContainer) } - private @Nullable Boolean getDirectiveResult(Map variables, List directives, String directiveName, boolean defaultValue) { - Directive foundDirective = NodeUtil.findNodeByName(directives, directiveName); - if (foundDirective != null) { - return getIfValue(foundDirective.getArguments(), variables); + private @Nullable Boolean getDirectiveResult(@Nullable Map variables, List directives, GraphQLDirective definition, boolean defaultValue, @Nullable GraphQLContext graphQLContext) { + Directive directive = NodeUtil.findNodeByName(directives, definition.getName()); + if (directive == null) { + return defaultValue; + } + if (variables == null) { + return getIfValueWithoutVariables(directive); + } + try { + Map argumentValues = ValuesResolver.getArgumentValues( + definition.getArguments(), directive.getArguments(), CoercedVariables.of(variables), + graphQLContext != null ? graphQLContext : GraphQLContext.getDefault(), Locale.getDefault()); + return (Boolean) argumentValues.get("if"); + } catch (RuntimeException exception) { + if (!(exception instanceof GraphQLError)) { + throw exception; + } + throw new ConditionalDirectiveCoercionException(directive, exception); } - return defaultValue; } - private @Nullable Boolean getIfValue(List arguments, @Nullable Map variables) { - for (Argument argument : arguments) { - if (argument.getName().equals("if")) { - Object value = argument.getValue(); - if (value instanceof BooleanValue) { - return ((BooleanValue) value).isValue(); - } - if (value instanceof VariableReference && variables != null) { - return (boolean) variables.get(((VariableReference) value).getName()); - } - return null; - } + private @Nullable Boolean getIfValueWithoutVariables(Directive directive) { + Argument argument = directive.getArgument("if"); + Assert.assertNotNull(argument, "The 'if' argument must be present"); + if (argument.getValue() instanceof BooleanValue) { + return ((BooleanValue) argument.getValue()).isValue(); } - return Assert.assertShouldNeverHappen("The 'if' argument must be present"); + return null; } } diff --git a/src/main/java/graphql/execution/incremental/DeferredFragmentCall.java b/src/main/java/graphql/execution/incremental/DeferredFragmentCall.java index 79f4c9b78d..63476ecc3b 100644 --- a/src/main/java/graphql/execution/incremental/DeferredFragmentCall.java +++ b/src/main/java/graphql/execution/incremental/DeferredFragmentCall.java @@ -84,9 +84,9 @@ private DeferPayload handleNonNullableFieldError(DeferPayload result, Throwable if (throwable != null) { Throwable cause = throwable.getCause(); if (cause instanceof NonNullableFieldWasNullException) { - GraphQLError error = new NonNullableFieldWasNullError((NonNullableFieldWasNullException) cause); + List errors = alternativeCallContext.getErrors(); return DeferPayload.newDeferredItem() - .errors(Collections.singletonList(error)) + .errors(errors.isEmpty() ? Collections.singletonList(new NonNullableFieldWasNullError((NonNullableFieldWasNullException) cause)) : errors) .label(label) .path(path) .build(); diff --git a/src/test/groovy/graphql/execution/ConditionalDirectiveCoercionTest.groovy b/src/test/groovy/graphql/execution/ConditionalDirectiveCoercionTest.groovy new file mode 100644 index 0000000000..9532731289 --- /dev/null +++ b/src/test/groovy/graphql/execution/ConditionalDirectiveCoercionTest.groovy @@ -0,0 +1,400 @@ +package graphql.execution + +import graphql.Directives +import graphql.ErrorType +import graphql.ExecutionInput +import graphql.ExecutionResult +import graphql.GraphQL +import graphql.TestUtil +import graphql.execution.conditional.ConditionalDirectiveCoercionException +import graphql.execution.conditional.ConditionalNodes +import graphql.execution.instrumentation.InstrumentationContext +import graphql.execution.instrumentation.SimplePerformantInstrumentation +import graphql.execution.pubsub.CapturingSubscriber +import graphql.incremental.IncrementalExecutionResult +import graphql.language.Field +import graphql.language.SourceLocation +import graphql.normalized.ExecutableNormalizedOperationFactory +import graphql.parser.Parser +import graphql.schema.DataFetcher +import graphql.schema.idl.RuntimeWiring +import org.awaitility.Awaitility +import org.dataloader.BatchLoader +import org.dataloader.DataLoaderFactory +import org.dataloader.DataLoaderRegistry +import reactor.core.publisher.Flux +import spock.lang.Specification + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit + +import static graphql.ExperimentalApi.ENABLE_INCREMENTAL_SUPPORT +import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring +import static graphql.execution.instrumentation.dataloader.DataLoaderDispatchingContextKeys.ENABLE_DATA_LOADER_CHAINING +import static graphql.execution.instrumentation.dataloader.DataLoaderDispatchingContextKeys.ENABLE_DATA_LOADER_EXHAUSTED_DISPATCHING + +class ConditionalDirectiveCoercionTest extends Specification { + + def "root #operation collection rejects null #directive on #selection before fetching"() { + given: + int calls = 0 + DataFetcher fetcher = { calls++; 'unexpected' } + def graphQL = TestUtil.graphQL('type Query { value: String } type Mutation { value: String }', + [Query: [value: fetcher], Mutation: [value: fetcher]]).build() + def condition = '@' + directive + '(if: $flag)' + def query = operation + '($flag: Boolean = true) { ' + selection.replace('@CONDITION', condition) + ' }' + if (selection.contains('...Fields')) { + query += ' fragment Fields on ' + (operation == 'query' ? 'Query' : 'Mutation') + ' { value }' + } + + when: + def result = execute(graphQL, query) + + then: + calls == 0 + result.dataPresent + result.data == null + assertError(result, query, null) + + where: + [operation, directive, selection] << [ + ['query', 'mutation'], ['skip', 'include'], + ['value @CONDITION', '... @CONDITION { value }', '...Fields @CONDITION'] + ].combinations() + } + + def "nested #directive errors respect #parentType with async=#async"() { + given: + int children = 0 + DataFetcher parent = { async ? CompletableFuture.supplyAsync { [child: 'value'] } : [child: 'value'] } + def graphQL = TestUtil.graphQL('type Query { good: String parent: ' + parentType + ' } type Parent { child: String }', + [Query: [good: { 'good' } as DataFetcher, parent: parent], + Parent: [child: { children++; 'unexpected' } as DataFetcher]]).build() + def query = 'query($flag: Boolean = true) { good alias: parent { child @' + directive + '(if: $flag) } }' + + when: + def result = execute(graphQL, query) + + then: + children == 0 + result.dataPresent + result.data == (parentType == 'Parent!' ? null : [good: 'good', alias: null]) + assertError(result, query, ['alias']) + + where: + [directive, parentType, async] << [['skip', 'include'], ['Parent', 'Parent!'], [false, true]].combinations() + } + + def "nested fragments report the enclosing response path for #selection"() { + given: + def graphQL = TestUtil.graphQL('type Query { parent: Parent } type Parent { child: String }').build() + def query = 'query($flag: Boolean = true) { alias: parent { ' + selection + ' } } fragment Fields on Parent { child }' + + when: + def result = execute(graphQL, query, [parent: [child: 'value']]) + + then: + result.data == [alias: null] + assertError(result, query, ['alias']) + + where: + selection << ['...Fields @skip(if: $flag)', '... on Parent @include(if: $flag) { ...Fields }'] + } + + def "list item failures propagate through #listType"() { + given: + def graphQL = TestUtil.graphQL('type Query { good: String parents: ' + listType + ' } type Parent { child: String }').build() + def query = 'query($flag: Boolean = true) { good alias: parents { child @include(if: $flag) } }' + + when: + def result = execute(graphQL, query, [good: 'good', parents: [[child: 'value']]]) + + then: + result.data == expected + assertError(result, query, ['alias', 0]) + + where: + listType | expected + '[Parent]' | [good: 'good', alias: [null]] + '[Parent]!' | [good: 'good', alias: [null]] + '[Parent!]' | [good: 'good', alias: null] + '[Parent!]!' | null + } + + def "mutation preserves completed siblings and only continues past a nullable failure with #parentType"() { + given: + def calls = [] + def graphQL = TestUtil.graphQL('type Query { unused: String } type Mutation { before: String parent: ' + parentType + ' after: String } type Parent { child: String }', + [Mutation: [before: { calls << 'before'; 'before' } as DataFetcher, + parent: { calls << 'parent'; [child: 'value'] } as DataFetcher, + after: { calls << 'after'; 'after' } as DataFetcher]]).build() + def query = 'mutation($flag: Boolean = true) { before alias: parent { child @skip(if: $flag) } after }' + + when: + def result = execute(graphQL, query) + + then: + calls == expectedCalls + result.data == expectedData + assertError(result, query, ['alias']) + + where: + parentType | expectedCalls | expectedData + 'Parent' | ['before', 'parent', 'after'] | [before: 'before', alias: null, after: 'after'] + 'Parent!' | ['before', 'parent'] | null + } + + def "subscription #directive failures produce an error result for each #parentType event"() { + given: + def events = [1, 2].collect { DataFetcherResult.newResult().data([child: 'value']).extensions([event: it]).build() } + DataFetcher source = { Flux.fromIterable(events) } + def graphQL = TestUtil.graphQL('type Query { unused: String } type Subscription { event: ' + parentType + ' } type Parent { child: String }', + [Subscription: [event: source]]).build() + def query = 'subscription($flag: Boolean = true) { alias: event { child @' + directive + '(if: $flag) } }' + def initial = execute(graphQL, query) + def subscriber = new CapturingSubscriber() + + when: + initial.data.subscribe(subscriber) + Awaitility.await().atMost(10, TimeUnit.SECONDS).untilTrue(subscriber.isDone()) + + then: + initial.errors.empty + subscriber.throwable == null + subscriber.events.size() == 2 + subscriber.events.each { result -> + assert result.dataPresent + assert result.data == (parentType == 'Parent!' ? null : [alias: null]) + assertError(result, query, ['alias']) + } + subscriber.events*.extensions*.event.sort() == [1, 2] + + where: + [directive, parentType] << [['skip', 'include'], ['Parent', 'Parent!']].combinations() + } + + def "unexpected subscription completion failures still terminate the stream"() { + given: + def failure = new IllegalStateException('Unexpected type resolver failure') + def wiring = RuntimeWiring.newRuntimeWiring() + .type(newTypeWiring('Subscription').dataFetcher('event', { Flux.just([:]) })) + .type(newTypeWiring('Parent').dataFetcher('node', { CompletableFuture.completedFuture([id: '1']) })) + .type(newTypeWiring('Node').typeResolver { throw failure }) + def graphQL = TestUtil.graphQL('''type Query { unused: String } + type Subscription { event: Parent } + type Parent { node: Node } + interface Node { id: ID } + type Child implements Node { id: ID } + ''', wiring).build() + def initial = graphQL.execute('subscription { event { node { id } } }') + def subscriber = new CapturingSubscriber() + + when: + initial.data.subscribe(subscriber) + Awaitility.await().atMost(10, TimeUnit.SECONDS).untilTrue(subscriber.isDone()) + + then: + subscriber.events.empty + subscriber.throwable != null + subscriber.throwable.cause.is(failure) + } + + def "deferred #parentType failure retains the directive error location"() { + given: + def graphQL = TestUtil.graphQL('type Query { good: String parent: ' + parentType + ' } type Parent { child: String }').build() + def query = 'query($flag: Boolean = true) { good ... @defer { alias: parent { child @skip(if: $flag) } } }' + def input = ExecutionInput.newExecutionInput(query).variables([flag: null]) + .root([good: 'good', parent: [child: 'value']]).graphQLContext([(ENABLE_INCREMENTAL_SUPPORT): true]).build() + + when: + IncrementalExecutionResult result = graphQL.execute(input) + def subscriber = new CapturingSubscriber() + result.incrementalItemPublisher.subscribe(subscriber) + Awaitility.await().atMost(10, TimeUnit.SECONDS).untilTrue(subscriber.isDone()) + def patches = subscriber.events.collectMany { it.toSpecification().incremental ?: [] } + + then: + result.data == [good: 'good'] + result.errors.empty + subscriber.throwable == null + patches.size() == 1 + patches[0].data == (parentType == 'Parent!' ? null : [alias: null]) + patches[0].errors.size() == 1 + patches[0].errors[0].message.contains("Invalid argument for directive '@skip'") + patches[0].errors[0].path == ['alias'] + patches[0].errors[0].locations == [[line: 1, column: query.lastIndexOf('$flag') + 1]] + + where: + parentType << ['Parent', 'Parent!'] + } + + def "conditional failure does not stall DataLoader dispatch with #mode and #parentType"() { + given: + BatchLoader batchLoader = { keys -> + CompletableFuture.completedFuture(keys.collect { it == 'parent' ? [child: 'value'] : 'good' }) + } + def registry = DataLoaderRegistry.newRegistry().register('values', DataLoaderFactory.newDataLoader(batchLoader)).build() + DataFetcher parent = { env -> env.getDataLoader('values').load('parent') } + DataFetcher good = { env -> env.getDataLoader('values').load('good') } + def graphQL = TestUtil.graphQL('type Query { parent: ' + parentType + ' good: String } type Parent { child: String }', + [Query: [parent: parent, good: good]]).build() + def query = 'query($flag: Boolean = true) { alias: parent { child @skip(if: $flag) } good }' + def input = ExecutionInput.newExecutionInput(query).variables([flag: null]).dataLoaderRegistry(registry) + .graphQLContext(mode == null ? [:] : [(mode): true]).build() + + when: + def result = graphQL.executeAsync(input).get(10, TimeUnit.SECONDS) + + then: + result.data == (parentType == 'Parent!' ? null : [alias: null, good: 'good']) + assertError(result, query, ['alias']) + + where: + [mode, parentType] << [[null, ENABLE_DATA_LOADER_CHAINING, ENABLE_DATA_LOADER_EXHAUSTED_DISPATCHING], ['Parent', 'Parent!']].combinations() + } + + def "defaults and Boolean variables keep #directive behavior for #variables"() { + given: + def graphQL = TestUtil.graphQL('type Query { field: Int }').build() + def query = 'query($flag: Boolean = true) { field @' + directive + '(if: $flag) }' + def input = ExecutionInput.newExecutionInput(query).variables(variables).root([field: 1]).build() + + when: + def result = graphQL.execute(input) + + then: + result.errors.empty + result.data == ((directive == 'include') == variables.getOrDefault('flag', true) ? [field: 1] : [:]) + + where: + [directive, variables] << [['skip', 'include'], [[:], [flag: true], [flag: false]]].combinations() + } + + def "unreached conditions are not coerced for #selection"() { + given: + def graphQL = TestUtil.graphQL('type Query { field: Int parent: Parent } type Parent { field: Int }').build() + def query = 'query($flag: Boolean = true) { ' + selection + ' }' + + when: + def result = execute(graphQL, query) + + then: + result.errors.empty + result.data == expected + + where: + selection | expected + 'field @skip(if: true) @include(if: $flag)' | [:] + 'parent { field @skip(if: $flag) }' | [parent: null] + '... @skip(if: true) { field @include(if: $flag) }' | [:] + } + + def "normalization keeps unknown variables undecided but rejects coerced null"() { + given: + def schema = TestUtil.schema('type Query { field: Int }') + def document = Parser.parse('query($flag: Boolean = true) { field @skip(if: $flag) }') + Field field = document.definitions[0].selectionSet.selections[0] as Field + + expect: + new ConditionalNodes().shouldIncludeWithoutVariables(field) == null + + when: + ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.of([flag: null])) + + then: + def exception = thrown(ConditionalDirectiveCoercionException) + exception.cause instanceof NonNullableValueCoercedAsNullException + exception.locations == [field.directives[0].arguments[0].value.sourceLocation] + } + + def "root failure completes operation instrumentation"() { + given: + def operationContext = Mock(InstrumentationContext) + def instrumentation = Spy(SimplePerformantInstrumentation) { + beginExecuteOperation(_, _) >> operationContext + } + def graphQL = TestUtil.graphQL('type Query { field: Int }').instrumentation(instrumentation).build() + def query = 'query($flag: Boolean = true) { field @skip(if: $flag) }' + + when: + def result = execute(graphQL, query) + + then: + 1 * operationContext.onDispatched() + 1 * operationContext.onCompleted({ it.dataPresent && it.data == null && it.errors.size() == 1 }, _ as ConditionalDirectiveCoercionException) + assertError(result, query, null) + } + + def "disabled error propagation keeps a failed non-null parent in its response position"() { + given: + def originallyEnabled = Directives.isExperimentalDisableErrorPropagationDirectiveEnabled() + Directives.setExperimentalDisableErrorPropagationEnabled(true) + def graphQL = TestUtil.graphQL('type Query { good: String parent: Parent! } type Parent { child: String }').build() + def query = 'query($flag: Boolean = true) @experimental_disableErrorPropagation { good alias: parent { child @skip(if: $flag) } }' + + when: + def result = execute(graphQL, query, [good: 'good', parent: [child: 'value']]) + + then: + result.data == [good: 'good', alias: null] + assertError(result, query, ['alias']) + + cleanup: + Directives.setExperimentalDisableErrorPropagationEnabled(originallyEnabled) + } + + def "non-null variable declarations still fail before operation execution"() { + given: + def graphQL = TestUtil.graphQL('type Query { field: Int }').build() + + when: + def result = execute(graphQL, 'query($flag: Boolean!) { field @skip(if: $flag) }') + + then: + !result.dataPresent + result.errors.size() == 1 + result.errors[0] instanceof NonNullableValueCoercedAsNullException + } + + def "conditional evaluation uses shared coercion for #condition even without a context"() { + given: + Field field = Parser.parse('{ field ' + condition + ' }').definitions[0].selectionSet.selections[0] as Field + + when: + new ConditionalNodes().shouldInclude(field, [:], null, null) + + then: + def exception = thrown(ConditionalDirectiveCoercionException) + exception.cause instanceof NonNullableValueCoercedAsNullException + exception.locations == [field.directives[0].arguments.empty ? field.directives[0].sourceLocation : field.directives[0].arguments[0].value.sourceLocation] + + where: + condition << ['@include(if: $missing)', '@skip'] + } + + def "unexpected coercion failures are not converted to GraphQL errors"() { + given: + Field field = Parser.parse('{ field @include(if: $flag) }').definitions[0].selectionSet.selections[0] as Field + + when: + // This API expects already-coerced variables. A wrong runtime type is a caller error. + new ConditionalNodes().shouldInclude(field, [flag: 'not a Boolean'], null, null) + + then: + thrown(ClassCastException) + } + + private ExecutionResult execute(GraphQL graphQL, String query, Map root = [:]) { + def input = ExecutionInput.newExecutionInput(query).variables([flag: null]).root(root).build() + graphQL.executeAsync(input).get(10, TimeUnit.SECONDS) + } + + private void assertError(ExecutionResult result, String query, List path) { + assert result.errors.size() == 1 + def error = result.errors[0] + assert error.message.contains('Invalid argument for directive') + assert error.errorType == ErrorType.DataFetchingException + assert error.path == path + assert error.locations == [new SourceLocation(1, query.lastIndexOf('$flag') + 1)] + } +}