Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance optimizations: cache executor, optimize HttpMethod enum #9063

Merged
merged 4 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -106,18 +106,19 @@ protected final void multipartEnabled(boolean multipartEnabled) {
protected final ExecutionFlow<MutableHttpResponse<?>> normalFlow() {
ServerRequestContext.set(request);

MediaType contentType = request.getContentType().orElse(null);
if (!multipartEnabled &&
contentType != null &&
if (!multipartEnabled) {
MediaType contentType = request.getContentType().orElse(null);
if (contentType != null &&
contentType.equals(MediaType.MULTIPART_FORM_DATA_TYPE)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Multipart uploads have been disabled via configuration. Rejected request for URI {}, method {}, and content type {}", request.getUri(),
request.getMethodName(), contentType);
if (LOG.isDebugEnabled()) {
LOG.debug("Multipart uploads have been disabled via configuration. Rejected request for URI {}, method {}, and content type {}", request.getUri(),
request.getMethodName(), contentType);
}
return onStatusError(
HttpResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE),
"Content Type [" + contentType + "] not allowed"
);
}
return onStatusError(
HttpResponse.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE),
"Content Type [" + contentType + "] not allowed"
);
}

UriRouteMatch<Object, Object> routeMatch = routeExecutor.findRouteMatch(request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,38 +420,37 @@ private ExecutionFlow<MutableHttpResponse<?>> fromImperativeExecute(HttpRequest<

ExecutionFlow<MutableHttpResponse<?>> callRoute(ContextView contextFromFilter, RouteMatch<?> routeMatch, HttpRequest<?> request) {
RouteInfo<?> routeInfo = routeMatch.getRouteInfo();
ExecutorService executorService = findExecutor(routeInfo);
Supplier<ExecutionFlow<MutableHttpResponse<?>>> flowSupplier = () -> executeRouteAndConvertBody(routeMatch, request);
ExecutorService executorService = routeInfo.getExecutor(serverConfiguration.getThreadSelection());
ExecutionFlow<MutableHttpResponse<?>> executeMethodResponseFlow;
if (executorService != null) {
if (routeInfo.isSuspended()) {
executeMethodResponseFlow = ReactiveExecutionFlow.fromPublisher(Mono.deferContextual(contextView -> {
coroutineHelper.ifPresent(helper -> helper.setupCoroutineContext(request, contextView));
return Mono.from(
ReactiveExecutionFlow.fromFlow(flowSupplier.get()).toPublisher()
ReactiveExecutionFlow.fromFlow(executeRouteAndConvertBody(routeMatch, request)).toPublisher()
);
}).contextWrite(contextFromFilter))
.putInContext(ServerRequestContext.KEY, request);
} else if (routeInfo.isReactive()) {
executeMethodResponseFlow = ReactiveExecutionFlow.async(executorService, flowSupplier)
executeMethodResponseFlow = ReactiveExecutionFlow.async(executorService, () -> executeRouteAndConvertBody(routeMatch, request))
.putInContext(ServerRequestContext.KEY, request);
} else {
executeMethodResponseFlow = ExecutionFlow.async(executorService, flowSupplier);
executeMethodResponseFlow = ExecutionFlow.async(executorService, () -> executeRouteAndConvertBody(routeMatch, request));
}
} else {
if (routeInfo.isSuspended()) {
executeMethodResponseFlow = ReactiveExecutionFlow.fromPublisher(Mono.deferContextual(contextView -> {
coroutineHelper.ifPresent(helper -> helper.setupCoroutineContext(request, contextView));
return Mono.from(
ReactiveExecutionFlow.fromFlow(flowSupplier.get()).toPublisher()
ReactiveExecutionFlow.fromFlow(executeRouteAndConvertBody(routeMatch, request)).toPublisher()
);
}).contextWrite(contextFromFilter))
.putInContext(ServerRequestContext.KEY, request);
} else if (routeInfo.isReactive()) {
executeMethodResponseFlow = ReactiveExecutionFlow.fromFlow(flowSupplier.get())
executeMethodResponseFlow = ReactiveExecutionFlow.fromFlow(executeRouteAndConvertBody(routeMatch, request))
.putInContext(ServerRequestContext.KEY, request);
} else {
executeMethodResponseFlow = flowSupplier.get();
executeMethodResponseFlow = executeRouteAndConvertBody(routeMatch, request);
}
}
return executeMethodResponseFlow;
Expand Down Expand Up @@ -479,7 +478,7 @@ ExecutionFlow<MutableHttpResponse<?>> createResponseForBody(HttpRequest<?> reque
if (body == null) {
if (routeInfo.isVoid()) {
MutableHttpResponse<Object> data = forStatus(routeInfo);
if (HttpMethod.permitsRequestBody(request.getMethod())) {
if (request.getMethod().permitsRequestBody()) {
data.header(HttpHeaders.CONTENT_LENGTH, "0");
}
outgoingResponse = ExecutionFlow.just(data);
Expand Down
49 changes: 39 additions & 10 deletions http/src/main/java/io/micronaut/http/HttpMethod.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,52 +26,60 @@ public enum HttpMethod implements CharSequence {
/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2.
*/
OPTIONS,
OPTIONS(false, true),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3.
*/
GET,
GET(false, false),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4.
*/
HEAD,
HEAD(false, false),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5.
*/
POST,
POST(true, true),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6.
*/
PUT,
PUT(true, true),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7.
*/
DELETE,
DELETE(false, true),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8.
*/
TRACE,
TRACE(false, false),

/**
* See https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.9.
*/
CONNECT,
CONNECT(false, false),

/**
* See https://tools.ietf.org/html/rfc5789.
*/
PATCH,
PATCH(true, true),

/**
* A custom non-standard HTTP method.
*/
CUSTOM;
CUSTOM(false, true);

private final boolean requiresRequestBody;
private final boolean permitsRequestBody;

HttpMethod(boolean requiresRequestBody, boolean permisRequestBody) {
this.requiresRequestBody = requiresRequestBody;
this.permitsRequestBody = permisRequestBody;
}

@Override
public int length() {
Expand All @@ -88,6 +96,27 @@ public CharSequence subSequence(int start, int end) {
return name().subSequence(start, end);
}

/**
* Whether the given method requires a request body.
*
* @return Does the method require a request body.
* @since 4.0.0
*/
public boolean requiresRequestBody() {
return requiresRequestBody;
}


/**
* Whether the given method allows a request body.
*
* @return Does the method allows a request body.
* @since 4.0.0
*/
public boolean permitsRequestBody() {
return permitsRequestBody;
}

/**
* Whether the given method requires a request body.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public DefaultRequestBinderRegistry(ConversionService conversionService, List<Re

byType.put(Argument.of(HttpHeaders.class).typeHashCode(), (RequestArgumentBinder<HttpHeaders>) (argument, source) -> () -> Optional.of(source.getHeaders()));
byType.put(Argument.of(HttpRequest.class).typeHashCode(), (RequestArgumentBinder<HttpRequest<?>>) (argument, source) -> {
if (HttpMethod.permitsRequestBody(source.getMethod())) {
if (source.getMethod().permitsRequestBody()) {
Optional<Argument<?>> typeVariable = argument.getFirstTypeVariable()
.filter(arg -> arg.getType() != Object.class)
.filter(arg -> arg.getType() != Void.class);
Expand All @@ -118,7 +118,7 @@ public DefaultRequestBinderRegistry(ConversionService conversionService, List<Re
Optional<Argument<?>> typeVariable = argument.getFirstTypeVariable()
.filter(arg -> arg.getType() != Object.class)
.filter(arg -> arg.getType() != Void.class);
if (typeVariable.isPresent() && HttpMethod.permitsRequestBody(source.getMethod())) {
if (typeVariable.isPresent() && source.getMethod().permitsRequestBody()) {
if (source.getBody().isPresent()) {
return () -> Optional.of(new PushCapableFullHttpRequest((PushCapableHttpRequest) source, typeVariable.get()));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public Class<Body> getAnnotationType() {

@Override
public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?> source) {
if (!HttpMethod.permitsRequestBody(source.getMethod())) {
if (!source.getMethod().permitsRequestBody()) {
return BindingResult.unsatisfied();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?
Argument<T> argument = context.getArgument();
AnnotationMetadata annotationMetadata = argument.getAnnotationMetadata();

if (HttpMethod.permitsRequestBody(source.getMethod()) && !annotationMetadata.hasAnnotation(QueryValue.class)) {
if (source.getMethod().permitsRequestBody() && !annotationMetadata.hasAnnotation(QueryValue.class)) {
// During the unmatched check avoid requests that don't allow bodies
return BindingResult.unsatisfied();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
import io.micronaut.inject.BeanDefinition;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.inject.MethodExecutionHandle;
import io.micronaut.inject.MethodReference;
import io.micronaut.scheduling.executor.ExecutorSelector;
import io.micronaut.scheduling.executor.ThreadSelection;
import io.micronaut.web.router.exceptions.RoutingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -52,6 +55,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.function.Predicate;
import java.util.function.Supplier;

Expand All @@ -75,6 +79,7 @@ public abstract class DefaultRouteBuilder implements RouteBuilder {
protected final UriNamingStrategy uriNamingStrategy;
protected final ConversionService conversionService;
protected final Charset defaultCharset;
private final ExecutorSelector executorSelector;

private DefaultUriRoute currentParentRoute;
private final List<UriRoute> uriRoutes = new ArrayList<>();
Expand Down Expand Up @@ -110,8 +115,10 @@ public DefaultRouteBuilder(ExecutionHandleLocator executionHandleLocator, UriNam
if (executionHandleLocator instanceof ApplicationContext applicationContext) {
Environment environment = applicationContext.getEnvironment();
defaultCharset = environment.get("micronaut.application.default-charset", Charset.class, StandardCharsets.UTF_8);
this.executorSelector = applicationContext.findBean(ExecutorSelector.class).orElse(null);
} else {
defaultCharset = StandardCharsets.UTF_8;
this.executorSelector = null;
}
}

Expand Down Expand Up @@ -735,12 +742,13 @@ public int hashCode() {
/**
* The default route impl.
*/
class DefaultUriRoute extends AbstractRoute implements UriRoute {
final class DefaultUriRoute extends AbstractRoute implements UriRoute {
final String httpMethodName;
final HttpMethod httpMethod;
final UriMatchTemplate uriMatchTemplate;
final List<DefaultUriRoute> nestedRoutes = new ArrayList<>(2);
private Integer port;
private final RouteExecutorSelector executorSelector;

/**
* @param httpMethod The HTTP method
Expand Down Expand Up @@ -863,22 +871,25 @@ class DefaultUriRoute extends AbstractRoute implements UriRoute {
this.httpMethod = httpMethod;
this.uriMatchTemplate = uriTemplate;
this.httpMethodName = httpMethodName;
this.executorSelector = new RouteExecutorSelector();
}

@Override
public UriRouteInfo<Object, Object> toRouteInfo() {
return new DefaultUrlRouteInfo<>(
httpMethod,
uriMatchTemplate,
defaultCharset,
targetMethod,
bodyArgumentName,
bodyArgument,
consumesMediaTypes,
producesMediaTypes,
conditions,
port,
conversionService);
httpMethod,
uriMatchTemplate,
defaultCharset,
targetMethod,
bodyArgumentName,
bodyArgument,
consumesMediaTypes,
producesMediaTypes,
conditions,
port,
conversionService,
executorSelector
);
}

@Override
Expand Down Expand Up @@ -964,12 +975,32 @@ public UriMatchTemplate getUriMatchTemplate() {
public int compareTo(UriRoute o) {
return uriMatchTemplate.compareTo(o.getUriMatchTemplate());
}

private final class RouteExecutorSelector implements ExecutorSelector {
@Override
public Optional<ExecutorService> select(MethodReference<?, ?> method, ThreadSelection threadSelection) {
if (DefaultRouteBuilder.this.executorSelector != null) {
return DefaultRouteBuilder.this.executorSelector.select(targetMethod.getExecutableMethod(), threadSelection);
} else {
return Optional.empty();
}
}

@Override
public Optional<ExecutorService> select(String name) {
if (DefaultRouteBuilder.this.executorSelector != null) {
return DefaultRouteBuilder.this.executorSelector.select(name);
} else {
return Optional.empty();
}
}
}
}

/**
* Define a single route.
*/
class DefaultSingleRoute extends DefaultResourceRoute {
final class DefaultSingleRoute extends DefaultResourceRoute {

/**
* @param resourceRoutes The resource routes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@
import io.micronaut.http.annotation.Produces;
import io.micronaut.http.annotation.Status;
import io.micronaut.http.sse.Event;
import io.micronaut.scheduling.executor.ThreadSelection;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;

/**
* The default route info implementation.
Expand Down Expand Up @@ -284,6 +286,11 @@ public boolean isPermitsRequestBody() {
return isPermitsBody;
}

@Override
public ExecutorService getExecutor(ThreadSelection threadSelection) {
return null;
}

@Override
public AnnotationMetadata getAnnotationMetadata() {
return annotationMetadata;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ public <T, R> List<UriRouteMatch<T, R>> findAllClosest(@NonNull HttpRequest<?> r
uriRoutes = mostSpecific;
}
}
boolean permitsBody = HttpMethod.permitsRequestBody(request.getMethod());
boolean permitsBody = request.getMethod().permitsRequestBody();
int routeCount = uriRoutes.size();
if (routeCount > 1 && permitsBody) {
final MediaType contentType = request.getContentType().orElse(MediaType.ALL_TYPE);
Expand Down Expand Up @@ -533,7 +533,7 @@ public <T, R> List<UriRouteMatch<T, R>> findAny(HttpRequest<?> request) {

private List<UriRouteInfo<Object, Object>> findInternal(HttpRequest<?> request) {
String httpMethodName = request.getMethodName();
boolean permitsBody = HttpMethod.permitsRequestBody(request.getMethod());
boolean permitsBody = request.getMethod().permitsRequestBody();
final Collection<MediaType> acceptedProducedTypes = request.accept();
List<UriRouteInfo<Object, Object>> routes = routesByMethod.getOrDefault(httpMethodName, Collections.emptyList());
if (CollectionUtils.isEmpty(routes)) {
Expand Down
Loading