Revise GraphQLRequestHandler

Rename to GraphQLService to make it more clear it is a layer below
the specific transport such as HTTP endpoints.

Add WebGraphQLService sub-interface for query execution in web
environment with a WebInterceptor chain.

See gh-42
This commit is contained in:
Rossen Stoyanchev
2021-04-09 08:43:57 +01:00
parent 0338607a9b
commit 4a18932941
13 changed files with 98 additions and 85 deletions

View File

@@ -34,11 +34,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.graphql.DefaultWebGraphQLRequestHandler;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.DefaultWebGraphQLService;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.webflux.GraphQLHttpHandler;
import org.springframework.graphql.webflux.GraphQLWebSocketHandler;
import org.springframework.http.MediaType;
@@ -65,18 +63,16 @@ public class WebFluxGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphQLRequestHandler<WebInput, WebOutput> graphQLRequestHandler(
GraphQL graphQL, ObjectProvider<WebInterceptor> interceptors) {
DefaultWebGraphQLRequestHandler handler = new DefaultWebGraphQLRequestHandler(graphQL);
public WebGraphQLService webGraphQLService(GraphQL graphQL, ObjectProvider<WebInterceptor> interceptors) {
DefaultWebGraphQLService handler = new DefaultWebGraphQLService(graphQL);
handler.setInterceptors(interceptors.orderedStream().collect(Collectors.toList()));
return handler;
}
@Bean
@ConditionalOnMissingBean
public GraphQLHttpHandler graphQLHandler(GraphQLRequestHandler<WebInput, WebOutput> requestHandler) {
return new GraphQLHttpHandler(requestHandler);
public GraphQLHttpHandler graphQLHandler(WebGraphQLService service) {
return new GraphQLHttpHandler(service);
}
@Bean
@@ -102,11 +98,10 @@ public class WebFluxGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphQLWebSocketHandler graphQLWebSocketHandler(
GraphQLRequestHandler<WebInput, WebOutput> handler, GraphQLProperties properties,
ServerCodecConfigurer configurer) {
WebGraphQLService service, GraphQLProperties properties, ServerCodecConfigurer configurer) {
return new GraphQLWebSocketHandler(
handler, configurer, properties.getWebsocket().getConnectionInitTimeout());
service, configurer, properties.getWebsocket().getConnectionInitTimeout());
}
@Bean

View File

@@ -38,11 +38,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.graphql.DefaultWebGraphQLRequestHandler;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.DefaultWebGraphQLService;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebInterceptor;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.webmvc.GraphQLHttpHandler;
import org.springframework.graphql.webmvc.GraphQLWebSocketHandler;
import org.springframework.http.HttpHeaders;
@@ -72,18 +70,16 @@ public class WebMvcGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphQLRequestHandler<WebInput, WebOutput> graphQLRequestHandler(
GraphQL graphQL, ObjectProvider<WebInterceptor> interceptors) {
DefaultWebGraphQLRequestHandler handler = new DefaultWebGraphQLRequestHandler(graphQL);
public WebGraphQLService webGraphQLService(GraphQL graphQL, ObjectProvider<WebInterceptor> interceptors) {
DefaultWebGraphQLService handler = new DefaultWebGraphQLService(graphQL);
handler.setInterceptors(interceptors.orderedStream().collect(Collectors.toList()));
return handler;
}
@Bean
@ConditionalOnMissingBean
public GraphQLHttpHandler graphQLHandler(GraphQLRequestHandler<WebInput, WebOutput> requestHandler) {
return new GraphQLHttpHandler(requestHandler);
public GraphQLHttpHandler graphQLHandler(WebGraphQLService service) {
return new GraphQLHttpHandler(service);
}
@Bean
@@ -111,8 +107,7 @@ public class WebMvcGraphQLAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GraphQLWebSocketHandler graphQLWebSocketHandler(
GraphQLRequestHandler<WebInput, WebOutput> handler, GraphQLProperties properties,
HttpMessageConverters converters) {
WebGraphQLService service, GraphQLProperties properties, HttpMessageConverters converters) {
HttpMessageConverter<?> converter = converters.getConverters().stream()
.filter(candidate -> candidate.canRead(Map.class, MediaType.APPLICATION_JSON))
@@ -120,7 +115,7 @@ public class WebMvcGraphQLAutoConfiguration {
.orElseThrow(() -> new IllegalStateException("No JSON converter"));
return new GraphQLWebSocketHandler(
handler, converter, properties.getWebsocket().getConnectionInitTimeout());
service, converter, properties.getWebsocket().getConnectionInitTimeout());
}
@Bean

View File

@@ -24,12 +24,12 @@ import graphql.ExecutionResult;
import reactor.core.publisher.Mono;
/**
* Base class for {@link GraphQLRequestHandler} implementations that supports
* customizations of request handling through a {@link WebInterceptor} chain.
* Sub-classes must implement {@link #handleInternal(ExecutionInput)} for the
* actual handling of the GraphQL query.
* Base class for {@link WebGraphQLService} implementations, providing support
* for customizations of the request through a {@link WebInterceptor} chain.
* Sub-classes must implement {@link #executeInternal(ExecutionInput)} to
* actually perform the GraphQL query.
*/
public abstract class AbstractWebGraphQLRequestHandler implements GraphQLRequestHandler<WebInput, WebOutput> {
public abstract class AbstractWebGraphQLService implements WebGraphQLService {
private final List<WebInterceptor> interceptors = new ArrayList<>();
@@ -52,9 +52,9 @@ public abstract class AbstractWebGraphQLRequestHandler implements GraphQLRequest
@Override
public final Mono<WebOutput> handle(WebInput input) {
public final Mono<WebOutput> execute(WebInput input) {
return preHandle(input)
.flatMap(executionInput -> Mono.fromFuture(handleInternal(executionInput)))
.flatMap(executionInput -> Mono.fromFuture(executeInternal(executionInput)))
.flatMap(executionResult -> postHandle(new WebOutput(input, executionResult, null)));
}
@@ -80,6 +80,6 @@ public abstract class AbstractWebGraphQLRequestHandler implements GraphQLRequest
* @param input the input to invoke {@link graphql.GraphQL} with
* @return the result from handling
*/
protected abstract CompletableFuture<ExecutionResult> handleInternal(ExecutionInput input);
protected abstract CompletableFuture<ExecutionResult> executeInternal(ExecutionInput input);
}

View File

@@ -22,21 +22,21 @@ import graphql.ExecutionResult;
import graphql.GraphQL;
/**
* Extension of {@link AbstractWebGraphQLRequestHandler} that simply delegates
* to {@link GraphQL}to execute the request.
* Extension of {@link AbstractWebGraphQLService} that executes GraphQL queries
* through the {@link GraphQL} instance it is configured with.
*/
public class DefaultWebGraphQLRequestHandler extends AbstractWebGraphQLRequestHandler {
public class DefaultWebGraphQLService extends AbstractWebGraphQLService {
private final GraphQL graphQL;
public DefaultWebGraphQLRequestHandler(GraphQL graphQL) {
public DefaultWebGraphQLService(GraphQL graphQL) {
this.graphQL = graphQL;
}
@Override
protected CompletableFuture<ExecutionResult> handleInternal(ExecutionInput input) {
protected CompletableFuture<ExecutionResult> executeInternal(ExecutionInput input) {
return this.graphQL.executeAsync(input);
}

View File

@@ -19,16 +19,19 @@ import graphql.ExecutionResult;
import reactor.core.publisher.Mono;
/**
* Contract to handle a GraphQL request.
* Contract to execute a GraphQL request.
*
* @param <I> the GraphQL query container along with any additional context
* depending on the environment in which the request is handled
* @param <O> the result of query execution and additional environment output
*/
@FunctionalInterface
public interface GraphQLRequestHandler<I extends RequestInput, O extends ExecutionResult> {
public interface GraphQLService<I extends RequestInput, O extends ExecutionResult> {
/**
* Handle the request and return the result of execution.
* Perform the request and return the result.
* @param input the GraphQL query container
* @return the execution result
*/
Mono<O> handle(I input);
Mono<O> execute(I input);
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
/**
* {@link GraphQLService} for executing GraphQL requests in a Web environment,
* over HTTP or WebSocket.
*/
public interface WebGraphQLService extends GraphQLService<WebInput, WebOutput> {
}

View File

@@ -22,9 +22,8 @@ import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebOutput;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
@@ -40,16 +39,16 @@ public class GraphQLHttpHandler {
new ParameterizedTypeReference<Map<String, Object>>() {};
private final GraphQLRequestHandler<WebInput, WebOutput> requestHandler;
private final WebGraphQLService graphQLService;
/**
* Create a new instance.
* @param requestHandler the handler to use for GraphQL query handling
* @param service for GraphQL query execution
*/
public GraphQLHttpHandler(GraphQLRequestHandler<WebInput, WebOutput> requestHandler) {
Assert.notNull(requestHandler, "GraphQLRequestHandler is required");
this.requestHandler = requestHandler;
public GraphQLHttpHandler(WebGraphQLService service) {
Assert.notNull(service, "WebGraphQLService is required");
this.graphQLService = service;
}
@@ -63,7 +62,7 @@ public class GraphQLHttpHandler {
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + webInput);
}
return this.requestHandler.handle(webInput);
return this.graphQLService.execute(webInput);
})
.flatMap(output -> {
Map<String, Object> spec = output.toSpecification();

View File

@@ -39,8 +39,7 @@ import org.springframework.core.codec.Decoder;
import org.springframework.core.codec.Encoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.WebSocketMessageInput;
import org.springframework.http.MediaType;
@@ -73,7 +72,7 @@ public class GraphQLWebSocketHandler implements WebSocketHandler {
ResolvableType.forType(new ParameterizedTypeReference<Map<String, Object>>() {});
private final GraphQLRequestHandler<WebInput, WebOutput> requestHandler;
private final WebGraphQLService graphQLService;
private final Decoder<?> decoder;
@@ -84,16 +83,16 @@ public class GraphQLWebSocketHandler implements WebSocketHandler {
/**
* Create a new instance.
* @param requestHandler the handler to use for GraphQL query handling
* @param service for GraphQL query execution
* @param configurer codec configurer for JSON encoding and decoding
* @param connectionInitTimeout the time within which the {@code CONNECTION_INIT}
* type message must be received.
*/
public GraphQLWebSocketHandler(GraphQLRequestHandler<WebInput, WebOutput> requestHandler,
ServerCodecConfigurer configurer, Duration connectionInitTimeout) {
public GraphQLWebSocketHandler(
WebGraphQLService service, ServerCodecConfigurer configurer, Duration connectionInitTimeout) {
Assert.notNull(requestHandler, "GraphQLRequestHandler is required");
this.requestHandler = requestHandler;
Assert.notNull(service, "WebGraphQLService is required");
this.graphQLService = service;
this.decoder = initDecoder(configurer);
this.encoder = initEncoder(configurer);
this.initTimeoutDuration = connectionInitTimeout;
@@ -165,7 +164,7 @@ public class GraphQLWebSocketHandler implements WebSocketHandler {
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);
}
return this.requestHandler.handle(input)
return this.graphQLService.execute(input)
.flatMapMany(output -> handleWebOutput(session, id, subscriptions, output))
.doOnTerminate(() -> subscriptions.remove(id));
case COMPLETE:

View File

@@ -25,9 +25,8 @@ import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebOutput;
import org.springframework.util.Assert;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.server.ServerWebInputException;
@@ -46,16 +45,16 @@ public class GraphQLHttpHandler {
new ParameterizedTypeReference<Map<String, Object>>() {};
private final GraphQLRequestHandler<WebInput, WebOutput> requestHandler;
private final WebGraphQLService graphQLService;
/**
* Create a new instance.
* @param requestHandler the handler to use for GraphQL query handling
* @param service for GraphQL query execution
*/
public GraphQLHttpHandler(GraphQLRequestHandler<WebInput, WebOutput> requestHandler) {
Assert.notNull(requestHandler, "GraphQLRequestHandler is required");
this.requestHandler = requestHandler;
public GraphQLHttpHandler(WebGraphQLService service) {
Assert.notNull(service, "WebGraphQLService is required");
this.graphQLService = service;
}
@@ -70,7 +69,7 @@ public class GraphQLHttpHandler {
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + webInput);
}
Mono<ServerResponse> responseMono = this.requestHandler.handle(webInput)
Mono<ServerResponse> responseMono = this.graphQLService.execute(webInput)
.map(output -> {
if (logger.isDebugEnabled()) {
logger.debug("Execution complete");

View File

@@ -41,8 +41,7 @@ import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import org.springframework.graphql.GraphQLRequestHandler;
import org.springframework.graphql.WebInput;
import org.springframework.graphql.WebGraphQLService;
import org.springframework.graphql.WebOutput;
import org.springframework.graphql.WebSocketMessageInput;
import org.springframework.http.HttpHeaders;
@@ -72,7 +71,7 @@ public class GraphQLWebSocketHandler extends TextWebSocketHandler implements Sub
Arrays.asList("graphql-transport-ws", "subscriptions-transport-ws");
private final GraphQLRequestHandler<WebInput, WebOutput> requestHandler;
private final WebGraphQLService service;
private final Duration initTimeoutDuration;
@@ -83,17 +82,17 @@ public class GraphQLWebSocketHandler extends TextWebSocketHandler implements Sub
/**
* Create a new instance.
* @param requestHandler the handler to use for GraphQL query handling
* @param service for GraphQL query execution
* @param converter for JSON encoding and decoding
* @param connectionInitTimeout the time within which the {@code CONNECTION_INIT}
* type message must be received.
*/
public GraphQLWebSocketHandler(
GraphQLRequestHandler<WebInput, WebOutput> requestHandler, HttpMessageConverter<?> converter,
Duration connectionInitTimeout) {
WebGraphQLService service, HttpMessageConverter<?> converter, Duration connectionInitTimeout) {
Assert.notNull(service, "WebGraphQLService is required");
Assert.notNull(converter, "HttpMessageConverter for JSON is required");
this.requestHandler = requestHandler;
this.service = service;
this.initTimeoutDuration = connectionInitTimeout;
this.converter = converter;
}
@@ -155,7 +154,7 @@ public class GraphQLWebSocketHandler extends TextWebSocketHandler implements Sub
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);
}
this.requestHandler.handle(input)
this.service.execute(input)
.flatMapMany(output -> handleWebOutput(session, input.requestId(), output))
.publishOn(sessionState.getScheduler()) // Serial blocking send via single thread
.subscribe(new SendMessageSubscriber(id, session, sessionState));

View File

@@ -40,9 +40,9 @@ import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link DefaultWebGraphQLRequestHandler}.
* Unit tests for {@link DefaultWebGraphQLService}.
*/
public class DefaultWebGraphQLRequestHandlerTests {
public class DefaultWebGraphQLServiceTests {
@Test
void testInterceptorInvocation() throws Exception {
@@ -64,10 +64,10 @@ public class DefaultWebGraphQLRequestHandlerTests {
Map body = mapper.reader().readValue("{\"query\": \"" + query + "\"}", Map.class);
WebInput webInput = new WebInput(URI.create("/graphql"), new HttpHeaders(), body);
DefaultWebGraphQLRequestHandler requestHandler = new DefaultWebGraphQLRequestHandler(createGraphQL());
DefaultWebGraphQLService requestHandler = new DefaultWebGraphQLService(createGraphQL());
requestHandler.setInterceptors(interceptors);
WebOutput webOutput = requestHandler.handle(webInput).block();
WebOutput webOutput = requestHandler.execute(webInput).block();
assertThat(sb.toString()).isEqualTo(":pre1:pre2:pre3:post3:post2:post1");
assertThat(webOutput.isDataPresent()).isTrue();

View File

@@ -42,7 +42,7 @@ import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.graphql.ConsumeOneAndNeverCompleteInterceptor;
import org.springframework.graphql.DefaultWebGraphQLRequestHandler;
import org.springframework.graphql.DefaultWebGraphQLService;
import org.springframework.graphql.GraphQLDataFetchers;
import org.springframework.graphql.WebInterceptor;
import org.springframework.http.HttpHeaders;
@@ -280,7 +280,7 @@ public class GraphQLWebSocketHandlerTests {
GraphQL graphQL = initGraphQL();
DefaultWebGraphQLRequestHandler requestHandler = new DefaultWebGraphQLRequestHandler(graphQL);
DefaultWebGraphQLService requestHandler = new DefaultWebGraphQLService(graphQL);
if (interceptors != null) {
requestHandler.setInterceptors(interceptors);
}

View File

@@ -37,7 +37,7 @@ import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import org.springframework.graphql.ConsumeOneAndNeverCompleteInterceptor;
import org.springframework.graphql.DefaultWebGraphQLRequestHandler;
import org.springframework.graphql.DefaultWebGraphQLService;
import org.springframework.graphql.GraphQLDataFetchers;
import org.springframework.graphql.WebInterceptor;
import org.springframework.http.HttpHeaders;
@@ -264,7 +264,7 @@ public class GraphQLWebSocketHandlerTests {
try {
GraphQL graphQL = initGraphQL();
DefaultWebGraphQLRequestHandler requestHandler = new DefaultWebGraphQLRequestHandler(graphQL);
DefaultWebGraphQLService requestHandler = new DefaultWebGraphQLService(graphQL);
if (interceptors != null) {
requestHandler.setInterceptors(interceptors);
}