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

More performance optimizations #9076

Merged
merged 3 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
38 changes: 38 additions & 0 deletions core/src/main/java/io/micronaut/core/type/UnsafeExecutable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2017-2020 original 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 io.micronaut.core.type;

import io.micronaut.core.annotation.Internal;

/**
* A variation of {@link Executable} that exposes invoke method without arguments validation.
* @param <T> The declaring type
* @param <R> The result of the method call
* @author Denis Stepanov
* @since 4.0.0
*/
@Internal
public interface UnsafeExecutable<T, R> extends Executable<T, R> {

/**
* Invokes the method without the arguments validation.
*
* @param instance The instance. Nullable only if it's a static method call.
* @param arguments The arguments
* @return The result
*/
R invokeUnsafe(T instance, Object... arguments);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.execution.ExecutionFlow;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpMethod;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MutableHttpResponse;
Expand All @@ -31,7 +29,6 @@
import io.micronaut.http.server.netty.types.files.NettyStreamedFileCustomizableResponseType;
import io.micronaut.http.server.netty.types.files.NettySystemFileCustomizableResponseType;
import io.micronaut.http.server.types.files.FileCustomizableResponseType;
import io.micronaut.web.router.MethodBasedRouteMatch;
import io.micronaut.web.router.RouteMatch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderResult;
Expand Down Expand Up @@ -168,29 +165,8 @@ void handleException(Throwable cause) {
}

private boolean needsBody(RouteMatch<?> routeMatch) {
if (!routeMatch.getRouteInfo().isPermitsRequestBody()) {
return false;
}
if (routeMatch instanceof MethodBasedRouteMatch<?, ?> methodBasedRouteMatch) {
if (hasArg(methodBasedRouteMatch, HttpRequest.class)) {
// HttpRequest argument in the method
return true;
}
}
if (routeMatch.getRouteInfo().getBodyArgument().isPresent()) {
// Body argument in the method
return true;
}
// Not annotated body argument
return !routeMatch.isFulfilled();
return routeMatch.getRouteInfo().needsRequestBody() || !routeMatch.isFulfilled();
}

private static boolean hasArg(MethodBasedRouteMatch<?, ?> methodBasedRouteMatch, Class<?> type) {
for (Argument<?> argument : methodBasedRouteMatch.getArguments()) {
if (argument.getType() == type) {
return true;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ private void encodeHttpResponse(
Writable writable = (Writable) body;
writable.writeTo(outputStream, nettyRequest.getCharacterEncoding());
response.body(byteBuf);
if (!response.getContentType().isPresent()) {
if (response.getContentType().isEmpty()) {
response.getAttribute(HttpAttributes.ROUTE_INFO, RouteInfo.class).ifPresent((routeInfo) ->
response.contentType(routeExecutor.resolveDefaultResponseContentType(nettyRequest, routeInfo)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
import io.micronaut.web.router.RouteMatch;
import io.micronaut.web.router.Router;
import io.micronaut.web.router.UriRouteMatch;
import io.micronaut.web.router.exceptions.DuplicateRouteException;
import io.micronaut.web.router.exceptions.UnsatisfiedRouteException;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
Expand Down Expand Up @@ -168,14 +167,7 @@ public Optional<CoroutineHelper> getCoroutineHelper() {

@Nullable
UriRouteMatch<Object, Object> findRouteMatch(HttpRequest<?> httpRequest) {
UriRouteMatch<Object, Object> routeMatch = null;

List<UriRouteMatch<Object, Object>> uriRoutes = router.findAllClosest(httpRequest);
if (uriRoutes.size() > 1) {
throw new DuplicateRouteException(httpRequest.getPath(), uriRoutes);
} else if (uriRoutes.size() == 1) {
routeMatch = uriRoutes.get(0);
}
UriRouteMatch<Object, Object> routeMatch = router.findClosest(httpRequest);

if (routeMatch == null && httpRequest.getMethod().equals(HttpMethod.OPTIONS)) {
List<UriRouteMatch<Object, Object>> anyUriRoutes = router.findAny(httpRequest);
Expand Down Expand Up @@ -386,26 +378,9 @@ private boolean isSingle(RouteInfo<?> finalRoute, Class<?> bodyClass) {
(finalRoute.isAsync() || finalRoute.isSuspended() || Publishers.isSingle(bodyClass)));
}

private MutableHttpResponse<?> toMutableResponse(HttpResponse<?> message) {
MutableHttpResponse<?> mutableHttpResponse;
if (message instanceof MutableHttpResponse) {
mutableHttpResponse = (MutableHttpResponse<?>) message;
} else {
mutableHttpResponse = HttpResponse.status(message.code(), message.reason());
mutableHttpResponse.body(message.body());
message.getHeaders().forEach((name, value) -> {
for (String val : value) {
mutableHttpResponse.header(name, val);
}
});
mutableHttpResponse.getAttributes().putAll(message.getAttributes());
}
return mutableHttpResponse;
}

private ExecutionFlow<MutableHttpResponse<?>> fromImperativeExecute(HttpRequest<?> request, RouteInfo<?> routeInfo, Object body) {
if (body instanceof HttpResponse) {
MutableHttpResponse<?> outgoingResponse = toMutableResponse((HttpResponse<?>) body);
if (body instanceof HttpResponse<?> httpResponse) {
MutableHttpResponse<?> outgoingResponse = httpResponse.toMutableResponse();
final Argument<?> bodyArgument = routeInfo.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return fromPublisher(
Expand Down Expand Up @@ -531,8 +506,8 @@ private ExecutionFlow<MutableHttpResponse<?>> fromKotlinCoroutineExecute(HttpReq
Mono.fromCompletionStage(supplier)
.flatMap(obj -> {
MutableHttpResponse<?> response;
if (obj instanceof HttpResponse) {
response = toMutableResponse((HttpResponse<?>) obj);
if (obj instanceof HttpResponse<?> httpResponse) {
response = httpResponse.toMutableResponse();
final Argument<?> bodyArgument = routeInfo.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return processPublisherBody(request, response, routeInfo);
Expand Down Expand Up @@ -585,8 +560,8 @@ private CorePublisher<MutableHttpResponse<?>> fromReactiveExecute(HttpRequest<?>
return Flux.just(emptyResponse.get());
}
}
if (o instanceof HttpResponse) {
singleResponse = toMutableResponse((HttpResponse<?>) o);
if (o instanceof HttpResponse<?> httpResponse) {
singleResponse = httpResponse.toMutableResponse();
final Argument<?> bodyArgument = routeInfo.getReturnType() //Mono
.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT) //HttpResponse
.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT); //Mono
Expand All @@ -609,7 +584,7 @@ private CorePublisher<MutableHttpResponse<?>> fromReactiveExecute(HttpRequest<?>
// a response stream
Publisher<HttpResponse<?>> bodyPublisher = Publishers.convertPublisher(conversionService, body, Publisher.class);
Flux<MutableHttpResponse<?>> response = Flux.from(bodyPublisher)
.map(this::toMutableResponse);
.map(HttpResponse::toMutableResponse);
Argument<?> bodyArgument = typeArgument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return response.flatMap((resp) ->
Expand Down
21 changes: 21 additions & 0 deletions http/src/main/java/io/micronaut/http/HttpResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -428,4 +428,25 @@ default Cookies getCookies() {
default Optional<Cookie> getCookie(String name) {
throw new UnsupportedOperationException("Operation not supported on a " + this.getClass() + " response.");
}

/**
* Returns a mutable response based on this response.
* @return the mutable response
* @since 4.0.0
*/
default MutableHttpResponse<?> toMutableResponse() {
if (this instanceof MutableHttpResponse<?> mutableHttpResponse) {
Copy link
Member

Choose a reason for hiding this comment

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

just override it in MutableHttpResponse instead

Copy link
Member

Choose a reason for hiding this comment

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

oh i see you did that, remove this check then.

return mutableHttpResponse;
}
MutableHttpResponse<?> mutableHttpResponse = HttpResponse.status(code(), reason());
mutableHttpResponse.body(body());
getHeaders().forEach((name, value) -> {
for (String val : value) {
mutableHttpResponse.header(name, val);
}
});
mutableHttpResponse.getAttributes().putAll(getAttributes());
return mutableHttpResponse;
}

}
5 changes: 5 additions & 0 deletions http/src/main/java/io/micronaut/http/MutableHttpResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,9 @@ default MutableHttpResponse<B> status(HttpStatus status) {
default MutableHttpResponse<B> attribute(CharSequence name, Object value) {
return (MutableHttpResponse<B>) setAttribute(name, value);
}

@Override
default MutableHttpResponse<?> toMutableResponse() {
return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import io.micronaut.core.order.Ordered;
import io.micronaut.core.type.Argument;
import io.micronaut.core.type.Executable;
import io.micronaut.core.type.UnsafeExecutable;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MutableHttpRequest;
Expand Down Expand Up @@ -551,7 +552,12 @@ private ExecutionFlow<FilterContext> filter(FilterContext filterContext,
return ExecutionFlow.just(filterContext);
}
Object[] args = bindArgs(methodContext);
Object returnValue = method.invoke(bean, args);
Object returnValue;
if (method instanceof UnsafeExecutable<T, ?> unsafeExecutable) {
returnValue = unsafeExecutable.invokeUnsafe(bean, args);
} else {
returnValue = method.invoke(bean, args);
}
return returnHandler.handle(filterContext, returnValue, methodContext.continuation);
} catch (Throwable e) {
return ExecutionFlow.error(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.micronaut.core.annotation.UsedByGeneratedCode;
import io.micronaut.core.type.Argument;
import io.micronaut.core.type.ReturnType;
import io.micronaut.core.type.UnsafeExecutable;
import io.micronaut.core.util.ArgumentUtils;
import io.micronaut.core.util.ObjectUtils;
import io.micronaut.inject.ExecutableMethod;
Expand All @@ -43,7 +44,7 @@
* @since 1.0
*/
@Internal
public abstract class AbstractExecutableMethod extends AbstractExecutable implements ExecutableMethod, EnvironmentConfigurable {
public abstract class AbstractExecutableMethod extends AbstractExecutable implements UnsafeExecutable, ExecutableMethod, EnvironmentConfigurable {

private final ReturnType returnType;
private final Argument<?> genericReturnType;
Expand Down Expand Up @@ -163,6 +164,11 @@ public final Object invoke(Object instance, Object... arguments) {
return invokeInternal(instance, arguments);
}

@Override
public Object invokeUnsafe(Object instance, Object... arguments) {
return invokeInternal(instance, arguments);
}

/**
* @param instance The instance
* @param arguments The arguments
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.micronaut.core.reflect.ClassUtils;
import io.micronaut.core.type.Argument;
import io.micronaut.core.type.ReturnType;
import io.micronaut.core.type.UnsafeExecutable;
import io.micronaut.core.util.ArgumentUtils;
import io.micronaut.core.util.ObjectUtils;
import io.micronaut.inject.ExecutableMethod;
Expand Down Expand Up @@ -327,8 +328,7 @@ public String toString() {
* @param <R> The result type
*/
private static final class DispatchedExecutableMethod<T, R> implements ExecutableMethod<T, R>,
EnvironmentConfigurable,
BeanContextConfigurable {
EnvironmentConfigurable, BeanContextConfigurable, UnsafeExecutable<T, R> {

private final AbstractExecutableMethodsDefinition dispatcher;
private final int index;
Expand Down Expand Up @@ -442,6 +442,11 @@ public R invoke(T instance, Object... arguments) {
return (R) dispatcher.dispatch(index, instance, arguments);
}

@Override
public R invokeUnsafe(T instance, Object... arguments) {
return (R) dispatcher.dispatch(index, instance, arguments);
}

@Override
public boolean equals(Object o) {
if (this == o) {
Expand Down
Loading