Skip to content
Closed
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
156 changes: 156 additions & 0 deletions src/jmh/java/benchmark/OneOfInputCoercionBenchmark.java
Original file line number Diff line number Diff line change
@@ -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<VariableDefinition> 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<String, PreparsedDocumentEntry> 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<String, Object> 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<String, Object> input = environment.getArgument("input");
int count = 0;
while (input != null) {
count += ((List<?>) input.get("values")).size();
input = (Map<String, Object>) 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<String, Object> inputValue() {
List<Map<String, Integer>> values = Collections.nCopies(VALUES_PER_LEVEL, Map.of("value", 1));
Map<String, Object> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public TraversalControl visitField(Field field, TraverserContext<Node> context)
GraphQLCodeRegistry codeRegistry = schema.getCodeRegistry();
Map<String, Object> argumentValues;
if (options.isCoerceFieldArguments()) {
argumentValues = ValuesResolver.getArgumentValues(codeRegistry,
argumentValues = ValuesResolver.getArgumentValues(schema, codeRegistry,
fieldDefinition.getArguments(),
field.getArguments(),
CoercedVariables.of(variables),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private static Supplier<ImmutableMapWithNullValues<String, Object>> getArgumentV
Supplier<ImmutableMapWithNullValues<String, Object>> argumentValues;
GraphQLCodeRegistry codeRegistry = executionContext.getGraphQLSchema().getCodeRegistry();
Supplier<ImmutableMapWithNullValues<String, Object>> argValuesSupplier = () -> {
Map<String, Object> resolvedValues = ValuesResolver.getArgumentValues(codeRegistry,
Map<String, Object> resolvedValues = ValuesResolver.getArgumentValues(executionContext.getGraphQLSchema(), codeRegistry,
fieldArgDefs,
fieldArgs,
executionContext.getCoercedVariables(),
Expand Down
21 changes: 18 additions & 3 deletions src/main/java/graphql/execution/ValuesResolver.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public static Map<String, Object> 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);
}

/**
Expand Down Expand Up @@ -207,7 +207,21 @@ public static Map<String, Object> 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<String, Object> getArgumentValues(
GraphQLSchema schema,
GraphQLCodeRegistry codeRegistry,
List<GraphQLArgument> argumentTypes,
List<Argument> arguments,
CoercedVariables coercedVariables,
GraphQLContext graphqlContext,
Locale locale
) {
InputInterceptor inputInterceptor = graphqlContext.get(InputInterceptor.class);
return getArgumentValuesImpl(schema, inputInterceptor, codeRegistry.getFieldVisibility(), argumentTypes, arguments, coercedVariables, graphqlContext, locale);
}

/**
Expand Down Expand Up @@ -319,6 +333,7 @@ public static <T> T getInputValueImpl(

@NonNull
private static Map<String, Object> getArgumentValuesImpl(
@Nullable GraphQLSchema schema,
InputInterceptor inputInterceptor,
GraphqlFieldVisibility fieldVisibility,
List<GraphQLArgument> argumentTypes,
Expand Down Expand Up @@ -375,7 +390,7 @@ private static Map<String, Object> getArgumentValuesImpl(
coercedValues.put(argumentName, value);
}

ValuesResolverOneOfValidation.validateOneOfInputTypes(argumentType, value, argumentValue, argumentName, locale);
ValuesResolverOneOfValidation.validateOneOfInputTypes(schema, argumentType, value, argumentValue, argumentName, locale);

}
}
Expand Down
25 changes: 24 additions & 1 deletion src/main/java/graphql/execution/ValuesResolverConversion.java
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ static CoercedVariables externalValueToInternalValueForVariables(
coercedValues.put(variableName, null);
} else {
Object coercedValue = externalValueToInternalValueImpl(
schema,
variableName,
inputInterceptor,
fieldVisibility,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -471,6 +486,7 @@ static Object externalValueToInternalValueImpl(
locale);
} else if (graphQLType instanceof GraphQLList) {
return externalValueToInternalValueForList(
schema,
inputInterceptor,
fieldVisibility,
(GraphQLList) graphQLType,
Expand All @@ -482,14 +498,15 @@ static Object externalValueToInternalValueImpl(
GraphQLInputObjectType inputObjectType = (GraphQLInputObjectType) graphQLType;
//noinspection unchecked
Map<String, Object> coercedMap = externalValueToInternalValueForObject(
schema,
inputInterceptor,
fieldVisibility,
inputObjectType,
(Map<String, Object>) value,
graphqlContext,
locale);

ValuesResolverOneOfValidation.validateOneOfInputTypes(inputObjectType, coercedMap, null, variableName, locale);
ValuesResolverOneOfValidation.validateOneOfInputTypes(schema, inputObjectType, coercedMap, null, variableName, locale);
return coercedMap;
} else {
throw CoercingParseValueException.newCoercingParseValueException()
Expand All @@ -506,6 +523,7 @@ static Object externalValueToInternalValueImpl(
* performs validation
*/
private static Map<String, Object> externalValueToInternalValueForObject(
@Nullable GraphQLSchema schema,
InputInterceptor inputInterceptor,
GraphqlFieldVisibility fieldVisibility,
GraphQLInputObjectType inputObjectType,
Expand Down Expand Up @@ -545,6 +563,8 @@ private static Map<String, Object> externalValueToInternalValueForObject(
coercedValues.put(fieldName, null);
} else {
value = externalValueToInternalValueImpl(
schema,
"externalValue",
inputInterceptor,
fieldVisibility,
fieldType,
Expand Down Expand Up @@ -592,6 +612,7 @@ private static Object externalValueToInternalValueForEnum(
* including validation
*/
private static List externalValueToInternalValueForList(
@Nullable GraphQLSchema schema,
InputInterceptor inputInterceptor,
GraphqlFieldVisibility fieldVisibility,
GraphQLList graphQLList,
Expand All @@ -605,6 +626,8 @@ private static List externalValueToInternalValueForList(
List<Object> list = FpKit.arrayListSizedTo(listOrSingletonList);
for (Object val : listOrSingletonList) {
list.add(externalValueToInternalValueImpl(
schema,
"externalValue",
inputInterceptor,
fieldVisibility,
wrappedType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,22 @@ public BiMap<GraphQLDirective, Directive> resolveDirectives(List<Directive> 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);
}
});
return ImmutableBiMap.copyOf(directiveMap);
}

private void buildArguments(GraphQLDirective.Builder directiveBuilder,
GraphQLSchema schema,
GraphQLCodeRegistry codeRegistry,
GraphQLDirective protoType,
Directive fieldDirective,
CoercedVariables variables,
GraphQLContext graphQLContext,
Locale locale) {
Map<String, Object> argumentValues = ValuesResolver.getArgumentValues(codeRegistry, protoType.getArguments(), fieldDirective.getArguments(), variables, graphQLContext, locale);
Map<String, Object> argumentValues = ValuesResolver.getArgumentValues(schema, codeRegistry, protoType.getArguments(), fieldDirective.getArguments(), variables, graphQLContext, locale);
directiveBuilder.clearArguments();
protoType.getArguments().forEach(protoArg -> {
if (argumentValues.containsKey(protoArg.getName())) {
Expand Down
Loading