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
124 changes: 124 additions & 0 deletions src/jmh/java/benchmark/OneOfVariableCoercionBenchmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package benchmark;

import graphql.GraphQLContext;
import graphql.execution.CoercedVariables;
import graphql.execution.RawVariables;
import graphql.execution.ValuesResolver;
import graphql.language.OperationDefinition;
import graphql.language.VariableDefinition;
import graphql.parser.Parser;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.SchemaGenerator;
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.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* Coerces a variable made of nested input objects, `depth` levels deep, each level having
* {@link #FIELDS_PER_LEVEL} optional scalar fields of which only a few are provided. The innermost
* level holds a `Leaf` input object which is either a plain input object or a `@oneOf` one.
*/
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3, time = 2)
@Measurement(iterations = 5, time = 2)
@Fork(2)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class OneOfVariableCoercionBenchmark {

private static final int FIELDS_PER_LEVEL = 8;
private static final int PROVIDED_FIELDS_PER_LEVEL = 3;
private static final int LIST_SIZE = 20;

@Param({"1", "8"})
public int depth;

@Param({"false", "true"})
public boolean oneOfLeaf;

private GraphQLSchema schema;
private List<VariableDefinition> variableDefinitions;
private RawVariables singleObjectVariables;
private RawVariables listOfObjectsVariables;
private final GraphQLContext graphQLContext = GraphQLContext.getDefault();

@Setup
public void setup() {
schema = SchemaGenerator.createdMockedSchema(sdl());
String query = "query ($input: Level0, $inputs: [Level0!]) { single(input: $input) list(inputs: $inputs) }";
variableDefinitions = Parser.parse(query)
.getFirstDefinitionOfType(OperationDefinition.class).orElseThrow()
.getVariableDefinitions();

Map<String, Object> input = inputValue();
List<Object> inputs = new ArrayList<>();
for (int i = 0; i < LIST_SIZE; i++) {
inputs.add(inputValue());
}
singleObjectVariables = RawVariables.of(Map.of("input", input));
listOfObjectsVariables = RawVariables.of(Map.of("inputs", inputs));

// make sure the variables are valid
singleObject();
listOfObjects();
}

@Benchmark
public CoercedVariables singleObject() {
return ValuesResolver.coerceVariableValues(schema, variableDefinitions, singleObjectVariables, graphQLContext, Locale.ENGLISH);
}

@Benchmark
public CoercedVariables listOfObjects() {
return ValuesResolver.coerceVariableValues(schema, variableDefinitions, listOfObjectsVariables, graphQLContext, Locale.ENGLISH);
}

private String sdl() {
StringBuilder sdl = new StringBuilder();
sdl.append("input Leaf ").append(oneOfLeaf ? "@oneOf " : "").append("{ a: Int, b: String }\n");
for (int level = 0; level < depth; level++) {
sdl.append("input Level").append(level).append(" {\n");
for (int f = 0; f < FIELDS_PER_LEVEL; f++) {
sdl.append(" f").append(f).append(": String\n");
}
if (level == depth - 1) {
sdl.append(" leaf: Leaf\n");
} else {
sdl.append(" next: Level").append(level + 1).append("\n");
}
sdl.append("}\n");
}
sdl.append("type Query { single(input: Level0): Boolean list(inputs: [Level0!]): Boolean }\n");
return sdl.toString();
}

private Map<String, Object> inputValue() {
Map<String, Object> value = Map.of("a", 1);
String childFieldName = "leaf";
for (int level = depth - 1; level >= 0; level--) {
Map<String, Object> levelValue = new LinkedHashMap<>();
for (int f = 0; f < PROVIDED_FIELDS_PER_LEVEL; f++) {
levelValue.put("f" + f, "value" + f);
}
levelValue.put(childFieldName, value);
value = levelValue;
childFieldName = "next";
}
return value;
}
}
35 changes: 31 additions & 4 deletions src/main/java/graphql/execution/ValuesResolverConversion.java
Original file line number Diff line number Diff line change
Expand Up @@ -481,16 +481,14 @@ static Object externalValueToInternalValueImpl(
if (value instanceof Map) {
GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) graphQLType;
//noinspection unchecked
Map<String, Object> coercedMap = externalValueToInternalValueForObject(
return externalValueToInternalValueForObject(
variableName,
inputInterceptor,
fieldVisibility,
inputObjectType,
(Map<String, Object>) value,
graphqlContext,
locale);

ValuesResolverOneOfValidation.validateOneOfInputTypes(inputObjectType, coercedMap, null, variableName, locale);
return coercedMap;
} else {
throw CoercingParseValueException.newCoercingParseValueException()
.message("Expected type 'Map' but was '" + value.getClass().getSimpleName() +
Expand All @@ -506,6 +504,7 @@ static Object externalValueToInternalValueImpl(
* performs validation
*/
private static Map<String, Object> externalValueToInternalValueForObject(
String variableName,
InputInterceptor inputInterceptor,
GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType inputObjectType,
Expand All @@ -522,6 +521,10 @@ private static Map<String, Object> externalValueToInternalValueForObject(
}

Map<String, Object> coercedValues = new LinkedHashMap<>();
// Fields filled from a literal or internal default. Unlike provided values and external defaults,
// these don't go through externalValueToInternalValueImpl, so nothing has oneOf-validated their
// nested input objects yet. Tracked so they can get a full recursive walk below.
List<GraphQLInputObjectField> nonExternalDefaultFields = null;

for (GraphQLInputObjectField inputFieldDefinition : fieldDefinitions) {
GraphQLInputType fieldType = inputFieldDefinition.getType();
Expand All @@ -538,6 +541,12 @@ private static Map<String, Object> externalValueToInternalValueForObject(
graphqlContext,
locale);
coercedValues.put(fieldName, coercedDefaultValue);
if (!defaultValue.isExternal()) {
if (nonExternalDefaultFields == null) {
nonExternalDefaultFields = new ArrayList<>(1);
}
nonExternalDefaultFields.add(inputFieldDefinition);
}
} else if (isNonNull(fieldType) && (!hasValue || value == null)) {
throw new NonNullableValueCoercedAsNullException(fieldName, emptyList(), fieldType);
} else if (hasValue) {
Expand All @@ -555,6 +564,24 @@ private static Map<String, Object> externalValueToInternalValueForObject(
}
}
}

// OneOf validation happens here, once per input object, as each object finishes conversion.
//
// This object: only its own oneOf rule is checked (no recursion). Every nested input object that came
// from a provided value or an external default was converted by externalValueToInternalValueImpl,
// which ends up back in this method for that object and checks it there. Re-walking the subtree from
// every ancestor would re-check the same objects at each level (O(depth x size)).
//
// Literal and internal defaults: these never reached this method for their nested objects, so they get
// the full recursive walk. It runs after this object's own check to keep the same error order.
if (inputObjectType.isOneOf()) {
ValuesResolverOneOfValidation.validateOneOfInputTypesInternal(inputObjectType, null, coercedValues, locale);
}
if (nonExternalDefaultFields != null) {
for (GraphQLInputObjectField defaultField : nonExternalDefaultFields) {
ValuesResolverOneOfValidation.validateOneOfInputTypes(defaultField.getType(), coercedValues.get(defaultField.getName()), null, variableName, locale);
}
}
return coercedValues;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ static void validateOneOfInputTypes(GraphQLType type, Object inputValue, Value<?
}
}

private static void validateOneOfInputTypesInternal(GraphQLInputObjectType oneOfInputType, Value<?> argumentValue, Map<String, Object> objectMap, Locale locale) {
static void validateOneOfInputTypesInternal(GraphQLInputObjectType oneOfInputType, Value<?> argumentValue, Map<String, Object> objectMap, Locale locale) {
final String fieldName;
if (argumentValue instanceof ObjectValue) {
List<ObjectField> objectFields = ((ObjectValue) argumentValue).getObjectFields();
Expand Down
133 changes: 133 additions & 0 deletions src/test/groovy/graphql/execution/ValuesResolverTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,139 @@ class ValuesResolverTest extends Specification {
}


def nestedOneOfSdl = '''
input OneOf @oneOf { a: Int, b: Int, nested: OneOf }
input Level3 { leaf: OneOf, leaves: [OneOf] }
input Level2 { level3: Level3, level3s: [Level3] }
input Level1 { level2: Level2, other: Int }
type Query { f(arg: Level1, args: [Level1], oneOf: OneOf, oneOfs: [OneOf]): Boolean }
'''

@Unroll
def "getVariableValues: nested oneOf violations in variables are reported - #testCase"() {
given:
def schema = TestUtil.schema(nestedOneOfSdl)
VariableDefinition variableDefinition = new VariableDefinition("variable", variableType)

when:
ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale)

then:
def e = thrown(expectedException)
e.message == expectedMessage

where:
testCase | variableType | inputValue || expectedException | expectedMessage
"depth 3 too many keys" | new TypeName("Level1") | [level2: [level3: [leaf: [a: 1, b: 2]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"depth 3 null value" | new TypeName("Level1") | [level2: [level3: [leaf: [a: null]]]] || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null."
"depth 3 empty" | new TypeName("Level1") | [level2: [level3: [leaf: [:]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"oneOf nested in oneOf" | new TypeName("Level1") | [level2: [level3: [leaf: [nested: [nested: [a: 1, b: 2]]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"oneOf nested in oneOf null value" | new TypeName("OneOf") | [nested: [nested: [b: null]]] || OneOfNullValueException | "OneOf type field 'OneOf.b' must be non-null."
"list of oneOf inside non-oneOf parents" | new TypeName("Level1") | [level2: [level3: [leaves: [[a: 1], [a: 1, b: 2]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"list of parents containing oneOf" | new TypeName("Level1") | [level2: [level3s: [[leaf: [a: 1]], [leaf: [b: null]]]]] || OneOfNullValueException | "OneOf type field 'OneOf.b' must be non-null."
"top level list of parents" | new ListType(new TypeName("Level1")) | [[level2: [level3: [leaf: [a: 1]]]], [level2: [level3: [leaf: [:]]]]] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"single value coerced to list" | new ListType(new TypeName("OneOf")) | [a: 1, b: 2] || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"single value coerced to nested list" | new TypeName("Level1") | [level2: [level3s: [leaves: [a: null]]]] || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null."
}

def "getVariableValues: valid nested oneOf variables are accepted"() {
given:
def schema = TestUtil.schema(nestedOneOfSdl)
VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Level1"))
def inputValue = [level2: [level3: [leaf: [nested: [a: 1]], leaves: [[a: 1], [b: 2]]], level3s: [[leaves: [b: 3]]]], other: 1]

when:
def resolvedValues = ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale)

then:
resolvedValues.get('variable') == [level2: [level3: [leaf: [nested: [a: 1]], leaves: [[a: 1], [b: 2]]], level3s: [[leaves: [[b: 3]]]]], other: 1]
}

@Unroll
def "getVariableValues: error precedence between nested oneOf violations and sibling coercion errors - #testCase"() {
given:
def sdl = '''
input OneOf @oneOf { a: Int, b: Int }
input Parent { first: OneOf, second: Int, third: OneOf }
type Query { f(arg: Parent): Boolean }
'''
def schema = TestUtil.schema(sdl)
VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Parent"))

when:
ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: inputValue]), graphQLContext, locale)

then:
def e = thrown(GraphQLException)
e.class == expectedException

where:
testCase | inputValue || expectedException
"oneOf violation before bad sibling" | [first: [a: 1, b: 2], second: "notAnInt"] || OneOfTooManyKeysException
"bad sibling before oneOf violation" | [second: "notAnInt", third: [a: 1, b: 2]] || CoercingParseValueException
}

@Unroll
def "getVariableValues: oneOf violations in nested non-external default values are reported - #testCase"() {
given:
def oneOfType = newInputObject()
.name("OneOf")
.withAppliedDirective(Directives.OneOfDirective.toAppliedDirective())
.field(newInputObjectField().name("a").type(GraphQLInt))
.field(newInputObjectField().name("b").type(GraphQLInt))
.build()
def childField = newInputObjectField().name("child").type(oneOfType)
defaultSetter(childField)
def inner = newInputObject()
.name("Inner")
.field(childField)
.field(newInputObjectField().name("x").type(GraphQLInt))
.build()
def outer = newInputObject()
.name("Outer")
.field(newInputObjectField().name("inner").type(inner))
.build()
def schema = TestUtil.schemaWithInputType(outer)
VariableDefinition variableDefinition = new VariableDefinition("variable", new TypeName("Outer"))

when:
ValuesResolver.coerceVariableValues(schema, [variableDefinition], RawVariables.of([variable: [inner: [x: 1]]]), graphQLContext, locale)

then:
def e = thrown(expectedException)
e.message == expectedMessage

where:
testCase | defaultSetter || expectedException | expectedMessage
"internal default" | { it.defaultValue([a: 1, b: 2]) } || OneOfTooManyKeysException | "Exactly one key must be specified for OneOf type 'OneOf'."
"literal default" | { it.defaultValueLiteral(ObjectValue.newObjectValue().objectField(new ObjectField("a", NullValue.of())).build()) } || OneOfNullValueException | "OneOf type field 'OneOf.a' must be non-null."
}

def "getVariableValues: oneOf violations in nested external default values are reported"() {
given:
def oneOfType = newInputObject()
.name("OneOf")
.withAppliedDirective(Directives.OneOfDirective.toAppliedDirective())
.field(newInputObjectField().name("a").type(GraphQLInt))
.field(newInputObjectField().name("b").type(GraphQLInt))
.build()
def inner = newInputObject()
.name("Inner")
.field(newInputObjectField().name("child").type(oneOfType).defaultValueProgrammatic([a: 1, b: 2]))
.field(newInputObjectField().name("x").type(GraphQLInt))
.build()
def outer = newInputObject()
.name("Outer")
.field(newInputObjectField().name("inner").type(inner))
.build()

when: "the schema is built"
TestUtil.schemaWithInputType(outer)

then: "external defaults are coerced, and so oneOf validated, during schema validation"
thrown(OneOfTooManyKeysException)
}

class Person {
def name = ""
def id = 0
Expand Down
Loading