diff --git a/src/jmh/java/benchmark/OneOfInputCoercionBenchmark.java b/src/jmh/java/benchmark/OneOfInputCoercionBenchmark.java new file mode 100644 index 0000000000..5735ecd788 --- /dev/null +++ b/src/jmh/java/benchmark/OneOfInputCoercionBenchmark.java @@ -0,0 +1,156 @@ +package benchmark; + +import graphql.Assert; +import graphql.ExecutionInput; +import graphql.ExecutionResult; +import graphql.GraphQL; +import graphql.GraphQLContext; +import graphql.execution.CoercedVariables; +import graphql.execution.RawVariables; +import graphql.execution.ValuesResolver; +import graphql.execution.preparsed.PreparsedDocumentEntry; +import graphql.language.OperationDefinition; +import graphql.language.VariableDefinition; +import graphql.parser.Parser; +import graphql.schema.DataFetchingEnvironment; +import graphql.schema.GraphQLSchema; +import graphql.schema.idl.RuntimeWiring; +import graphql.schema.idl.SchemaGenerator; +import graphql.schema.idl.SchemaParser; +import graphql.schema.idl.TypeDefinitionRegistry; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 3, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(2) +public class OneOfInputCoercionBenchmark { + + private static final int VALUES_PER_LEVEL = 8; + + @Param({"NONE", "UNRELATED", "REACHABLE"}) + public String oneOfCase; + + @Param({"1", "8"}) + public int depth; + + private TypeDefinitionRegistry registry; + private RuntimeWiring wiring; + private GraphQLSchema schema; + private GraphQL graphQL; + private ExecutionInput literalInput; + private ExecutionInput variableInput; + private List variableDefinitions; + private RawVariables rawVariables; + private GraphQLContext graphQLContext; + + @Setup + public void setup() { + registry = new SchemaParser().parse(schemaDefinition()); + wiring = RuntimeWiring.newRuntimeWiring() + .type("Query", type -> type.dataFetcher("result", this::countValues)) + .build(); + schema = buildSchema(); + graphQLContext = GraphQLContext.getDefault(); + Map documents = new LinkedHashMap<>(); + graphQL = GraphQL.newGraphQL(schema).preparsedDocumentProvider((input, parseAndValidate) -> { + PreparsedDocumentEntry entry = documents.computeIfAbsent(input.getQuery(), ignored -> parseAndValidate.apply(input)); + return CompletableFuture.completedFuture(entry); + }).build(); + String variableQuery = "query($input: Filter0!) { result(input: $input) }"; + variableDefinitions = Parser.parse(variableQuery).getDefinitionsOfType(OperationDefinition.class).get(0).getVariableDefinitions(); + rawVariables = RawVariables.of(Map.of("input", inputValue())); + literalInput = ExecutionInput.newExecutionInput().query("{ result(input: " + inputLiteral() + ") }").build(); + variableInput = ExecutionInput.newExecutionInput().query(variableQuery).variables(rawVariables.toMap()).build(); + validateResult(executeLiteralArgument()); + validateResult(executeVariableArgument()); + } + + @Benchmark + public ExecutionResult executeLiteralArgument() { + return graphQL.execute(literalInput); + } + + @Benchmark + public ExecutionResult executeVariableArgument() { + return graphQL.execute(variableInput); + } + + @Benchmark + public CoercedVariables coerceVariables() { + return ValuesResolver.coerceVariableValues(schema, variableDefinitions, rawVariables, graphQLContext, Locale.ROOT); + } + + @Benchmark + public GraphQLSchema buildSchema() { + return new SchemaGenerator().makeExecutableSchema(registry, wiring); + } + + private void validateResult(ExecutionResult result) { + Assert.assertTrue(result.getErrors().isEmpty(), "Benchmark query failed: %s", result.getErrors()); + Map data = result.getData(); + Assert.assertTrue(Integer.valueOf(VALUES_PER_LEVEL * depth).equals(data.get("result")), "Unexpected benchmark result"); + } + + @SuppressWarnings("unchecked") + private int countValues(DataFetchingEnvironment environment) { + Map input = environment.getArgument("input"); + int count = 0; + while (input != null) { + count += ((List) input.get("values")).size(); + input = (Map) input.get("next"); + } + return count; + } + + private String schemaDefinition() { + String leafDirective = oneOfCase.equals("REACHABLE") ? "@oneOf" : ""; + String otherDirective = oneOfCase.equals("UNRELATED") ? "@oneOf" : ""; + StringBuilder sdl = new StringBuilder() + .append("input Leaf ").append(leafDirective).append(" { value: Int, other: Int }\n") + .append("input Other ").append(otherDirective).append(" { value: Int, other: Int }\n"); + for (int level = 0; level < depth; level++) { + sdl.append("input Filter").append(level).append(" { values: [Leaf!]!, next: Filter") + .append((level + 1) % depth).append(" }\n"); + } + return sdl.append("type Query { result(input: Filter0!): Int, unused(input: Other): Int }").toString(); + } + + private Map inputValue() { + List> values = Collections.nCopies(VALUES_PER_LEVEL, Map.of("value", 1)); + Map input = Map.of("values", values); + for (int level = 1; level < depth; level++) { + input = Map.of("values", values, "next", input); + } + return input; + } + + private String inputLiteral() { + String values = "values: [" + String.join(",", Collections.nCopies(VALUES_PER_LEVEL, "{value: 1}")) + "]"; + String input = "{" + values + "}"; + for (int level = 1; level < depth; level++) { + input = "{" + values + ", next: " + input + "}"; + } + return input; + } +} diff --git a/src/main/java/graphql/analysis/NodeVisitorWithTypeTracking.java b/src/main/java/graphql/analysis/NodeVisitorWithTypeTracking.java index c2f0bebd3f..83af3021b5 100644 --- a/src/main/java/graphql/analysis/NodeVisitorWithTypeTracking.java +++ b/src/main/java/graphql/analysis/NodeVisitorWithTypeTracking.java @@ -166,7 +166,7 @@ public TraversalControl visitField(Field field, TraverserContext context) GraphQLCodeRegistry codeRegistry = schema.getCodeRegistry(); Map argumentValues; if (options.isCoerceFieldArguments()) { - argumentValues = ValuesResolver.getArgumentValues(codeRegistry, + argumentValues = ValuesResolver.getArgumentValues(schema, codeRegistry, fieldDefinition.getArguments(), field.getArguments(), CoercedVariables.of(variables), diff --git a/src/main/java/graphql/execution/ExecutionStepInfoFactory.java b/src/main/java/graphql/execution/ExecutionStepInfoFactory.java index fc382c2052..946424230f 100644 --- a/src/main/java/graphql/execution/ExecutionStepInfoFactory.java +++ b/src/main/java/graphql/execution/ExecutionStepInfoFactory.java @@ -76,7 +76,7 @@ private static Supplier> getArgumentV Supplier> argumentValues; GraphQLCodeRegistry codeRegistry = executionContext.getGraphQLSchema().getCodeRegistry(); Supplier> argValuesSupplier = () -> { - Map resolvedValues = ValuesResolver.getArgumentValues(codeRegistry, + Map resolvedValues = ValuesResolver.getArgumentValues(executionContext.getGraphQLSchema(), codeRegistry, fieldArgDefs, fieldArgs, executionContext.getCoercedVariables(), diff --git a/src/main/java/graphql/execution/ValuesResolver.java b/src/main/java/graphql/execution/ValuesResolver.java index 357e19d64b..48919e1fd9 100644 --- a/src/main/java/graphql/execution/ValuesResolver.java +++ b/src/main/java/graphql/execution/ValuesResolver.java @@ -155,7 +155,7 @@ public static Map getArgumentValues( Locale locale ) { InputInterceptor inputInterceptor = graphqlContext.get(InputInterceptor.class); - return getArgumentValuesImpl(inputInterceptor, DEFAULT_FIELD_VISIBILITY, argumentTypes, arguments, coercedVariables, graphqlContext, locale); + return getArgumentValuesImpl(null, inputInterceptor, DEFAULT_FIELD_VISIBILITY, argumentTypes, arguments, coercedVariables, graphqlContext, locale); } /** @@ -207,7 +207,21 @@ public static Map getArgumentValues( Locale locale ) { InputInterceptor inputInterceptor = graphqlContext.get(InputInterceptor.class); - return getArgumentValuesImpl(inputInterceptor, codeRegistry.getFieldVisibility(), argumentTypes, arguments, coercedVariables, graphqlContext, locale); + return getArgumentValuesImpl(null, inputInterceptor, codeRegistry.getFieldVisibility(), argumentTypes, arguments, coercedVariables, graphqlContext, locale); + } + + @Internal + public static Map getArgumentValues( + GraphQLSchema schema, + GraphQLCodeRegistry codeRegistry, + List argumentTypes, + List arguments, + CoercedVariables coercedVariables, + GraphQLContext graphqlContext, + Locale locale + ) { + InputInterceptor inputInterceptor = graphqlContext.get(InputInterceptor.class); + return getArgumentValuesImpl(schema, inputInterceptor, codeRegistry.getFieldVisibility(), argumentTypes, arguments, coercedVariables, graphqlContext, locale); } /** @@ -319,6 +333,7 @@ public static T getInputValueImpl( @NonNull private static Map getArgumentValuesImpl( + @Nullable GraphQLSchema schema, InputInterceptor inputInterceptor, GraphqlFieldVisibility fieldVisibility, List argumentTypes, @@ -375,7 +390,7 @@ private static Map getArgumentValuesImpl( coercedValues.put(argumentName, value); } - ValuesResolverOneOfValidation.validateOneOfInputTypes(argumentType, value, argumentValue, argumentName, locale); + ValuesResolverOneOfValidation.validateOneOfInputTypes(schema, argumentType, value, argumentValue, argumentName, locale); } } diff --git a/src/main/java/graphql/execution/ValuesResolverConversion.java b/src/main/java/graphql/execution/ValuesResolverConversion.java index 20e9feb552..135d508107 100644 --- a/src/main/java/graphql/execution/ValuesResolverConversion.java +++ b/src/main/java/graphql/execution/ValuesResolverConversion.java @@ -376,6 +376,7 @@ static CoercedVariables externalValueToInternalValueForVariables( coercedValues.put(variableName, null); } else { Object coercedValue = externalValueToInternalValueImpl( + schema, variableName, inputInterceptor, fieldVisibility, @@ -429,9 +430,23 @@ static Object externalValueToInternalValueImpl( Object originalValue, GraphQLContext graphqlContext, Locale locale + ) throws NonNullableValueCoercedAsNullException, CoercingParseValueException { + return externalValueToInternalValueImpl(null, variableName, inputInterceptor, fieldVisibility, graphQLType, originalValue, graphqlContext, locale); + } + + private static Object externalValueToInternalValueImpl( + @Nullable GraphQLSchema schema, + String variableName, + InputInterceptor inputInterceptor, + GraphqlFieldVisibility fieldVisibility, + GraphQLInputType graphQLType, + Object originalValue, + GraphQLContext graphqlContext, + Locale locale ) throws NonNullableValueCoercedAsNullException, CoercingParseValueException { if (isNonNull(graphQLType)) { Object returnValue = externalValueToInternalValueImpl( + schema, variableName, inputInterceptor, fieldVisibility, @@ -471,6 +486,7 @@ static Object externalValueToInternalValueImpl( locale); } else if (graphQLType instanceof GraphQLList) { return externalValueToInternalValueForList( + schema, inputInterceptor, fieldVisibility, (GraphQLList) graphQLType, @@ -482,6 +498,7 @@ static Object externalValueToInternalValueImpl( GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) graphQLType; //noinspection unchecked Map coercedMap = externalValueToInternalValueForObject( + schema, inputInterceptor, fieldVisibility, inputObjectType, @@ -489,7 +506,7 @@ static Object externalValueToInternalValueImpl( graphqlContext, locale); - ValuesResolverOneOfValidation.validateOneOfInputTypes(inputObjectType, coercedMap, null, variableName, locale); + ValuesResolverOneOfValidation.validateOneOfInputTypes(schema, inputObjectType, coercedMap, null, variableName, locale); return coercedMap; } else { throw CoercingParseValueException.newCoercingParseValueException() @@ -506,6 +523,7 @@ static Object externalValueToInternalValueImpl( * performs validation */ private static Map externalValueToInternalValueForObject( + @Nullable GraphQLSchema schema, InputInterceptor inputInterceptor, GraphqlFieldVisibility fieldVisibility, GraphQLInputObjectType inputObjectType, @@ -545,6 +563,8 @@ private static Map externalValueToInternalValueForObject( coercedValues.put(fieldName, null); } else { value = externalValueToInternalValueImpl( + schema, + "externalValue", inputInterceptor, fieldVisibility, fieldType, @@ -592,6 +612,7 @@ private static Object externalValueToInternalValueForEnum( * including validation */ private static List externalValueToInternalValueForList( + @Nullable GraphQLSchema schema, InputInterceptor inputInterceptor, GraphqlFieldVisibility fieldVisibility, GraphQLList graphQLList, @@ -605,6 +626,8 @@ private static List externalValueToInternalValueForList( List list = FpKit.arrayListSizedTo(listOrSingletonList); for (Object val : listOrSingletonList) { list.add(externalValueToInternalValueImpl( + schema, + "externalValue", inputInterceptor, fieldVisibility, wrappedType, diff --git a/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java b/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java index 4c1daac1c8..2b56a74766 100644 --- a/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java +++ b/src/main/java/graphql/execution/ValuesResolverOneOfValidation.java @@ -11,8 +11,10 @@ import graphql.schema.GraphQLInputObjectType; import graphql.schema.GraphQLInputType; import graphql.schema.GraphQLList; +import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLType; import graphql.schema.GraphQLTypeUtil; +import org.jspecify.annotations.Nullable; import java.util.List; import java.util.Locale; @@ -24,6 +26,13 @@ @Internal final class ValuesResolverOneOfValidation { + public static void validateOneOfInputTypes(@Nullable GraphQLSchema schema, GraphQLType type, Object inputValue, Value argumentValue, String argumentName, Locale locale) { + if (schema != null && !schema.inputTypeContainsOneOf(type)) { + return; + } + validateOneOfInputTypes(type, inputValue, argumentValue, argumentName, locale); + } + @SuppressWarnings("unchecked") static void validateOneOfInputTypes(GraphQLType type, Object inputValue, Value argumentValue, String argumentName, Locale locale) { GraphQLType unwrappedNonNullType = GraphQLTypeUtil.unwrapNonNull(type); diff --git a/src/main/java/graphql/execution/directives/DirectivesResolver.java b/src/main/java/graphql/execution/directives/DirectivesResolver.java index 9fff2a514c..b26310b64e 100644 --- a/src/main/java/graphql/execution/directives/DirectivesResolver.java +++ b/src/main/java/graphql/execution/directives/DirectivesResolver.java @@ -34,7 +34,7 @@ public BiMap resolveDirectives(List dire directives.forEach(directive -> { GraphQLDirective protoType = schema.getDirective(directive.getName()); if (protoType != null) { - GraphQLDirective graphQLDirective = protoType.transform(builder -> buildArguments(builder, codeRegistry, protoType, directive, variables, graphQLContext, locale)); + GraphQLDirective graphQLDirective = protoType.transform(builder -> buildArguments(builder, schema, codeRegistry, protoType, directive, variables, graphQLContext, locale)); directiveMap.put(graphQLDirective, directive); } }); @@ -42,13 +42,14 @@ public BiMap resolveDirectives(List dire } private void buildArguments(GraphQLDirective.Builder directiveBuilder, + GraphQLSchema schema, GraphQLCodeRegistry codeRegistry, GraphQLDirective protoType, Directive fieldDirective, CoercedVariables variables, GraphQLContext graphQLContext, Locale locale) { - Map argumentValues = ValuesResolver.getArgumentValues(codeRegistry, protoType.getArguments(), fieldDirective.getArguments(), variables, graphQLContext, locale); + Map argumentValues = ValuesResolver.getArgumentValues(schema, codeRegistry, protoType.getArguments(), fieldDirective.getArguments(), variables, graphQLContext, locale); directiveBuilder.clearArguments(); protoType.getArguments().forEach(protoArg -> { if (argumentValues.containsKey(protoArg.getName())) { diff --git a/src/main/java/graphql/schema/GraphQLSchema.java b/src/main/java/graphql/schema/GraphQLSchema.java index 88039d25cf..314b656aa2 100644 --- a/src/main/java/graphql/schema/GraphQLSchema.java +++ b/src/main/java/graphql/schema/GraphQLSchema.java @@ -17,6 +17,7 @@ import graphql.language.SchemaDefinition; import graphql.language.SchemaExtensionDefinition; import graphql.schema.impl.GraphQLTypeCollectingVisitor; +import graphql.schema.impl.OneOfInputTypeReachability; import graphql.schema.impl.SchemaUtil; import graphql.schema.validation.InvalidSchemaException; import graphql.schema.validation.SchemaValidationError; @@ -72,6 +73,7 @@ public class GraphQLSchema { private final GraphQLCodeRegistry codeRegistry; private final ImmutableMap typeMap; + private final ImmutableMap inputTypeContainsOneOf; private final ImmutableMap> interfaceNameToObjectTypes; private final ImmutableMap> interfaceNameToObjectTypeNames; @@ -104,6 +106,7 @@ private GraphQLSchema(Builder builder) { this.codeRegistry = builder.codeRegistry; this.typeMap = ImmutableKit.emptyMap(); + this.inputTypeContainsOneOf = ImmutableKit.emptyMap(); this.interfaceNameToObjectTypes = ImmutableKit.emptyMap(); this.interfaceNameToObjectTypeNames = ImmutableKit.emptyMap(); } @@ -134,6 +137,7 @@ public GraphQLSchema(GraphQLSchema existingSchema, this.description = existingSchema.description; this.codeRegistry = codeRegistry; this.typeMap = typeMap; + this.inputTypeContainsOneOf = OneOfInputTypeReachability.compute(typeMap); this.interfaceNameToObjectTypes = interfaceNameToObjectTypes; this.interfaceNameToObjectTypeNames = buildInterfacesToObjectName(interfaceNameToObjectTypes); } @@ -159,6 +163,7 @@ public GraphQLSchema(BuilderWithoutTypes builder) { this.definition = existingSchema.definition; this.extensionDefinitions = existingSchema.extensionDefinitions; this.typeMap = existingSchema.typeMap; + this.inputTypeContainsOneOf = existingSchema.inputTypeContainsOneOf; this.interfaceNameToObjectTypes = existingSchema.interfaceNameToObjectTypes; this.interfaceNameToObjectTypeNames = existingSchema.interfaceNameToObjectTypeNames; @@ -220,6 +225,7 @@ private GraphQLSchema(FastBuilder fastBuilder) { this.description = fastBuilder.description; this.codeRegistry = fastBuilder.codeRegistryBuilder.build(); this.typeMap = finalTypeMap; + this.inputTypeContainsOneOf = OneOfInputTypeReachability.compute(finalTypeMap); this.interfaceNameToObjectTypes = finalInterfaceMap; this.interfaceNameToObjectTypeNames = finalInterfaceNameMap; } @@ -254,6 +260,22 @@ private static ImmutableMap> buildInterfacesToObje return map.build(); } + @Internal + public boolean inputTypeContainsOneOf(GraphQLType inputType) { + GraphQLType namedType = GraphQLTypeUtil.unwrapAllAs(inputType); + if (namedType instanceof GraphQLTypeReference) { + return inputTypeContainsOneOf.getOrDefault(((GraphQLTypeReference) namedType).getName(), true); + } + if (!(namedType instanceof GraphQLInputObjectType)) { + return false; + } + String name = ((GraphQLInputObjectType) namedType).getName(); + if (typeMap.get(name) != namedType) { + return true; + } + return inputTypeContainsOneOf.getOrDefault(name, true); + } + public GraphQLCodeRegistry getCodeRegistry() { return codeRegistry; } diff --git a/src/main/java/graphql/schema/impl/OneOfInputTypeReachability.java b/src/main/java/graphql/schema/impl/OneOfInputTypeReachability.java new file mode 100644 index 0000000000..5f26b1fd2d --- /dev/null +++ b/src/main/java/graphql/schema/impl/OneOfInputTypeReachability.java @@ -0,0 +1,66 @@ +package graphql.schema.impl; + +import com.google.common.collect.ImmutableMap; +import graphql.Internal; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; +import graphql.schema.GraphQLNamedType; +import graphql.schema.GraphQLTypeUtil; +import org.jspecify.annotations.NullMarked; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@Internal +@NullMarked +public class OneOfInputTypeReachability { + + public static ImmutableMap compute(Map typeMap) { + Map containsOneOf = new LinkedHashMap<>(); + Deque pending = new ArrayDeque<>(); + for (GraphQLNamedType type : typeMap.values()) { + if (!(type instanceof GraphQLInputObjectType)) { + continue; + } + boolean oneOf = ((GraphQLInputObjectType) type).isOneOf(); + containsOneOf.put(type.getName(), oneOf); + if (oneOf) { + pending.add(type.getName()); + } + } + if (pending.isEmpty()) { + return ImmutableMap.copyOf(containsOneOf); + } + Map> parents = new LinkedHashMap<>(); + for (GraphQLNamedType type : typeMap.values()) { + if (type instanceof GraphQLInputObjectType) { + collectParents((GraphQLInputObjectType) type, parents); + } + } + while (!pending.isEmpty()) { + String name = pending.removeFirst(); + markParents(parents.getOrDefault(name, List.of()), containsOneOf, pending); + } + return ImmutableMap.copyOf(containsOneOf); + } + + private static void markParents(List parents, Map containsOneOf, Deque pending) { + for (String parent : parents) { + if (!Boolean.TRUE.equals(containsOneOf.get(parent))) { + containsOneOf.put(parent, true); + pending.addLast(parent); + } + } + } + + private static void collectParents(GraphQLInputObjectType type, Map> parents) { + for (GraphQLInputObjectField field : type.getFields()) { + GraphQLNamedType child = GraphQLTypeUtil.unwrapAllAs(field.getType()); + parents.computeIfAbsent(child.getName(), ignored -> new ArrayList<>()).add(type.getName()); + } + } +} diff --git a/src/test/groovy/graphql/execution/OneOfInputCoercionBenchmarkTest.groovy b/src/test/groovy/graphql/execution/OneOfInputCoercionBenchmarkTest.groovy new file mode 100644 index 0000000000..093b698e7a --- /dev/null +++ b/src/test/groovy/graphql/execution/OneOfInputCoercionBenchmarkTest.groovy @@ -0,0 +1,43 @@ +package graphql.execution + +import graphql.schema.GraphQLInputObjectType +import spock.lang.Specification + +class OneOfInputCoercionBenchmarkTest extends Specification { + + def "benchmark fixtures coerce the intended input graph - #oneOfCase, depth #depth"() { + given: + // JMH classes are available only on the test runtime classpath. + def benchmark = Class.forName("benchmark.OneOfInputCoercionBenchmark").getDeclaredConstructor().newInstance() + benchmark.oneOfCase = oneOfCase + benchmark.depth = depth + benchmark.setup() + + when: + def literalResult = benchmark.executeLiteralArgument() + def variableResult = benchmark.executeVariableArgument() + def variables = benchmark.coerceVariables().toMap() + def schema = benchmark.buildSchema() + + then: + literalResult.errors.isEmpty() + variableResult.errors.isEmpty() + literalResult.getData() == [result: 8 * depth] + variableResult.getData() == literalResult.getData() + schema.inputTypeContainsOneOf(schema.getType('Filter0')) == (oneOfCase == 'REACHABLE') + ((GraphQLInputObjectType) schema.getType('Leaf')).isOneOf() == (oneOfCase == 'REACHABLE') + ((GraphQLInputObjectType) schema.getType('Other')).isOneOf() == (oneOfCase == 'UNRELATED') + + and: + def input = variables.input + depth.times { level -> + assert input['values'] == Collections.nCopies(8, [value: 1]) + assert input.containsKey('next') == (level < depth - 1) + input = input.next + } + input == null + + where: + [oneOfCase, depth] << [['NONE', 'UNRELATED', 'REACHABLE'], [1, 8]].combinations() + } +} diff --git a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy index 291314f575..a0ae0643db 100644 --- a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy +++ b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy @@ -1,5 +1,6 @@ package graphql.execution +import graphql.AssertException import graphql.Directives import graphql.ErrorType import graphql.GraphQLContext @@ -179,6 +180,101 @@ class ValuesResolverTest extends Specification { er.errors[0].message.contains("OneOf type field 'OneOf.a' must be non-null.") } + def "schema-aware argument coercion validates detached types and schema-less coercion retains validation"() { + given: + def plain = TestUtil.schema('input Choice { a: Int, b: Int } type Query { q(arg: Choice): Boolean }') + def oneOf = TestUtil.schema('input Choice @oneOf { a: Int, b: Int } type Query { q(arg: Choice): Boolean }') + def arguments = [newArgument().name('arg').type(oneOf.getType('Choice')).build()] + def supplied = [Argument.newArgument().name('arg').value(buildObjectLiteral([a: IntValue.of(1), b: IntValue.of(2)])).build()] + + when: + ValuesResolver.getArgumentValues(plain, plain.codeRegistry, arguments, supplied, CoercedVariables.emptyVariables(), graphQLContext, locale) + + then: + thrown(OneOfTooManyKeysException) + + when: + ValuesResolver.getArgumentValues(arguments, supplied, CoercedVariables.emptyVariables(), graphQLContext, locale) + + then: + thrown(OneOfTooManyKeysException) + } + + def "schema-less argument coercion retains duplicate object field assertion"() { + given: + def schema = TestUtil.schema('input Plain { value: Int } type Query { q(arg: Plain): Boolean }') + def duplicate = ObjectValue.newObjectValue().objectFields([ + ObjectField.newObjectField().name('value').value(IntValue.of(1)).build(), + ObjectField.newObjectField().name('value').value(IntValue.of(2)).build() + ]).build() + def supplied = [Argument.newArgument().name('arg').value(duplicate).build()] + + when: + ValuesResolver.getArgumentValues(schema.queryType.getFieldDefinition('q').arguments, supplied, CoercedVariables.emptyVariables(), graphQLContext, locale) + + then: + thrown(AssertException) + } + + def "oneOf reachable through a self-referencing input type is still validated"() { + def sdl = ''' + input OneOf @oneOf { a: Int, b: Int } + input Recursive { oneOfField: OneOf, self: Recursive } + type Query { q(arg: Recursive): Boolean } + ''' + + DataFetcher q = { env -> return !env.getArguments().isEmpty() } + def graphQL = TestUtil.graphQL(sdl, [Query: [q: q]]).build() + + when: "a variable value violates the nested oneOf constraint" + def er = graphQL.execute( + newExecutionInput('query ($arg: Recursive) { q(arg: $arg) }') + .variables([arg: [self: [oneOfField: [a: 1, b: 2]]]])) + + then: + er.errors.size() == 1 + er.errors[0].message == "Exactly one key must be specified for OneOf type 'OneOf'." + + when: "the nested oneOf value is valid" + er = graphQL.execute( + newExecutionInput('query ($arg: Recursive) { q(arg: $arg) }') + .variables([arg: [self: [self: [oneOfField: [a: 1]]]]])) + + then: + er.errors.isEmpty() + + when: "a literal value violates the nested oneOf constraint" + er = graphQL.execute('{ q(arg: {self: {oneOfField: {a: 1, b: 2}}}) }') + + then: + er.errors.size() == 1 + er.errors[0].message.contains("Exactly one key must be specified for OneOf type 'OneOf'.") + } + + def "self-referencing input types without oneOf execute without infinite recursion"() { + def sdl = ''' + input Plain { x: Int, self: Plain } + type Query { q(arg: Plain): Boolean } + ''' + + DataFetcher q = { env -> return !env.getArguments().isEmpty() } + def graphQL = TestUtil.graphQL(sdl, [Query: [q: q]]).build() + + when: "a variable value uses a self-referencing input type with no reachable @oneOf" + def er = graphQL.execute( + newExecutionInput('query ($arg: Plain) { q(arg: $arg) }') + .variables([arg: [self: [self: [x: 1]]]])) + + then: + er.errors.isEmpty() + + when: "a literal value uses a self-referencing input type with no reachable @oneOf" + er = graphQL.execute('{ q(arg: {self: {self: {x: 1}}}) }') + + then: + er.errors.isEmpty() + } + class Person { def name = "" diff --git a/src/test/groovy/graphql/schema/OneOfInputTypeReachabilityTest.groovy b/src/test/groovy/graphql/schema/OneOfInputTypeReachabilityTest.groovy new file mode 100644 index 0000000000..281e094b7a --- /dev/null +++ b/src/test/groovy/graphql/schema/OneOfInputTypeReachabilityTest.groovy @@ -0,0 +1,102 @@ +package graphql.schema + +import graphql.Directives +import graphql.TestUtil +import spock.lang.Specification + +import static graphql.Scalars.GraphQLString +import static graphql.schema.GraphQLArgument.newArgument +import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition +import static graphql.schema.GraphQLInputObjectField.newInputObjectField +import static graphql.schema.GraphQLInputObjectType.newInputObject +import static graphql.schema.GraphQLList.list +import static graphql.schema.GraphQLNonNull.nonNull +import static graphql.schema.GraphQLObjectType.newObject +import static graphql.schema.GraphQLTypeReference.typeRef + +class OneOfInputTypeReachabilityTest extends Specification { + + def "inputTypeContainsOneOf resolves wrapped types and recursive references - #oneOf"() { + given: + def schema = TestUtil.schema(""" + input Choice ${oneOf ? '@oneOf' : ''} { value: String } + input A { back: [B!], choice: [Choice!] } + input B { back: A } + input Plain { self: Plain, value: String } + type Query { q(arg: A, plain: Plain): String } + """) + + expect: + schema.inputTypeContainsOneOf(schema.getType('A')) == oneOf + schema.inputTypeContainsOneOf(schema.getType('B')) == oneOf + schema.inputTypeContainsOneOf(schema.getType('Choice')) == oneOf + schema.inputTypeContainsOneOf(nonNull(list(nonNull(schema.getType('A'))))) == oneOf + schema.inputTypeContainsOneOf(nonNull(list(typeRef('B')))) == oneOf + !schema.inputTypeContainsOneOf(schema.getType('Plain')) + !schema.inputTypeContainsOneOf(GraphQLString) + + where: + oneOf << [false, true] + } + + def "inputTypeContainsOneOf is independent for schemas with the same type names"() { + given: + def plain = TestUtil.schema('input Choice { value: String } type Query { q(arg: Choice): String }') + def oneOf = TestUtil.schema('input Choice @oneOf { value: String } type Query { q(arg: Choice): String }') + + expect: + !plain.inputTypeContainsOneOf(plain.getType('Choice')) + oneOf.inputTypeContainsOneOf(oneOf.getType('Choice')) + plain.inputTypeContainsOneOf(oneOf.getType('Choice')) + oneOf.inputTypeContainsOneOf(plain.getType('Choice')) + plain.inputTypeContainsOneOf(typeRef('Unknown')) + plain.inputTypeContainsOneOf(newInputObject().name('Unknown').field(newInputObjectField().name('value').type(GraphQLString)).build()) + } + + def "inputTypeContainsOneOf follows schema transforms"() { + given: + def original = TestUtil.schema('input Choice { value: String } type Query { q(arg: Choice): String }') + def choice = (GraphQLInputObjectType) original.getType('Choice') + def changedChoice = choice.transform { it.withAppliedDirective(Directives.OneOfDirective.toAppliedDirective()) } + def changedQuery = original.queryType.transform { + it.field(original.queryType.getFieldDefinition('q').transform { field -> + field.argument(newArgument().name('arg').type(changedChoice)) + }) + } + + when: + def transformed = original.transform { it.query(changedQuery) } + def registryOnly = transformed.transformWithoutTypes { it.codeRegistry(GraphQLCodeRegistry.newCodeRegistry().build()) } + + then: + !original.inputTypeContainsOneOf(choice) + transformed.inputTypeContainsOneOf(transformed.getType('Choice')) + registryOnly.inputTypeContainsOneOf(registryOnly.getType('Choice')) + !original.transformWithoutTypes { it.description('copy') }.inputTypeContainsOneOf(choice) + } + + def "inputTypeContainsOneOf works with FastBuilder and unresolved references - #oneOf"() { + given: + def choiceBuilder = newInputObject().name('Choice').field(newInputObjectField().name('value').type(GraphQLString)) + if (oneOf) { + choiceBuilder.withAppliedDirective(Directives.OneOfDirective.toAppliedDirective()) + } + def choice = choiceBuilder.build() + def recursive = newInputObject().name('Recursive') + .field(newInputObjectField().name('self').type(typeRef('Recursive'))) + .field(newInputObjectField().name('choice').type(typeRef('Choice'))).build() + def query = newObject().name('Query').field(newFieldDefinition().name('q').type(GraphQLString) + .argument(newArgument().name('arg').type(typeRef('Recursive')))).build() + + when: + def schema = new GraphQLSchema.FastBuilder(GraphQLCodeRegistry.newCodeRegistry(), query, null, null) + .addType(recursive).addType(choice).withValidation(true).build() + + then: + schema.inputTypeContainsOneOf(recursive) == oneOf + schema.inputTypeContainsOneOf(typeRef('Choice')) == oneOf + + where: + oneOf << [false, true] + } +}