diff --git a/src/main/java/graphql/execution/ExecutionContext.java b/src/main/java/graphql/execution/ExecutionContext.java index 702d475209..604bd318bd 100644 --- a/src/main/java/graphql/execution/ExecutionContext.java +++ b/src/main/java/graphql/execution/ExecutionContext.java @@ -20,6 +20,7 @@ import graphql.language.FragmentDefinition; import graphql.language.OperationDefinition; import graphql.normalized.ExecutableNormalizedOperation; +import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.util.FpKit; import graphql.util.LockKit; @@ -32,6 +33,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; @@ -78,6 +80,9 @@ public class ExecutionContext { private volatile DataLoaderDispatchStrategy dataLoaderDispatcherStrategy = DataLoaderDispatchStrategy.NO_OP; private final ResultNodesInfo resultNodesInfo = new ResultNodesInfo(); + // the sub fields of a merged field only depend on the object type (variables and fragments are fixed for an execution) + // so they are collected once rather than for every object in a list + private final Map> collectedSubFields = new ConcurrentHashMap<>(); private final EngineRunningState engineRunningState; private final Supplier>> allOperationsDirectives; @@ -409,6 +414,11 @@ public ResultNodesInfo getResultNodesInfo() { return resultNodesInfo; } + @Internal + public Map> getCollectedSubFields() { + return collectedSubFields; + } + @Internal public boolean hasIncrementalSupport() { GraphQLContext graphqlContext = getGraphQLContext(); diff --git a/src/main/java/graphql/execution/ExecutionStrategy.java b/src/main/java/graphql/execution/ExecutionStrategy.java index 06f52b9918..774458dabe 100644 --- a/src/main/java/graphql/execution/ExecutionStrategy.java +++ b/src/main/java/graphql/execution/ExecutionStrategy.java @@ -5,6 +5,7 @@ import graphql.EngineRunningState; import graphql.ExecutionResult; import graphql.ExecutionResultImpl; +import graphql.GraphQLContext; import graphql.GraphQLError; import graphql.Internal; import graphql.PublicSpi; @@ -12,6 +13,7 @@ import graphql.TrivialDataFetcher; import graphql.TypeMismatchError; import graphql.UnresolvedTypeError; +import graphql.execution.conditional.ConditionalNodeDecision; import graphql.execution.directives.QueryDirectives; import graphql.execution.directives.QueryDirectivesImpl; import graphql.execution.incremental.AlternativeCallContext; @@ -55,6 +57,7 @@ import java.util.OptionalInt; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; @@ -1043,19 +1046,7 @@ protected Object completeValueForEnum(ExecutionContext executionContext, Executi protected Object completeValueForObject(ExecutionContext executionContext, ExecutionStrategyParameters parameters, GraphQLObjectType resolvedObjectType, Object result) { ExecutionStepInfo executionStepInfo = parameters.getExecutionStepInfo(); - FieldCollectorParameters collectorParameters = newParameters() - .schema(executionContext.getGraphQLSchema()) - .objectType(resolvedObjectType) - .fragments(executionContext.getFragmentsByName()) - .variables(executionContext.getCoercedVariables().toMap()) - .graphQLContext(executionContext.getGraphQLContext()) - .build(); - - MergedSelectionSet subFields = fieldCollector.collectFields( - collectorParameters, - parameters.getField(), - executionContext.hasIncrementalSupport() - ); + MergedSelectionSet subFields = collectSubFields(executionContext, parameters.getField(), resolvedObjectType); ExecutionStepInfo newExecutionStepInfo = executionStepInfo.changeTypeWithPreservedNonNull(resolvedObjectType); @@ -1067,6 +1058,34 @@ protected Object completeValueForObject(ExecutionContext executionContext, Execu return executionContext.getQueryStrategy().executeObject(executionContext, newParameters); } + private MergedSelectionSet collectSubFields(ExecutionContext executionContext, MergedField field, GraphQLObjectType objectType) { + // deferred executions are captured per collection and a custom decision callback may not be deterministic + // so in those cases we always collect the fields + GraphQLContext graphQLContext = executionContext.getGraphQLContext(); + if (executionContext.hasIncrementalSupport() || (graphQLContext != null && graphQLContext.get(ConditionalNodeDecision.class) != null)) { + return collectSubFieldsImpl(executionContext, field, objectType); + } + Map byObjectType = executionContext.getCollectedSubFields().computeIfAbsent(field, k -> new ConcurrentHashMap<>()); + MergedSelectionSet subFields = byObjectType.get(objectType); + if (subFields == null) { + subFields = collectSubFieldsImpl(executionContext, field, objectType); + byObjectType.put(objectType, subFields); + } + return subFields; + } + + private MergedSelectionSet collectSubFieldsImpl(ExecutionContext executionContext, MergedField field, GraphQLObjectType objectType) { + FieldCollectorParameters collectorParameters = newParameters() + .schema(executionContext.getGraphQLSchema()) + .objectType(objectType) + .fragments(executionContext.getFragmentsByName()) + .variables(executionContext.getCoercedVariables().toMap()) + .graphQLContext(executionContext.getGraphQLContext()) + .build(); + + return fieldCollector.collectFields(collectorParameters, field, executionContext.hasIncrementalSupport()); + } + @SuppressWarnings("SameReturnValue") private Object handleCoercionProblem(ExecutionContext context, ExecutionStrategyParameters parameters, CoercingSerializeException e) { SerializationError error = new SerializationError(parameters.getPath(), e); diff --git a/src/test/groovy/graphql/execution/CollectedSubFieldsReuseTest.groovy b/src/test/groovy/graphql/execution/CollectedSubFieldsReuseTest.groovy new file mode 100644 index 0000000000..62de73f29c --- /dev/null +++ b/src/test/groovy/graphql/execution/CollectedSubFieldsReuseTest.groovy @@ -0,0 +1,210 @@ +package graphql.execution + +import graphql.ExecutionInput +import graphql.ExperimentalApi +import graphql.GraphQL +import graphql.TestUtil +import graphql.execution.conditional.ConditionalNodeDecision +import graphql.execution.conditional.ConditionalNodeDecisionEnvironment +import graphql.execution.instrumentation.Instrumentation +import graphql.execution.instrumentation.InstrumentationState +import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters +import graphql.language.Field +import graphql.schema.DataFetcher +import graphql.schema.GraphQLObjectType +import graphql.schema.TypeResolver +import graphql.schema.idl.RuntimeWiring +import spock.lang.Specification + +import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring + +/** + * The sub fields of a merged field are collected once per object type and reused for every object in the result + */ +class CollectedSubFieldsReuseTest extends Specification { + + def sdl = """ + type Query { + pets : [Pet] + dogs : [Dog] + } + interface Pet { + name : String + } + type Dog implements Pet { + name : String + bark : String + } + type Cat implements Pet { + name : String + meow : String + } + """ + + def pets = [ + [type: "Dog", name: "d1", bark: "woof1", meow: "x"], + [type: "Cat", name: "c1", bark: "x", meow: "meow1"], + [type: "Dog", name: "d2", bark: "woof2", meow: "x"], + [type: "Cat", name: "c2", bark: "x", meow: "meow2"], + ] + + ExecutionContext capturedContext + + GraphQL buildGraphQL() { + TypeResolver typeResolver = { env -> env.getSchema().getObjectType(((Map) env.getObject()).type as String) } + def runtimeWiring = RuntimeWiring.newRuntimeWiring() + .type(newTypeWiring("Query") + .dataFetcher("pets", { env -> pets } as DataFetcher) + .dataFetcher("dogs", { env -> pets.findAll { it.type == "Dog" } } as DataFetcher)) + .type(newTypeWiring("Pet").typeResolver(typeResolver)) + .build() + def instrumentation = new Instrumentation() { + @Override + ExecutionContext instrumentExecutionContext(ExecutionContext executionContext, InstrumentationExecutionParameters parameters, InstrumentationState state) { + capturedContext = executionContext + return executionContext + } + } + return TestUtil.graphQL(sdl, runtimeWiring).instrumentation(instrumentation).build() + } + + def "objects of different types in the same list get the fields for their own type"() { + def query = """ + { + pets { + name + ... on Dog { bark } + ... on Cat { meow } + } + } + """ + + when: + def er = buildGraphQL().execute(query) + + then: + er.errors.isEmpty() + er.data == [pets: [ + [name: "d1", bark: "woof1"], + [name: "c1", meow: "meow1"], + [name: "d2", bark: "woof2"], + [name: "c2", meow: "meow2"], + ]] + } + + def "aliased fields with different selections are collected separately"() { + def query = """ + { + a: dogs { name } + b: dogs { bark } + } + """ + + when: + def er = buildGraphQL().execute(query) + + then: + er.errors.isEmpty() + er.data == [ + a: [[name: "d1"], [name: "d2"]], + b: [[bark: "woof1"], [bark: "woof2"]], + ] + } + + def "fields merged from fragments keep all their sub selections"() { + def query = """ + { + dogs { name } + ... on Query { dogs { bark } } + } + """ + + when: + def er = buildGraphQL().execute(query) + + then: + er.errors.isEmpty() + er.data == [dogs: [[name: "d1", bark: "woof1"], [name: "d2", bark: "woof2"]]] + } + + def "sub fields are collected once per field and object type"() { + def query = """ + { + pets { + name + ... on Dog { bark } + } + } + """ + + when: + def er = buildGraphQL().execute(query) + + then: + er.errors.isEmpty() + def collected = capturedContext.getCollectedSubFields() + collected.size() == 1 + def byObjectType = collected.values().first() + byObjectType.keySet().collect { it.name }.toSet() == ["Dog", "Cat"].toSet() + byObjectType.find { GraphQLObjectType type, MergedSelectionSet set -> type.name == "Dog" }.value.getKeys() == ["name", "bark"] + byObjectType.find { GraphQLObjectType type, MergedSelectionSet set -> type.name == "Cat" }.value.getKeys() == ["name"] + } + + def "a custom conditional node decision is asked for every object"() { + def query = """ + { + dogs { + name + bark + } + } + """ + // this decision is not deterministic, so the collected fields must not be reused + def calls = 0 + ConditionalNodeDecision decision = new ConditionalNodeDecision() { + @Override + boolean shouldInclude(ConditionalNodeDecisionEnvironment env) { + def directivesContainer = env.getDirectivesContainer() + if (directivesContainer instanceof Field && directivesContainer.name == "bark") { + calls++ + return calls % 2 == 1 + } + return true + } + } + def ei = ExecutionInput.newExecutionInput(query) + .graphQLContext([(ConditionalNodeDecision.class): decision]) + .build() + + when: + def er = buildGraphQL().execute(ei) + + then: + er.errors.isEmpty() + er.data == [dogs: [[name: "d1", bark: "woof1"], [name: "d2"]]] + calls == 2 + capturedContext.getCollectedSubFields().isEmpty() + } + + def "collected fields are not reused when incremental support is enabled"() { + def query = """ + { + dogs { + name + bark + } + } + """ + def ei = ExecutionInput.newExecutionInput(query) + .graphQLContext([(ExperimentalApi.ENABLE_INCREMENTAL_SUPPORT): true]) + .build() + + when: + def er = buildGraphQL().execute(ei) + + then: + er.errors.isEmpty() + er.data == [dogs: [[name: "d1", bark: "woof1"], [name: "d2", bark: "woof2"]]] + capturedContext.getCollectedSubFields().isEmpty() + } +}