Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/main/java/graphql/execution/Execution.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -212,11 +213,15 @@ private CompletableFuture<ExecutionResult> 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();
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/graphql/execution/ExecutionStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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);

Expand Down
17 changes: 15 additions & 2 deletions src/main/java/graphql/execution/SubscriptionExecutionStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -191,8 +192,7 @@ private CompletableFuture<ExecutionResult> executeSubscriptionEvent(ExecutionCon
executionContext.getDataLoaderDispatcherStrategy().subscriptionEventCompletionDone(alternativeCallContext);
CompletableFuture<ExecutionResult> 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);
});
Expand All @@ -209,6 +209,19 @@ private CompletableFuture<ExecutionResult> executeSubscriptionEvent(ExecutionCon
return overallResult;
}

private ExecutionResult completeSubscriptionEvent(ExecutionStrategyParameters parameters, AlternativeCallContext alternativeCallContext,
@Nullable Map<Object, Object> 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(
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
}
}
56 changes: 33 additions & 23 deletions src/main/java/graphql/execution/conditional/ConditionalNodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -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;
}
//
Expand Down Expand Up @@ -83,20 +87,20 @@ public GraphQLContext getGraphQLContext() {
}


private @Nullable Boolean shouldInclude(Map<String, Object> variables, List<Directive> directives) {
private @Nullable Boolean shouldInclude(@Nullable Map<String, Object> variables, List<Directive> 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;
}
if (skip) {
return false;
}

return getDirectiveResult(variables, directives, IncludeDirective.getName(), true);
return getDirectiveResult(variables, directives, IncludeDirective, true, graphQLContext);
}

public boolean containsSkipOrIncludeDirective(DirectivesContainer<?> directivesContainer) {
Expand Down Expand Up @@ -130,27 +134,33 @@ public String getIncludeVariableName(DirectivesContainer<?> directivesContainer)
}


private @Nullable Boolean getDirectiveResult(Map<String, Object> variables, List<Directive> 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<String, Object> variables, List<Directive> 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<String, Object> 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<Argument> arguments, @Nullable Map<String, Object> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<GraphQLError> 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();
Expand Down
Loading
Loading