diff --git a/src/main/java/graphql/execution/AsyncExecutionStrategy.java b/src/main/java/graphql/execution/AsyncExecutionStrategy.java index 27e24ace88..bbd4a9cf68 100644 --- a/src/main/java/graphql/execution/AsyncExecutionStrategy.java +++ b/src/main/java/graphql/execution/AsyncExecutionStrategy.java @@ -72,14 +72,14 @@ public CompletableFuture execute(ExecutionContext executionCont for (FieldValueInfo completeValueInfo : completeValueInfos) { fieldValuesFutures.addObject(completeValueInfo.getFieldValueObject()); } - dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesInfo(completeValueInfos, parameters); + dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesInfo(completeValueInfos); executionStrategyCtx.onFieldValuesInfo(completeValueInfos); fieldValuesFutures.await().whenComplete(handleResultsConsumer); }).exceptionally((ex) -> { // if there are any issues with combining/handling the field results, // complete the future at all costs and bubble up any thrown exception so // the execution does not hang. - dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesException(ex, parameters); + dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesException(ex); executionStrategyCtx.onFieldValuesException(); overallResult.completeExceptionally(ex); return null; diff --git a/src/main/java/graphql/execution/AsyncSerialExecutionStrategy.java b/src/main/java/graphql/execution/AsyncSerialExecutionStrategy.java index 6f64b8cd8c..fb871712da 100644 --- a/src/main/java/graphql/execution/AsyncSerialExecutionStrategy.java +++ b/src/main/java/graphql/execution/AsyncSerialExecutionStrategy.java @@ -32,7 +32,7 @@ public AsyncSerialExecutionStrategy(DataFetcherExceptionHandler exceptionHandler @Override @SuppressWarnings({"TypeParameterUnusedInFormals", "FutureReturnValueIgnored"}) public CompletableFuture execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException { - executionContext.getDataLoaderDispatcherStrategy().executionStrategy(executionContext, parameters); + DataLoaderDispatchStrategy dataLoaderDispatcherStrategy = executionContext.getDataLoaderDispatcherStrategy(); Instrumentation instrumentation = executionContext.getInstrumentation(); InstrumentationExecutionStrategyParameters instrumentationParameters = new InstrumentationExecutionStrategyParameters(executionContext, parameters); @@ -54,7 +54,8 @@ public CompletableFuture execute(ExecutionContext executionCont ResultPath fieldPath = parameters.getPath().segment(mkNameForPath(currentField)); ExecutionStrategyParameters newParameters = parameters .transform(builder -> builder.field(currentField).path(fieldPath)); - return resolveField(executionContext, newParameters); + + return resolveSerialField(executionContext, dataLoaderDispatcherStrategy, newParameters); }); CompletableFuture overallResult = new CompletableFuture<>(); @@ -65,4 +66,22 @@ public CompletableFuture execute(ExecutionContext executionCont return overallResult; } + private Object resolveSerialField(ExecutionContext executionContext, + DataLoaderDispatchStrategy dataLoaderDispatcherStrategy, + ExecutionStrategyParameters newParameters) { + dataLoaderDispatcherStrategy.executionSerialStrategy(executionContext, newParameters); + + Object fieldWithInfo = resolveFieldWithInfo(executionContext, newParameters); + if (fieldWithInfo instanceof CompletableFuture) { + //noinspection unchecked + return ((CompletableFuture) fieldWithInfo).thenCompose(fvi -> { + dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesInfo(List.of(fvi)); + return fvi.getFieldValueFuture(); + }); + } else { + FieldValueInfo fvi = (FieldValueInfo) fieldWithInfo; + dataLoaderDispatcherStrategy.executionStrategyOnFieldValuesInfo(List.of(fvi)); + return fvi.getFieldValueObject(); + } + } } diff --git a/src/main/java/graphql/execution/DataLoaderDispatchStrategy.java b/src/main/java/graphql/execution/DataLoaderDispatchStrategy.java index 9e21b94bfa..5101ae3a56 100644 --- a/src/main/java/graphql/execution/DataLoaderDispatchStrategy.java +++ b/src/main/java/graphql/execution/DataLoaderDispatchStrategy.java @@ -16,11 +16,15 @@ default void executionStrategy(ExecutionContext executionContext, ExecutionStrat } - default void executionStrategyOnFieldValuesInfo(List fieldValueInfoList, ExecutionStrategyParameters parameters) { + default void executionSerialStrategy(ExecutionContext executionContext, ExecutionStrategyParameters parameters) { } - default void executionStrategyOnFieldValuesException(Throwable t, ExecutionStrategyParameters parameters) { + default void executionStrategyOnFieldValuesInfo(List fieldValueInfoList) { + + } + + default void executionStrategyOnFieldValuesException(Throwable t) { } diff --git a/src/main/java/graphql/execution/Execution.java b/src/main/java/graphql/execution/Execution.java index cf805a84fb..2403e5294d 100644 --- a/src/main/java/graphql/execution/Execution.java +++ b/src/main/java/graphql/execution/Execution.java @@ -228,7 +228,7 @@ private DataLoaderDispatchStrategy createDataLoaderDispatchStrategy(ExecutionCon if (executionContext.getDataLoaderRegistry() == EMPTY_DATALOADER_REGISTRY || doNotAutomaticallyDispatchDataLoader) { return DataLoaderDispatchStrategy.NO_OP; } - if (executionStrategy instanceof AsyncExecutionStrategy) { + if (! executionContext.isSubscriptionOperation()) { boolean deferEnabled = Optional.ofNullable(executionContext.getGraphQLContext()) .map(graphqlContext -> graphqlContext.getBoolean(ExperimentalApi.ENABLE_INCREMENTAL_SUPPORT)) .orElse(false); diff --git a/src/main/java/graphql/execution/ExecutionContext.java b/src/main/java/graphql/execution/ExecutionContext.java index c122f9d2c3..ddb1fd6db8 100644 --- a/src/main/java/graphql/execution/ExecutionContext.java +++ b/src/main/java/graphql/execution/ExecutionContext.java @@ -170,6 +170,34 @@ public ValueUnboxer getValueUnboxer() { return valueUnboxer; } + /** + * @return true if the current operation is a Query + */ + public boolean isQueryOperation() { + return isOpType(OperationDefinition.Operation.QUERY); + } + + /** + * @return true if the current operation is a Mutation + */ + public boolean isMutationOperation() { + return isOpType(OperationDefinition.Operation.MUTATION); + } + + /** + * @return true if the current operation is a Subscription + */ + public boolean isSubscriptionOperation() { + return isOpType(OperationDefinition.Operation.SUBSCRIPTION); + } + + private boolean isOpType(OperationDefinition.Operation operation) { + if (operationDefinition != null) { + return operation.equals(operationDefinition.getOperation()); + } + return false; + } + /** * This method will only put one error per field path. * diff --git a/src/main/java/graphql/execution/instrumentation/dataloader/FallbackDataLoaderDispatchStrategy.java b/src/main/java/graphql/execution/instrumentation/dataloader/FallbackDataLoaderDispatchStrategy.java index dba4378046..f33657cb63 100644 --- a/src/main/java/graphql/execution/instrumentation/dataloader/FallbackDataLoaderDispatchStrategy.java +++ b/src/main/java/graphql/execution/instrumentation/dataloader/FallbackDataLoaderDispatchStrategy.java @@ -7,7 +7,7 @@ /** - * Used when the execution strategy is not an AsyncExecutionStrategy: simply dispatch always after each DF. + * Used when we cant guarantee the fields will be counted right: simply dispatch always after each DF. */ @Internal public class FallbackDataLoaderDispatchStrategy implements DataLoaderDispatchStrategy { diff --git a/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategy.java b/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategy.java index 60bd36e6f9..0d1903eaab 100644 --- a/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategy.java +++ b/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategy.java @@ -6,7 +6,6 @@ import graphql.execution.ExecutionContext; import graphql.execution.ExecutionStrategyParameters; import graphql.execution.FieldValueInfo; -import graphql.execution.MergedField; import graphql.schema.DataFetcher; import graphql.util.LockKit; import org.dataloader.DataLoaderRegistry; @@ -27,55 +26,81 @@ private static class CallStack { private final LockKit.ReentrantLock lock = new LockKit.ReentrantLock(); private final LevelMap expectedFetchCountPerLevel = new LevelMap(); private final LevelMap fetchCountPerLevel = new LevelMap(); - private final LevelMap expectedStrategyCallsPerLevel = new LevelMap(); - private final LevelMap happenedStrategyCallsPerLevel = new LevelMap(); + + private final LevelMap expectedExecuteObjectCallsPerLevel = new LevelMap(); + private final LevelMap happenedExecuteObjectCallsPerLevel = new LevelMap(); + private final LevelMap happenedOnFieldValueCallsPerLevel = new LevelMap(); private final Set dispatchedLevels = new LinkedHashSet<>(); public CallStack() { - expectedStrategyCallsPerLevel.set(1, 1); + expectedExecuteObjectCallsPerLevel.set(1, 1); } void increaseExpectedFetchCount(int level, int count) { expectedFetchCountPerLevel.increment(level, count); } + void clearExpectedFetchCount() { + expectedFetchCountPerLevel.clear(); + } + void increaseFetchCount(int level) { fetchCountPerLevel.increment(level, 1); } - void increaseExpectedStrategyCalls(int level, int count) { - expectedStrategyCallsPerLevel.increment(level, count); + void clearFetchCount() { + fetchCountPerLevel.clear(); + } + + void increaseExpectedExecuteObjectCalls(int level, int count) { + expectedExecuteObjectCallsPerLevel.increment(level, count); } - void increaseHappenedStrategyCalls(int level) { - happenedStrategyCallsPerLevel.increment(level, 1); + void clearExpectedObjectCalls() { + expectedExecuteObjectCallsPerLevel.clear(); + } + + void increaseHappenedExecuteObjectCalls(int level) { + happenedExecuteObjectCallsPerLevel.increment(level, 1); + } + + void clearHappenedExecuteObjectCalls() { + happenedExecuteObjectCallsPerLevel.clear(); } void increaseHappenedOnFieldValueCalls(int level) { happenedOnFieldValueCallsPerLevel.increment(level, 1); } - boolean allStrategyCallsHappened(int level) { - return happenedStrategyCallsPerLevel.get(level) == expectedStrategyCallsPerLevel.get(level); + void clearHappenedOnFieldValueCalls() { + happenedOnFieldValueCallsPerLevel.clear(); + } + + boolean allExecuteObjectCallsHappened(int level) { + return happenedExecuteObjectCallsPerLevel.get(level) == expectedExecuteObjectCallsPerLevel.get(level); } boolean allOnFieldCallsHappened(int level) { - return happenedOnFieldValueCallsPerLevel.get(level) == expectedStrategyCallsPerLevel.get(level); + return happenedOnFieldValueCallsPerLevel.get(level) == expectedExecuteObjectCallsPerLevel.get(level); } boolean allFetchesHappened(int level) { return fetchCountPerLevel.get(level) == expectedFetchCountPerLevel.get(level); } + void clearDispatchLevels() { + dispatchedLevels.clear(); + } + @Override public String toString() { return "CallStack{" + "expectedFetchCountPerLevel=" + expectedFetchCountPerLevel + ", fetchCountPerLevel=" + fetchCountPerLevel + - ", expectedStrategyCallsPerLevel=" + expectedStrategyCallsPerLevel + - ", happenedStrategyCallsPerLevel=" + happenedStrategyCallsPerLevel + + ", expectedExecuteObjectCallsPerLevel=" + expectedExecuteObjectCallsPerLevel + + ", happenedExecuteObjectCallsPerLevel=" + happenedExecuteObjectCallsPerLevel + ", happenedOnFieldValueCallsPerLevel=" + happenedOnFieldValueCallsPerLevel + ", dispatchedLevels" + dispatchedLevels + '}'; @@ -105,19 +130,23 @@ public void executeDeferredOnFieldValueInfo(FieldValueInfo fieldValueInfo, Execu @Override public void executionStrategy(ExecutionContext executionContext, ExecutionStrategyParameters parameters) { int curLevel = parameters.getExecutionStepInfo().getPath().getLevel() + 1; - increaseCallCounts(curLevel, parameters); + increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(curLevel, parameters); } @Override - public void executionStrategyOnFieldValuesInfo(List fieldValueInfoList, ExecutionStrategyParameters parameters) { - int curLevel = parameters.getPath().getLevel() + 1; - onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel, parameters); + public void executionSerialStrategy(ExecutionContext executionContext, ExecutionStrategyParameters parameters) { + resetCallStack(); + increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(1, 1); + } + + @Override + public void executionStrategyOnFieldValuesInfo(List fieldValueInfoList) { + onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, 1); } - public void executionStrategyOnFieldValuesException(Throwable t, ExecutionStrategyParameters executionStrategyParameters) { - int curLevel = executionStrategyParameters.getPath().getLevel() + 1; + public void executionStrategyOnFieldValuesException(Throwable t) { callStack.lock.runLocked(() -> - callStack.increaseHappenedOnFieldValueCalls(curLevel) + callStack.increaseHappenedOnFieldValueCalls(1) ); } @@ -125,13 +154,13 @@ public void executionStrategyOnFieldValuesException(Throwable t, ExecutionStrate @Override public void executeObject(ExecutionContext executionContext, ExecutionStrategyParameters parameters) { int curLevel = parameters.getExecutionStepInfo().getPath().getLevel() + 1; - increaseCallCounts(curLevel, parameters); + increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(curLevel, parameters); } @Override public void executeObjectOnFieldValuesInfo(List fieldValueInfoList, ExecutionStrategyParameters parameters) { int curLevel = parameters.getPath().getLevel() + 1; - onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel, parameters); + onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel); } @@ -143,16 +172,30 @@ public void executeObjectOnFieldValuesException(Throwable t, ExecutionStrategyPa ); } + private void increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(int curLevel, ExecutionStrategyParameters executionStrategyParameters) { + increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(curLevel, executionStrategyParameters.getFields().size()); + } - private void increaseCallCounts(int curLevel, ExecutionStrategyParameters executionStrategyParameters) { - int fieldCount = executionStrategyParameters.getFields().size(); + private void increaseHappenedExecuteObjectAndIncreaseExpectedFetchCount(int curLevel, int fieldCount) { callStack.lock.runLocked(() -> { + callStack.increaseHappenedExecuteObjectCalls(curLevel); callStack.increaseExpectedFetchCount(curLevel, fieldCount); - callStack.increaseHappenedStrategyCalls(curLevel); }); } - private void onFieldValuesInfoDispatchIfNeeded(List fieldValueInfoList, int curLevel, ExecutionStrategyParameters parameters) { + private void resetCallStack() { + callStack.lock.runLocked(() -> { + callStack.clearDispatchLevels(); + callStack.clearExpectedObjectCalls(); + callStack.clearExpectedFetchCount(); + callStack.clearFetchCount(); + callStack.clearHappenedExecuteObjectCalls(); + callStack.clearHappenedOnFieldValueCalls(); + callStack.expectedExecuteObjectCallsPerLevel.set(1, 1); + }); + } + + private void onFieldValuesInfoDispatchIfNeeded(List fieldValueInfoList, int curLevel) { boolean dispatchNeeded = callStack.lock.callLocked(() -> handleOnFieldValuesInfo(fieldValueInfoList, curLevel) ); @@ -166,18 +209,21 @@ private void onFieldValuesInfoDispatchIfNeeded(List fieldValueIn // private boolean handleOnFieldValuesInfo(List fieldValueInfos, int curLevel) { callStack.increaseHappenedOnFieldValueCalls(curLevel); - int expectedStrategyCalls = getCountForList(fieldValueInfos); - callStack.increaseExpectedStrategyCalls(curLevel + 1, expectedStrategyCalls); + int expectedOnObjectCalls = getObjectCountForList(fieldValueInfos); + callStack.increaseExpectedExecuteObjectCalls(curLevel + 1, expectedOnObjectCalls); return dispatchIfNeeded(curLevel + 1); } - private int getCountForList(List fieldValueInfos) { + /** + * the amount of (non nullable) objects that will require an execute object call + */ + private int getObjectCountForList(List fieldValueInfos) { int result = 0; for (FieldValueInfo fieldValueInfo : fieldValueInfos) { if (fieldValueInfo.getCompleteValueType() == FieldValueInfo.CompleteValueType.OBJECT) { result += 1; } else if (fieldValueInfo.getCompleteValueType() == FieldValueInfo.CompleteValueType.LIST) { - result += getCountForList(fieldValueInfo.getFieldValueInfos()); + result += getObjectCountForList(fieldValueInfo.getFieldValueInfos()); } } return result; @@ -221,7 +267,7 @@ private boolean levelReady(int level) { return callStack.allFetchesHappened(1); } if (levelReady(level - 1) && callStack.allOnFieldCallsHappened(level - 1) - && callStack.allStrategyCallsHappened(level) && callStack.allFetchesHappened(level)) { + && callStack.allExecuteObjectCallsHappened(level) && callStack.allFetchesHappened(level)) { return true; } diff --git a/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategyWithDeferAlwaysDispatch.java b/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategyWithDeferAlwaysDispatch.java index e81ef3948c..26c847b754 100644 --- a/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategyWithDeferAlwaysDispatch.java +++ b/src/main/java/graphql/execution/instrumentation/dataloader/PerLevelDataLoaderDispatchStrategyWithDeferAlwaysDispatch.java @@ -137,19 +137,17 @@ public void executeObject(ExecutionContext executionContext, ExecutionStrategyPa } @Override - public void executionStrategyOnFieldValuesInfo(List fieldValueInfoList, ExecutionStrategyParameters parameters) { + public void executionStrategyOnFieldValuesInfo(List fieldValueInfoList) { if (this.startedDeferredExecution.get()) { this.dispatch(); } - int curLevel = parameters.getPath().getLevel() + 1; - onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel, parameters); + onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, 1); } @Override - public void executionStrategyOnFieldValuesException(Throwable t, ExecutionStrategyParameters executionStrategyParameters) { - int curLevel = executionStrategyParameters.getPath().getLevel() + 1; + public void executionStrategyOnFieldValuesException(Throwable t) { callStack.lock.runLocked(() -> - callStack.increaseHappenedOnFieldValueCalls(curLevel) + callStack.increaseHappenedOnFieldValueCalls(1) ); } @@ -159,7 +157,7 @@ public void executeObjectOnFieldValuesInfo(List fieldValueInfoLi this.dispatch(); } int curLevel = parameters.getPath().getLevel() + 1; - onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel, parameters); + onFieldValuesInfoDispatchIfNeeded(fieldValueInfoList, curLevel); } @@ -207,7 +205,7 @@ private void increaseCallCounts(int curLevel, ExecutionStrategyParameters parame }); } - private void onFieldValuesInfoDispatchIfNeeded(List fieldValueInfoList, int curLevel, ExecutionStrategyParameters parameters) { + private void onFieldValuesInfoDispatchIfNeeded(List fieldValueInfoList, int curLevel) { boolean dispatchNeeded = callStack.lock.callLocked(() -> handleOnFieldValuesInfo(fieldValueInfoList, curLevel) ); diff --git a/src/test/groovy/graphql/MutationTest.groovy b/src/test/groovy/graphql/MutationTest.groovy index d99506880d..5c872b1f83 100644 --- a/src/test/groovy/graphql/MutationTest.groovy +++ b/src/test/groovy/graphql/MutationTest.groovy @@ -1,7 +1,14 @@ package graphql +import graphql.schema.DataFetcher +import org.awaitility.Awaitility +import org.dataloader.BatchLoader +import org.dataloader.BatchLoaderWithContext +import org.dataloader.DataLoaderFactory +import org.dataloader.DataLoaderRegistry import spock.lang.Specification +import java.util.concurrent.CompletableFuture class MutationTest extends Specification { @@ -102,4 +109,355 @@ class MutationTest extends Specification { executionResult.errors.every({ it instanceof ExceptionWhileDataFetching }) } + + def "simple async mutation"() { + def sdl = """ + type Query { + q : String + } + + type Mutation { + plus1(arg: Int) : Int + plus2(arg: Int) : Int + plus3(arg: Int) : Int + } + """ + + def mutationDF = { env -> + CompletableFuture.supplyAsync { + + def fieldName = env.getField().name + def factor = Integer.parseInt(fieldName.substring(fieldName.length() - 1)) + def value = env.getArgument("arg") + + return value + factor + } + } as DataFetcher + + def schema = TestUtil.schema(sdl, [Mutation: [ + plus1: mutationDF, + plus2: mutationDF, + plus3: mutationDF, + ]]) + + def graphQL = GraphQL.newGraphQL(schema).build() + + when: + def er = graphQL.execute(""" + mutation m { + plus1(arg:10) + plus2(arg:10) + plus3(arg:10) + } + """) + + then: + er.errors.isEmpty() + er.data == [ + plus1: 11, + plus2: 12, + plus3: 13, + ] + } + + def "simple async mutation with DataLoader"() { + def sdl = """ + type Query { + q : String + } + + type Mutation { + plus1(arg: Int) : Int + plus2(arg: Int) : Int + plus3(arg: Int) : Int + } + + """ + + BatchLoader batchLoader = { keys -> + CompletableFuture.supplyAsync { + return keys + } + + } as BatchLoader + + + DataLoaderRegistry dlReg = DataLoaderRegistry.newRegistry() + .register("dl", DataLoaderFactory.newDataLoader(batchLoader)) + .build() + + def mutationDF = { env -> + def fieldName = env.getField().name + def factor = Integer.parseInt(fieldName.substring(fieldName.length() - 1)) + def value = env.getArgument("arg") + + def key = value + factor + return env.getDataLoader("dl").load(key) + } as DataFetcher + + def schema = TestUtil.schema(sdl, [Mutation: [ + plus1: mutationDF, + plus2: mutationDF, + plus3: mutationDF, + ]]) + + + def graphQL = GraphQL.newGraphQL(schema) + .build() + + + def ei = ExecutionInput.newExecutionInput(""" + mutation m { + plus1(arg:10) + plus2(arg:10) + plus3(arg:10) + } + """).dataLoaderRegistry(dlReg).build() + when: + def er = graphQL.execute(ei) + + then: + er.errors.isEmpty() + er.data == [ + plus1: 11, + plus2: 12, + plus3: 13, + ] + } + + /* + This test shows a dataloader being called at the mutation field level, in serial via AsyncSerialExecutionStrategy, and then + again at the sub field level, in parallel, via AsyncExecutionStrategy. + */ + def "more complex async mutation with DataLoader"() { + def sdl = """ + type Query { + q : String + } + + type Mutation { + topLevelF1(arg: Int) : ComplexType + topLevelF2(arg: Int) : ComplexType + topLevelF3(arg: Int) : ComplexType + topLevelF4(arg: Int) : ComplexType + } + + type ComplexType { + f1 : ComplexType + f2 : ComplexType + f3 : ComplexType + f4 : ComplexType + end : String + } + """ + + def emptyComplexMap = [ + f1: null, + f2: null, + f3: null, + f4: null, + ] + + BatchLoaderWithContext fieldBatchLoader = { keys, context -> + assert keys.size() == 2, "since only f1 and f2 are DL based, we will only get 2 key values" + + def batchValue = [ + emptyComplexMap, + emptyComplexMap, + ] + CompletableFuture.supplyAsync { + return batchValue + } + + } as BatchLoaderWithContext + + BatchLoader mutationBatchLoader = { keys -> + CompletableFuture.supplyAsync { + return keys + } + + } as BatchLoader + + + DataLoaderRegistry dlReg = DataLoaderRegistry.newRegistry() + .register("topLevelDL", DataLoaderFactory.newDataLoader(mutationBatchLoader)) + .register("fieldDL", DataLoaderFactory.newDataLoader(fieldBatchLoader)) + .build() + + def mutationDF = { env -> + def fieldName = env.getField().name + def factor = Integer.parseInt(fieldName.substring(fieldName.length() - 1)) + def value = env.getArgument("arg") + + def key = value + factor + return env.getDataLoader("topLevelDL").load(key) + } as DataFetcher + + def fieldDataLoaderDF = { env -> + def fieldName = env.getField().name + def level = env.getExecutionStepInfo().getPath().getLevel() + return env.getDataLoader("fieldDL").load(fieldName, level) + } as DataFetcher + + def fieldDataLoaderNonDF = { env -> + return emptyComplexMap + } as DataFetcher + + def schema = TestUtil.schema(sdl, + [Mutation : [ + topLevelF1: mutationDF, + topLevelF2: mutationDF, + topLevelF3: mutationDF, + topLevelF4: mutationDF, + ], + // only f1 and f3 are using data loaders - f2 and f4 are plain old property based + // so some fields with batch loader and some without + ComplexType: [ + f1: fieldDataLoaderDF, + f2: fieldDataLoaderNonDF, + f3: fieldDataLoaderDF, + f4: fieldDataLoaderNonDF, + ] + ]) + + + def graphQL = GraphQL.newGraphQL(schema) + .build() + + + def ei = ExecutionInput.newExecutionInput(""" + mutation m { + topLevelF1(arg:10) { + f1 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f2 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f3 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f4 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + } + + topLevelF2(arg:10) { + f1 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f2 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f3 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f4 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + } + + topLevelF3(arg:10) { + f1 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f2 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f3 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f4 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + } + + topLevelF4(arg:10) { + f1 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f2 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f3 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + f4 { + f1 { end } + f2 { end } + f3 { end } + f4 { end } + } + } + } + """).dataLoaderRegistry(dlReg).build() + when: + def cf = graphQL.executeAsync(ei) + + Awaitility.await().until { cf.isDone() } + def er = cf.join() + + then: + + er.errors.isEmpty() + + def expectedMap = [ + f1: [f1: [end: null], f2: [end: null], f3: [end: null], f4: [end: null]], + f2: [f1: [end: null], f2: [end: null], f3: [end: null], f4: [end: null]], + f3: [f1: [end: null], f2: [end: null], f3: [end: null], f4: [end: null]], + f4: [f1: [end: null], f2: [end: null], f3: [end: null], f4: [end: null]], + ] + + er.data == [ + topLevelF1: expectedMap, + topLevelF2: expectedMap, + topLevelF3: expectedMap, + topLevelF4: expectedMap, + ] + } } diff --git a/src/test/groovy/graphql/execution/instrumentation/dataloader/DataLoaderDispatcherTest.groovy b/src/test/groovy/graphql/execution/instrumentation/dataloader/DataLoaderDispatcherTest.groovy index 839621f727..5ed01769f7 100644 --- a/src/test/groovy/graphql/execution/instrumentation/dataloader/DataLoaderDispatcherTest.groovy +++ b/src/test/groovy/graphql/execution/instrumentation/dataloader/DataLoaderDispatcherTest.groovy @@ -20,8 +20,8 @@ import org.jetbrains.annotations.NotNull import org.reactivestreams.Publisher import reactor.core.publisher.Mono import spock.lang.Specification -import spock.lang.Unroll +import java.time.Duration import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionStage @@ -120,10 +120,10 @@ class DataLoaderDispatcherTest extends Specification { } - @Unroll - def "ensure DataLoaderDispatcher works for #executionStrategyName"() { + def "ensure DataLoaderDispatcher works for async serial execution strategy"() { given: + def executionStrategy = new AsyncSerialExecutionStrategy() def starWarsWiring = new StarWarsDataLoaderWiring() def dlRegistry = starWarsWiring.newDataLoaderRegistry() @@ -136,15 +136,12 @@ class DataLoaderDispatcherTest extends Specification { def asyncResult = graphql.executeAsync(newExecutionInput().query(query).dataLoaderRegistry(dlRegistry)) + Awaitility.await().atMost(Duration.ofMillis(200)).until { -> asyncResult.isDone() } def er = asyncResult.join() then: er.data == expectedQueryData - where: - executionStrategyName | executionStrategy || _ - "AsyncExecutionStrategy" | new AsyncSerialExecutionStrategy() || _ - "AsyncSerialExecutionStrategy" | new AsyncSerialExecutionStrategy() || _ } def "basic batch loading is possible"() {