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
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ private CompletableFuture<List<FetchedValue>> fetchData(ExecutionContext executi
valuesFuture.completeExceptionally(e);
}
return valuesFuture
.thenApply((result) -> assertResult(parentResults, result))
.thenCompose((result) -> checkAndConvertResults(parentResults, result))
.whenComplete(fetchCtx::onEnd)
.handle(handleResult(executionContext, parameters, parentResults, fields, fieldDef, argumentValues, environment));
}
Expand Down Expand Up @@ -451,7 +451,7 @@ private BiFunction<List<Object>, Throwable, List<FetchedValue>> handleResult(Exe
};
}

private List<Object> assertResult(List<MapOrList> parentResults, Object result) {
private CompletableFuture<List<Object>> checkAndConvertResults(List<MapOrList> parentResults, Object result) {
result = convertPossibleArray(result);
if (result != null && !(result instanceof Iterable)) {
throw new BatchAssertionFailed(String.format("BatchedDataFetcher provided an invalid result: Iterable expected but got '%s'. Affected fields are set to null.", result.getClass().getName()));
Expand All @@ -462,13 +462,41 @@ private List<Object> assertResult(List<MapOrList> parentResults, Object result)
throw new BatchAssertionFailed("BatchedDataFetcher provided a null Iterable of result values. Affected fields are set to null.");
}
List<Object> resultList = new ArrayList<>();
iterableResult.forEach(resultList::add);

boolean foundFuture = false;

for (Object value : iterableResult) {
if (value instanceof CompletionStage) {
foundFuture = true;
}

resultList.add(value);
}

long size = resultList.size();
if (size != parentResults.size()) {
throw new BatchAssertionFailed(String.format("BatchedDataFetcher provided invalid number of result values, expected %d but got %d. Affected fields are set to null.", parentResults.size(), size));
}
return resultList;

// fast path if return values are plain objects, not CompletionStages
if (!foundFuture) {
return CompletableFuture.completedFuture(resultList);
}

List<CompletableFuture<?>> futures = new ArrayList<>();

for (Object value : resultList) {
if (value instanceof CompletionStage) {
CompletionStage<?> completionStage = (CompletionStage<?>) value;
futures.add(completionStage.toCompletableFuture());
}
else {
futures.add(CompletableFuture.completedFuture(value));
}
}

return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(toList()));
}

private Object convertPossibleArray(Object result) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package graphql.execution.batched;

