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

Improve POJA implementation #806

Merged
merged 4 commits into from
Oct 17, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.impl.io.DefaultHttpResponseWriter;
import org.apache.hc.core5.http.impl.io.SessionInputBufferImpl;
import org.apache.hc.core5.http.impl.io.SessionOutputBufferImpl;
import org.apache.hc.core5.http.io.SessionInputBuffer;
import org.apache.hc.core5.http.io.SessionOutputBuffer;

import java.io.IOException;
Expand All @@ -57,6 +59,7 @@ public class ApacheServerlessApplication
private final ExecutorService ioExecutor;
private final ByteBufferFactory<?, ?> byteBufferFactory;
private final ApacheServletConfiguration configuration;
private SessionInputBuffer sessionInputBuffer;

/**
* Default constructor.
Expand All @@ -82,14 +85,20 @@ protected void handleSingleRequest(
) throws IOException {
ApacheServletHttpResponse<?> response = new ApacheServletHttpResponse<>(conversionService);
try {
// The buffer is initialized only once
if (sessionInputBuffer == null) {
sessionInputBuffer = new SessionInputBufferImpl(configuration.inputBufferSize());
}
ApacheServletHttpRequest exchange = new ApacheServletHttpRequest<>(
in, conversionService, codecRegistry, ioExecutor, byteBufferFactory, response, configuration
in, sessionInputBuffer, conversionService, codecRegistry, ioExecutor, byteBufferFactory, response, configuration
);
servletHttpHandler.service(exchange);
} catch (ApacheServletBadRequestException e) {
response.status(HttpStatus.BAD_REQUEST);
response.contentType(MediaType.TEXT_PLAIN_TYPE);
response.getOutputStream().write(e.getMessage().getBytes());
writeResponse(response.getNativeResponse(), out);
throw e;
}
writeResponse(response.getNativeResponse(), out);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import io.micronaut.http.cookie.Cookies;
import io.micronaut.http.poja.PojaHttpRequest;
import io.micronaut.http.poja.apache.exception.ApacheServletBadRequestException;
import io.micronaut.http.poja.exception.NoPojaRequestException;
import io.micronaut.http.poja.util.MultiValueHeaders;
import io.micronaut.http.poja.util.MultiValuesQueryParameters;
import io.micronaut.http.simple.cookies.SimpleCookies;
Expand All @@ -42,7 +43,7 @@
import org.apache.hc.core5.http.impl.io.ChunkedInputStream;
import org.apache.hc.core5.http.impl.io.ContentLengthInputStream;
import org.apache.hc.core5.http.impl.io.DefaultHttpRequestParser;
import org.apache.hc.core5.http.impl.io.SessionInputBufferImpl;
import org.apache.hc.core5.http.io.SessionInputBuffer;
import org.apache.hc.core5.http.io.entity.EmptyInputStream;
import org.apache.hc.core5.net.URIBuilder;

Expand Down Expand Up @@ -94,6 +95,7 @@ public final class ApacheServletHttpRequest<B> extends PojaHttpRequest<B, Classi
*/
public ApacheServletHttpRequest(
InputStream inputStream,
SessionInputBuffer sessionInputBuffer,
ConversionService conversionService,
MediaTypeCodecRegistry codecRegistry,
ExecutorService ioExecutor,
Expand All @@ -102,16 +104,16 @@ public ApacheServletHttpRequest(
ApacheServletConfiguration configuration
) {
super(conversionService, codecRegistry, response);

SessionInputBufferImpl sessionInputBuffer
= new SessionInputBufferImpl(configuration.inputBufferSize());
DefaultHttpRequestParser parser = new DefaultHttpRequestParser();

try {
request = parser.parse(sessionInputBuffer, inputStream);
} catch (HttpException | IOException e) {
throw new ApacheServletBadRequestException("HTTP request could not be parsed", e);
}
if (request == null) {
throw new NoPojaRequestException();
}

method = HttpMethod.parse(request.getMethod());
try {
Expand Down Expand Up @@ -140,7 +142,7 @@ public ApacheServletHttpRequest(
* @param sessionInputBuffer The input buffer
* @return The body stream
*/
private InputStream createBodyStream(InputStream inputStream, long contentLength, SessionInputBufferImpl sessionInputBuffer) {
private InputStream createBodyStream(InputStream inputStream, long contentLength, SessionInputBuffer sessionInputBuffer) {
InputStream bodyStream;
if (contentLength > 0) {
bodyStream = new ContentLengthInputStream(sessionInputBuffer, inputStream, contentLength);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.micronaut.http.poja

import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification
import spock.lang.Stepwise

@Stepwise
@MicronautTest
class SimpleServerFailedParseSpec extends Specification {

@Inject
SimpleServerSpec.StringTestingClient client

void "test non-parseable GET method"() {
when:
var response = client.exchange(SimpleServerSpec.unindent("""
GET /test HTTP/1.1error\r
Host: h\r
\r
"""))

then:
response == SimpleServerSpec.unindent("""
HTTP/1.1 400 Bad Request\r
Content-Length: 32\r
Content-Type: text/plain\r
\r
HTTP request could not be parsed""")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,23 +54,6 @@ class SimpleServerSpec extends Specification {
{"_links":{"self":[{"href":"/invalid-test","templated":false}]},"_embedded":{"errors":[{"message":"Page Not Found"}]},"message":"Not Found"}""")
}

void "test non-parseable GET method"() {
when:
var response = client.exchange(unindent("""
GET /test HTTP/1.1error\r
Host: h\r
\r
"""))

then:
response == unindent("""
HTTP/1.1 400 Bad Request\r
Content-Length: 32\r
Content-Type: text/plain\r
\r
HTTP request could not be parsed""")
}

void "test DELETE method"() {
when:
var response = client.exchange(unindent("""
Expand Down Expand Up @@ -153,7 +136,7 @@ class SimpleServerSpec extends Specification {

}

private String unindent(String value, int indentSpaces = 8) {
static String unindent(String value, int indentSpaces = 8) {
while (value.charAt(0) == '\n' as char) {
value = value.substring(1)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import io.micronaut.context.ApplicationContext;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.poja.exception.NoPojaRequestException;
import io.micronaut.runtime.ApplicationConfiguration;
import io.micronaut.runtime.EmbeddedApplication;
import io.micronaut.servlet.http.ServletExchange;
Expand Down Expand Up @@ -90,6 +91,9 @@ protected ServletExchange<REQ, RES> createExchange(Object request, Object respon
runIndefinitely(servletHttpHandler, input, output);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoPojaRequestException e) {
this.stop();
Thread.currentThread().interrupt();
}
return this;
}
Expand All @@ -112,7 +116,7 @@ protected ServletExchange<REQ, RES> createExchange(Object request, Object respon
return start(System.in, System.out);
}
} catch (IOException e) {
throw new RuntimeException();
throw new RuntimeException(e);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2017-2024 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.http.poja.exception;

/**
* An exception to be thrown when no additional requests can be parsed.
* This can happen if the input stream is closed when waiting for a new request.
* This is not an error condition, therefore application can simply stop.
*/
public class NoPojaRequestException extends RuntimeException {

/**
* Constructor for the exception.
*/
public NoPojaRequestException() {
super("No new request was found in the input stream");
}

}
5 changes: 5 additions & 0 deletions test-sample-poja/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@ Hello, Micronaut Without Netty!

```

Alternatively redirect the input from a file:
```shell
gradle :micronaut-test-sample-poja:run --console=plain <test-sample-poja/test-request.txt
```

1 change: 1 addition & 0 deletions test-sample-poja/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ graalvmNative {
binaries.all {
buildArgs.add("--gc=serial")
buildArgs.add("--install-exit-handlers")
buildArgs.add("-Ob")
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.micronaut.http.poja.sample;

import io.micronaut.context.ApplicationContext;
import io.micronaut.runtime.Micronaut;

/**
Expand All @@ -26,7 +27,8 @@
public class Application {

public static void main(String[] args) {
Micronaut.run(Application.class, args);
ApplicationContext context = Micronaut.run(Application.class, args);
context.stop();
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestMethodOrder(MethodOrderer.MethodName.class)
public class SimpleServerTest {

@Inject
Expand Down
3 changes: 3 additions & 0 deletions test-sample-poja/test-request.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
GET / HTTP/1.1
Content-Length: 0

Loading