Skip to content

Commit

Permalink
Watermarked response backpressure helidon-io#3136
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Kec <daniel.kec@oracle.com>
  • Loading branch information
danielkec committed Oct 3, 2022
1 parent 50548e8 commit 295b054
Show file tree
Hide file tree
Showing 19 changed files with 761 additions and 235 deletions.
18 changes: 17 additions & 1 deletion docs/se/webserver/02_configuration.adoc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
///////////////////////////////////////////////////////////////////////////////

Copyright (c) 2018, 2020 Oracle and/or its affiliates.
Copyright (c) 2018, 2022 Oracle and/or its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -85,6 +85,22 @@ Available socket configuration options:
|`enabled` |`true` |boolean |A socket can be disabled through configuration, in which case it is never opened
|`max-chunk-size` | `8192` |int |Maximal size of a chunk to read from incoming requests
|`max-payload-size` | `-1` |long |Maximal size of a request payload in bytes. If exceeded a 413 error is returned. Negative value means no limit.
|`backpressure-buffer-size` |long |`5242880` |Set a maximum length of the unflushed response data sending buffer can keep without applying backpressure.
Depends on `backpressure-policy` what happens if max buffer size is reached.
Default is `5*1024*1024` - 5Mb
|`backpressure-policy` | String | `LINEAR` |Sets the strategy for applying backpressure to the reactive stream
of response data.
* LINEAR - Data chunks are requested one-by-one after previous data chunk has been written to Netty's buffer, when
`backpressure-buffer-size` watermark is reached, new chunks are not requested until buffer size decrease under
the watermark value.
* PREFETCH - After first data chunk arrives, expected number of chunks needed to fill the buffer up
to watermark is calculated and requested.
* AUTO_FLUSH - Data are requested one-by-one, in case buffer reaches watermark, no other data is requested and extra flush is initiated.
* UNBOUNDED - No backpressure is applied, Long.MAX_VALUE(unbounded) is requested from upstream.
Default is `LINEAR`
|`validate-headers` |`true` |boolean |Whether to validate header names, if they contain illegal characters.
|`initial-buffer-size` |`128` |int |Initial size of buffer used to parse HTTP line and headers
|`tls` |{nbsp} |Object |Configuration of TLS, please see our TLS example in repository
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
*
* 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
*
* http://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.helidon.microprofile.server;

import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import io.helidon.microprofile.tests.junit5.AddBean;
import io.helidon.microprofile.tests.junit5.AddConfig;
import io.helidon.microprofile.tests.junit5.AddExtension;
import io.helidon.microprofile.tests.junit5.DisableDiscovery;
import io.helidon.microprofile.tests.junit5.HelidonTest;

import org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.is;

@HelidonTest
@DisableDiscovery
@AddBean(StreamingOutputLeakTest.DownloadResource.class)
@AddExtension(ServerCdiExtension.class)
@AddExtension(JaxRsCdiExtension.class)
@AddExtension(CdiComponentProvider.class)
@AddConfig(key = "server.backpressure-buffer-size", value = "20971520")//20Mb
class StreamingOutputLeakTest {

private static final int SIZE10MB = 10 * 1024 * 1024;
private static final int SIZE = SIZE10MB;
private static final long NUMBER_OF_BUFS = 20;
private static final byte[] DATA_10MB = new byte[SIZE];

static {
Random r = new Random();
r.nextBytes(DATA_10MB);
}

/**
* Reproducer for issue #4643
*/
@Test
void streamingOutput(WebTarget target) throws IOException {

InputStream is = target.path("/download")
.request()
.get(InputStream.class);
long size = 0;
while (is.read() != -1) {
size++;
}
is.close();

// Make sure all data has been read
assertThat(size, is(NUMBER_OF_BUFS * SIZE));
}

@Path("/download")
public static class DownloadResource {

@GET
@Produces(MediaType.MULTIPART_FORM_DATA)
public Response getPayload(
@NotNull @QueryParam("fileName") String fileName) {
StreamingOutput fileStream = output -> {

// 2gb
for (int i = 0; i < NUMBER_OF_BUFS; i++) {
output.write(DATA_10MB);
output.flush();
}

};
return Response
.ok(fileStream, MediaType.MULTIPART_FORM_DATA)
.build();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2021 Oracle and/or its affiliates.
* Copyright (c) 2017, 2022 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -39,6 +39,7 @@
import io.helidon.common.reactive.Single;
import io.helidon.media.common.MediaContext;
import io.helidon.media.common.MediaSupport;
import io.helidon.webserver.BackpressureStrategy;
import io.helidon.webserver.BareRequest;
import io.helidon.webserver.BareResponse;
import io.helidon.webserver.Routing;
Expand Down Expand Up @@ -294,6 +295,11 @@ public Single<BareResponse> whenCompleted() {
return Single.create(completionStage);
}

@Override
public void backpressureStrategy(BackpressureStrategy backpressureStrategy) {
//noop
}

@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
Expand Down
23 changes: 18 additions & 5 deletions webserver/webserver/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,30 @@
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<id>tck-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*TckTest.java</include>
</includes>
</configuration>
</execution>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<includes>
<include>**/*TckTest.java</include>
</includes>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
*
* 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
*
* http://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.helidon.webserver;

import java.util.concurrent.Flow;

import io.helidon.webserver.ServerResponseSubscription.Unbounded;
import io.helidon.webserver.ServerResponseSubscription.WatermarkAutoFlush;
import io.helidon.webserver.ServerResponseSubscription.WatermarkLinear;
import io.helidon.webserver.ServerResponseSubscription.WatermarkPrefetch;

/**
* Strategy for applying backpressure to the reactive stream of response data.
*/
public enum BackpressureStrategy {
/**
* Data chunks are requested one-by-one after previous data chunk has been given to Netty for writing.
* When backpressure-buffer-size watermark is reached new chunks are not requested until buffer size
* decrease under the watermark value.
*/
LINEAR(1),
/**
* Data are requested one-by-one, in case buffer reaches watermark,
* no other data is requested and extra flush is initiated.
*/
AUTO_FLUSH(2),
/**
* After first data chunk arrives, expected number of chunks needed
* to fill the buffer up to watermark is calculated and requested.
*/
PREFETCH(3),
/**
* No backpressure is applied, Long.MAX_VALUE(unbounded) is requested from upstream.
*/
UNBOUNDED(4);

private final int type;

BackpressureStrategy(int type) {
this.type = type;
}

ServerResponseSubscription createSubscription(Flow.Subscription subscription,
long backpressureBufferSize) {
switch (type) {
case 1: return new WatermarkLinear(subscription, backpressureBufferSize);
case 2: return new WatermarkAutoFlush(subscription, backpressureBufferSize);
case 3: return new WatermarkPrefetch(subscription, backpressureBufferSize);
case 4: return new Unbounded(subscription);
default: throw new IllegalStateException("Unknown backpressure strategy.");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2020 Oracle and/or its affiliates.
* Copyright (c) 2017, 2022 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -58,6 +58,13 @@ void writeStatusAndHeaders(Http.ResponseStatus status, Map<String, List<String>>
*/
Single<BareResponse> whenCompleted();

/**
* Set the backpressure strategy used for requesting response data.
*
* @param backpressureStrategy strategy used for requesting response data
*/
void backpressureStrategy(BackpressureStrategy backpressureStrategy);

/**
* Each response is subscribed up to a single publisher and AFTER {@link #writeStatusAndHeaders(Http.ResponseStatus, Map)}
* method is called and returned.
Expand Down
Loading

0 comments on commit 295b054

Please sign in to comment.