Skip to content
Merged
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
22 changes: 22 additions & 0 deletions src/main/java/graphql/execution/Async.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

@Internal
public class Async {
Expand All @@ -20,6 +22,7 @@ public interface CFFactory<T, U> {

public static <U> CompletableFuture<List<U>> each(List<CompletableFuture<U>> futures) {
CompletableFuture<List<U>> overallResult = new CompletableFuture<>();

CompletableFuture
.allOf(futures.toArray(new CompletableFuture[futures.size()]))
.whenComplete((noUsed, exception) -> {
Expand Down Expand Up @@ -82,4 +85,23 @@ private static <T, U> void eachSequentiallyImpl(Iterator<T> iterator, CFFactory<
eachSequentiallyImpl(iterator, cfFactory, index + 1, tmpResult, overallResult);
});
}


/**
* Turns an object T into a CompletableFuture if its not already
*
* @param t - the object to check
* @param <T> for two
*
* @return a CompletableFuture
*/
public static <T> CompletableFuture<T> toCompletableFuture(T t) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good idea :-)

if (t instanceof CompletionStage) {
//noinspection unchecked
return ((CompletionStage<T>) t).toCompletableFuture();
} else {
return CompletableFuture.completedFuture(t);
}
}

}
9 changes: 3 additions & 6 deletions src/main/java/graphql/execution/ExecutionStrategy.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.stream.IntStream;