import graphql.Scalars;
import graphql.schema.GraphQLInterfaceType;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLTypeReference;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class AsyncTypeResolverSchema {

public GraphQLSchema createSchema() {
GraphQLObjectType foo = GraphQLObjectType.newObject()
.name("Foo")
.withInterface(new GraphQLTypeReference("Node"))
.field(field -> field
.name("id")
.type(Scalars.GraphQLID))
.build();

GraphQLInterfaceType node = GraphQLInterfaceType.newInterface()
.name("Node")
.field(field -> field
.name("id")
.type(Scalars.GraphQLID))
.typeResolver((env) -> {
if (env.getObject() instanceof CompletionStage) {
throw new RuntimeException("TypeResolver received CompletionStage as environment object, this should not happen");
}

return foo;
})
.build();

GraphQLObjectType query = GraphQLObjectType.newObject()
.name("RootQuery")
.field(field -> field
.name("node")
.dataFetcher(env ->
CompletableFuture.supplyAsync(() -> {
Map<String, String> map = new HashMap<>();
map.put("id", "abc");
return map;
}))
.type(node))
.build();

return GraphQLSchema.newSchema()
.query(query)
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package graphql.execution.batched

import graphql.ExceptionWhileDataFetching
import graphql.ExecutionInput
import graphql.ExecutionResult
import graphql.GraphQL
import graphql.execution.AsyncExecutionStrategy
Expand Down Expand Up @@ -400,4 +401,68 @@ class BatchedExecutionStrategyTest extends Specification {
runTest(query, expected)
}

def "Batching works with CompletableFutures"() {
given:
String query = """
{
string(value: "test") {
futureOfList {
value
append(text: "X") {
value
}
}
listOfFutures {
value
append(text: "Y") {
value
}
}
append(text: "Z") {
value
futureOfList {
value
}
listOfFutures {
value
}
}
}
}"""
Map<String, Object> expected = [
"string": [
"futureOfList": [
"value": "testasync1",
"append": ["value": "testasync1X"]
],
"listOfFutures": [
"value": "testasync2",
"append": ["value": "testasync2Y"]
],
"append": [
"value": "testZ",
"futureOfList": ["value": "testZasync1"],
"listOfFutures": ["value": "testZasync2"]
]
]
]
expect:
runTest(query, expected)
}

def "TypeResolver works with Batching and CompletableFutures"() {
given:
GraphQL graphQL = GraphQL.newGraphQL(new AsyncTypeResolverSchema().createSchema())
.queryExecutionStrategy(new BatchedExecutionStrategy())
.build()

ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query("{node {id}}")
.build()

Map<String, Object> expected = ["node": ["id": "abc"]]
expect:
graphQL.execute(executionInput).data == expected
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

public class FunWithStringsSchemaFactory {
Expand Down Expand Up @@ -169,6 +170,32 @@ public Object get(DataFetchingEnvironment environment) {
}
});

factory.setFutureOfListFetcher(new DataFetcher() {
@Batched
@Override
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
List<String> retVal = new ArrayList<>();
for (String s: (List<String>) environment.getSource()) {
retVal.add(s + "async1");
}
return CompletableFuture.completedFuture(retVal);
}
});

factory.setListOfFuturesFetcher(new DataFetcher() {
@Batched
@Override
@SuppressWarnings("unchecked")
public Object get(DataFetchingEnvironment environment) {
List<CompletableFuture<String>> retVal = new ArrayList<>();
for (String s: (List<String>) environment.getSource()) {
retVal.add(CompletableFuture.completedFuture(s + "async2"));
}
return retVal;
}
});

return factory;

}
Expand Down Expand Up @@ -245,6 +272,16 @@ private static void splitSentence(String source, List<List<String>> sentence) {
return new LinkedHashSet<>(Arrays.asList(source, "end"));
};

private DataFetcher futureOfListFetcher = e -> {
String source = e.getSource();
return CompletableFuture.completedFuture(source + "async1");
};

private DataFetcher listOfFuturesFetcher = e -> {
String source = e.getSource();
return CompletableFuture.completedFuture(source + "async2");
};

private void setWordsAndLettersFetcher(DataFetcher fetcher) {
this.wordsAndLettersFetcher = fetcher;
}
Expand Down Expand Up @@ -273,6 +310,14 @@ private void setReturnBadList(DataFetcher fetcher) {
this.returnBadListFetcher = fetcher;
}

private void setFutureOfListFetcher(DataFetcher fetcher) {
this.futureOfListFetcher = fetcher;
}

private void setListOfFuturesFetcher(DataFetcher fetcher) {
this.listOfFuturesFetcher = fetcher;
}

GraphQLSchema createSchema() {

GraphQLObjectType stringObjectType = GraphQLObjectType.newObject()
Expand Down Expand Up @@ -354,6 +399,16 @@ GraphQLSchema createSchema() {
.type(Scalars.GraphQLString))
.dataFetcher(optionalFetcher))

.field(GraphQLFieldDefinition.newFieldDefinition()
.name("futureOfList")
.type(new GraphQLTypeReference("StringObject"))
.dataFetcher(futureOfListFetcher))

.field(GraphQLFieldDefinition.newFieldDefinition()
.name("listOfFutures")
.type(new GraphQLTypeReference("StringObject"))
.dataFetcher(listOfFuturesFetcher))

.build();


Expand Down