import static graphql.execution.ExecutionTypeInfo.newTypeInfo;
Expand Down Expand Up @@ -218,11 +217,7 @@ protected CompletableFuture<Object> fetchField(ExecutionContext executionContext
dataFetcher = instrumentation.instrumentDataFetcher(dataFetcher, instrumentationFieldFetchParams);
try {
Object fetchedValueRaw = dataFetcher.get(environment);
if (fetchedValueRaw instanceof CompletionStage) {
fetchedValue = ((CompletionStage) fetchedValueRaw).toCompletableFuture();
} else {
fetchedValue = CompletableFuture.completedFuture(fetchedValueRaw);
}
fetchedValue = Async.toCompletableFuture(fetchedValueRaw);
} catch (Exception e) {
fetchedValue = new CompletableFuture<>();
fetchedValue.completeExceptionally(e);
Expand Down Expand Up @@ -404,6 +399,8 @@ protected Object unboxPossibleOptional(Object result) {
/**
* Converts an object that is known to should be an Iterable into one
*
* @param result the result object
*
* @return an Iterable from that object
*
* @throws java.lang.ClassCastException if its not an Iterable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import graphql.ExecutionResultImpl;
import graphql.GraphQLException;
import graphql.PublicApi;
import graphql.execution.Async;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.ExecutionContext;
Expand Down Expand Up @@ -47,7 +48,6 @@
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.stream.IntStream;

Expand Down Expand Up @@ -160,6 +160,7 @@ private void executeImpl(ExecutionContext executionContext,

ExecutionNode finalCurNode = curNode;
Iterator<String> finalCurFieldNames = curFieldNames;

resolveField(executionContext, newParameters, fieldName, curNode)
.whenComplete((childNodes, exception) -> {
if (exception != null) {
Expand Down Expand Up @@ -201,6 +202,52 @@ private CompletableFuture<List<ExecutionNode>> resolveField(ExecutionContext exe

}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly moved this up in the file so its near where it gets called and tweaked the DF fetching to use the Async code

private CompletableFuture<List<FetchedValue>> fetchData(ExecutionContext executionContext,
ExecutionStrategyParameters parameters,
String fieldName,
ExecutionNode node,
GraphQLFieldDefinition fieldDef) {
GraphQLObjectType parentType = node.getType();
List<Field> fields = node.getFields().get(fieldName);
List<MapOrList> parentResults = node.getParentResults();

Map<String, Object> argumentValues = valuesResolver.getArgumentValues(
fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables());

GraphQLOutputType fieldType = fieldDef.getType();
DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector(executionContext, fieldType, fields);

DataFetchingEnvironment environment = newDataFetchingEnvironment(executionContext)
.source(node.getSources())
.arguments(argumentValues)
.fieldDefinition(fieldDef)
.fields(fields)
.fieldType(fieldDef.getType())
.fieldTypeInfo(parameters.typeInfo())
.parentType(parentType)
.selectionSet(fieldCollector)
.build();

Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationContext<Object> fetchCtx = instrumentation.beginFieldFetch(
new InstrumentationFieldFetchParameters(executionContext, fieldDef, environment)
);

CompletableFuture<Object> fetchedValue;
try {
BatchedDataFetcher dataFetcher = getDataFetcher(fieldDef);
Object fetchedValueRaw = dataFetcher.get(environment);
fetchedValue = Async.toCompletableFuture(fetchedValueRaw);
} catch (Exception e) {
fetchedValue = new CompletableFuture<>();
fetchedValue.completeExceptionally(e);
}
return fetchedValue
.thenApply((result) -> assertResult(parentResults, result))
.whenComplete(fetchCtx::onEnd)
.handle(handleResult(executionContext, parameters, parentResults, fields, fieldDef, argumentValues, environment));
}

private List<ExecutionNode> completeValues(ExecutionContext executionContext, GraphQLObjectType parentType,
List<FetchedValue> fetchedValues, String fieldName, List<Field> fields,
GraphQLOutputType fieldType, ExecutionTypeInfo typeInfo, Map<String, Object> argumentValues) {
Expand Down Expand Up @@ -373,56 +420,6 @@ private boolean isObject(GraphQLType type) {
type instanceof GraphQLUnionType;
}

@SuppressWarnings("unchecked")
private CompletableFuture<List<FetchedValue>> fetchData(ExecutionContext executionContext,
ExecutionStrategyParameters parameters,
String fieldName,
ExecutionNode node,
GraphQLFieldDefinition fieldDef) {
GraphQLObjectType parentType = node.getType();
List<Field> fields = node.getFields().get(fieldName);
List<MapOrList> parentResults = node.getParentResults();

Map<String, Object> argumentValues = valuesResolver.getArgumentValues(
fieldDef.getArguments(), fields.get(0).getArguments(), executionContext.getVariables());

GraphQLOutputType fieldType = fieldDef.getType();
DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector(executionContext, fieldType, fields);

DataFetchingEnvironment environment = newDataFetchingEnvironment(executionContext)
.source(node.getSources())
.arguments(argumentValues)
.fieldDefinition(fieldDef)
.fields(fields)
.fieldType(fieldDef.getType())
.fieldTypeInfo(parameters.typeInfo())
.parentType(parentType)
.selectionSet(fieldCollector)
.build();

Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationContext<Object> fetchCtx = instrumentation.beginFieldFetch(
new InstrumentationFieldFetchParameters(executionContext, fieldDef, environment)
);

CompletableFuture<Object> valuesFuture;
try {
Object rawValue = getDataFetcher(fieldDef).get(environment);
if (rawValue instanceof CompletionStage) {
valuesFuture = ((CompletionStage) rawValue).toCompletableFuture();
} else {
valuesFuture = CompletableFuture.completedFuture(rawValue);
}
} catch (Exception e) {
valuesFuture = new CompletableFuture<>();
valuesFuture.completeExceptionally(e);
}
return valuesFuture
.thenApply((result) -> assertResult(parentResults, result))
.whenComplete(fetchCtx::onEnd)
.handle(handleResult(executionContext, parameters, parentResults, fields, fieldDef, argumentValues, environment));
}

private BiFunction<List<Object>, Throwable, List<FetchedValue>> handleResult(ExecutionContext executionContext, ExecutionStrategyParameters parameters, List<MapOrList> parentResults, List<Field> fields, GraphQLFieldDefinition fieldDef, Map<String, Object> argumentValues, DataFetchingEnvironment environment) {
return (result, exception) -> {
if (exception != null) {
Expand Down
12 changes: 2 additions & 10 deletions src/main/java/graphql/execution/batched/UnbatchedDataFetcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

import static graphql.schema.DataFetchingEnvironmentBuilder.newDataFetchingEnvironment;

Expand All @@ -34,16 +33,9 @@ public CompletableFuture<List<Object>> get(DataFetchingEnvironment environment)

DataFetchingEnvironment singleEnv = newDataFetchingEnvironment(environment)
.source(source).build();
results.add(getResult(delegate.get(singleEnv)));
CompletableFuture<Object> cf = Async.toCompletableFuture(delegate.get(singleEnv));
results.add(cf);
}

return Async.each(results);
}

private CompletableFuture<Object> getResult(Object rawResult) {
if (!(rawResult instanceof CompletionStage)) {
return CompletableFuture.completedFuture(rawResult);
}
return ((CompletionStage) rawResult).toCompletableFuture();
}
}
1 change: 0 additions & 1 deletion src/test/groovy/graphql/execution/AsyncTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,4 @@ class AsyncTest extends Specification {
result.isDone()
result.get() == ['x', 'y', 'z']
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -400,4 +400,22 @@ class BatchedExecutionStrategyTest extends Specification {
runTest(query, expected)
}

def "#672-683 handles completable futures ok"() {

given:
String query = "{ string(value: \"test\"){ completableFuture } }"
Map<String, Object> expected = ["string": ["completableFuture": "completableFuture"]]
expect:
runTest(query, expected)
}

def "#672-683 handles completable futures ok in interfaces"() {

given:
String query = "{ interface { value } }"
Map<String, Object> expected = ["interface": ["value": "interfacesHandled"]]
expect:
runTest(query, expected)
}

}
Loading