index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/util/ScheduledBatchedProducer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*
* Original source licensed under the Apache License 2.0 by playframework.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs.util;
import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* A batched producer.
*
* Responds to read requests with batches of elements according to batch size. When eofOn is reached, it closes the
* channel.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
public class ScheduledBatchedProducer extends BatchedProducer {
private final ScheduledExecutorService executor;
private final long delay;
public ScheduledBatchedProducer(long eofOn, int batchSize, long sequence, ScheduledExecutorService executor, long delay) {
super(eofOn, batchSize, sequence, executor);
this.executor = executor;
this.delay = delay;
}
protected boolean complete;
@Override
public void read(final ChannelHandlerContext ctx) throws Exception {
executor.schedule(() -> {
for (int i = 0; i < batchSize && sequence != eofOn; i++) {
ctx.fireChannelRead(sequence++);
}
complete = eofOn == sequence;
executor.schedule(() -> {
if (complete) {
ctx.fireChannelInactive();
} else {
ctx.fireChannelReadComplete();
}
}, delay, TimeUnit.MILLISECONDS);
}, delay, TimeUnit.MILLISECONDS);
}
}
| 1,100 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/ServerCloseConnectionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.reactivex.Flowable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
/**
* Testing the scenario where the connection gets inactive without GOAWAY frame
*/
public class ServerCloseConnectionTest {
private static final Logger LOGGER = Logger.loggerFor(ServerCloseConnectionTest.class);
private SdkAsyncHttpClient netty;
private Server server;
@BeforeEach
public void setup() throws Exception {
server = new Server();
server.init();
netty = NettyNioAsyncHttpClient.builder()
.readTimeout(Duration.ofMillis(500))
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(3).build())
.protocol(Protocol.HTTP2)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
@AfterEach
public void teardown() throws InterruptedException {
if (server != null) {
server.shutdown();
}
server = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void connectionGetsInactive_shouldNotReuse() {
server.ackPingOnFirstChannel = true;
// The first request picks up a bad channel and should fail. Channel 1
CompletableFuture<Void> firstRequest = sendGetRequest();
assertThatThrownBy(() -> firstRequest.join())
.hasMessageContaining("An error occurred on the connection")
.hasCauseInstanceOf(IOException.class)
.hasRootCauseInstanceOf(ClosedChannelException.class);
server.failOnFirstChannel = false;
// The second request should establish a new connection instead of reusing the bad channel 2
LOGGER.info(() -> "sending out the second request");
sendGetRequest().join();
// should be 2 connections
assertThat(server.h2ConnectionCount.get()).isEqualTo(2);
}
private CompletableFuture<Void> sendGetRequest() {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.responseHandler(new SdkAsyncHttpResponseHandler() {
private SdkHttpResponse headers;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.headers = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
Flowable.fromPublisher(stream).forEach(b -> {
});
}
@Override
public void onError(Throwable error) {
}
})
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost")
.port(server.port())
.build())
.requestContentPublisher(new EmptyPublisher())
.build();
return netty.execute(req);
}
private static class Server extends ChannelInitializer<Channel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private String[] channelIds = new String[5];
private final NioEventLoopGroup group = new NioEventLoopGroup();
private SslContext sslCtx;
private AtomicInteger h2ConnectionCount = new AtomicInteger(0);
private boolean ackPingOnFirstChannel = false;
private boolean failOnFirstChannel = true;
void init() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
@Override
protected void initChannel(Channel ch) {
channelIds[h2ConnectionCount.get()] = ch.id().asShortText();
ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));
LOGGER.debug(() -> "init channel " + ch);
h2ConnectionCount.incrementAndGet();
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
Http2FrameCodec http2Codec = Http2FrameCodecBuilder.forServer()
// simulate not sending goaway
.decoupleCloseAndGoAway(true)
.initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(2))
.frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "WIRE"))
.build();
Http2MultiplexHandler http2Handler = new Http2MultiplexHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new MightCloseConnectionStreamFrameHandler());
}
});
pipeline.addLast(http2Codec);
pipeline.addLast(http2Handler);
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
serverSock.close();
}
public int port() {
return serverSock.localAddress().getPort();
}
private class MightCloseConnectionStreamFrameHandler extends SimpleChannelInboundHandler<Http2Frame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
// Not respond if this is channel 1
if (channelIds[0].equals(ctx.channel().parent().id().asShortText()) && failOnFirstChannel) {
ctx.channel().parent().close();
} else {
DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(false);
try {
LOGGER.info(() -> "return empty data " + ctx.channel() + " frame " + frame.getClass());
Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
ctx.write(dataFrame);
ctx.write(new DefaultHttp2HeadersFrame(headers, true));
ctx.flush();
} finally {
dataFrame.release();
}
}
}
}
}
}
}
| 1,101 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/DelegatingSslEngine.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
public class DelegatingSslEngine extends SSLEngine {
private final SSLEngine delegate;
public DelegatingSslEngine(SSLEngine delegate) {
this.delegate = delegate;
}
@Override
public SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst) throws SSLException {
return delegate.wrap(srcs, offset, length, dst);
}
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
return delegate.unwrap(src, dsts, offset, length);
}
@Override
public Runnable getDelegatedTask() {
return delegate.getDelegatedTask();
}
@Override
public void closeInbound() throws SSLException {
delegate.closeInbound();
}
@Override
public boolean isInboundDone() {
return delegate.isInboundDone();
}
@Override
public void closeOutbound() {
delegate.closeOutbound();
}
@Override
public boolean isOutboundDone() {
return delegate.isOutboundDone();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public String[] getEnabledCipherSuites() {
return delegate.getEnabledCipherSuites();
}
@Override
public void setEnabledCipherSuites(String[] suites) {
delegate.setEnabledCipherSuites(suites);
}
@Override
public String[] getSupportedProtocols() {
return delegate.getSupportedProtocols();
}
@Override
public String[] getEnabledProtocols() {
return delegate.getEnabledProtocols();
}
@Override
public void setEnabledProtocols(String[] protocols) {
delegate.setEnabledProtocols(protocols);
}
@Override
public SSLSession getSession() {
return delegate.getSession();
}
@Override
public void beginHandshake() throws SSLException {
delegate.beginHandshake();
}
@Override
public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
return delegate.getHandshakeStatus();
}
@Override
public void setUseClientMode(boolean mode) {
delegate.setUseClientMode(mode);
}
@Override
public boolean getUseClientMode() {
return delegate.getUseClientMode();
}
@Override
public void setNeedClientAuth(boolean need) {
delegate.setNeedClientAuth(need);
}
@Override
public boolean getNeedClientAuth() {
return delegate.getNeedClientAuth();
}
@Override
public void setWantClientAuth(boolean want) {
delegate.setWantClientAuth(want);
}
@Override
public boolean getWantClientAuth() {
return delegate.getWantClientAuth();
}
@Override
public void setEnableSessionCreation(boolean flag) {
delegate.setEnableSessionCreation(flag);
}
@Override
public boolean getEnableSessionCreation() {
return delegate.getEnableSessionCreation();
}
}
| 1,102 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/GoAwayTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2FrameReader;
import io.netty.handler.codec.http2.DefaultHttp2FrameWriter;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.Http2FrameAdapter;
import io.netty.handler.codec.http2.Http2FrameListener;
import io.netty.handler.codec.http2.Http2FrameReader;
import io.netty.handler.codec.http2.Http2FrameWriter;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.util.AttributeKey;
import io.reactivex.Flowable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.http.nio.netty.internal.http2.GoAwayException;
/**
* Tests to ensure that the client behaves as expected when it receives GOAWAY messages.
*/
public class GoAwayTest {
private SdkAsyncHttpClient netty;
private SimpleEndpointDriver endpointDriver;
@AfterEach
public void teardown() throws InterruptedException {
if (endpointDriver != null) {
endpointDriver.shutdown();
}
endpointDriver = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void goAwayCanCloseAllStreams() throws InterruptedException {
Set<String> serverChannels = ConcurrentHashMap.newKeySet();
CountDownLatch allRequestsReceived = new CountDownLatch(2);
Supplier<Http2FrameListener> frameListenerSupplier = () -> new TestFrameListener() {
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
private void onHeadersReadDelegator(ChannelHandlerContext ctx, int streamId) {
serverChannels.add(ctx.channel().id().asShortText());
Http2Headers outboundHeaders = new DefaultHttp2Headers()
.status("200")
.add("content-type", "text/plain")
.addInt("content-length", 5);
frameWriter().writeHeaders(ctx, streamId, outboundHeaders, 0, false, ctx.newPromise());
ctx.flush();
allRequestsReceived.countDown();
}
};
endpointDriver = new SimpleEndpointDriver(frameListenerSupplier);
endpointDriver.init();
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.build();
CompletableFuture<Void> request1 = sendGetRequest();
CompletableFuture<Void> request2 = sendGetRequest();
allRequestsReceived.await();
endpointDriver.channels.forEach(ch -> {
if (serverChannels.contains(ch.id().asShortText())) {
endpointDriver.goAway(ch, 0);
}
});
assertThatThrownBy(() -> request1.join())
.hasMessageContaining("GOAWAY received from service")
.hasCauseInstanceOf(GoAwayException.class);
assertThatThrownBy(() -> request2.join())
.hasMessageContaining("GOAWAY received from service")
.hasCauseInstanceOf(GoAwayException.class);
assertThat(endpointDriver.currentConnectionCount.get()).isEqualTo(0);
}
@Test
public void execute_goAwayReceived_existingChannelsNotReused() throws InterruptedException {
// Frame listener supplier for each connection
Supplier<Http2FrameListener> frameListenerSupplier = () -> new TestFrameListener() {
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
private void onHeadersReadDelegator(ChannelHandlerContext ctx, int streamId) {
frameWriter().writeHeaders(ctx, streamId, new DefaultHttp2Headers().add("content-length", "0").status("204"), 0, true, ctx.newPromise());
ctx.flush();
}
};
endpointDriver = new SimpleEndpointDriver(frameListenerSupplier);
endpointDriver.init();
netty = NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(1).build())
.protocol(Protocol.HTTP2)
.build();
sendGetRequest().join();
// Note: It's possible the initial request can cause the client to allocate more than 1 channel
int initialChannelNum = endpointDriver.channels.size();
// Send GOAWAY to all the currently open channels
endpointDriver.channels.forEach(ch -> endpointDriver.goAway(ch, 1));
// Need to give a chance for the streams to get closed
Thread.sleep(1000);
// Since the existing channels are now invalid, this request should cause a new channel to be opened
sendGetRequest().join();
assertThat(endpointDriver.channels).hasSize(initialChannelNum + 1);
}
// The client should not close streams that are less than the 'last stream
// ID' given in the GOAWAY frame since it means they were processed fully
@Test
public void execute_goAwayReceived_lastStreamId_lowerStreamsNotClosed() throws InterruptedException {
ConcurrentHashMap<String, Set<Integer>> channelToStreams = new ConcurrentHashMap<>();
CompletableFuture<Void> stream3Received = new CompletableFuture<>();
CountDownLatch allRequestsReceived = new CountDownLatch(2);
byte[] getPayload = "go away!".getBytes(StandardCharsets.UTF_8);
Supplier<Http2FrameListener> frameListenerSupplier = () -> new TestFrameListener() {
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) {
onHeadersReadDelegator(ctx, streamId);
}
private void onHeadersReadDelegator(ChannelHandlerContext ctx, int streamId) {
channelToStreams.computeIfAbsent(ctx.channel().id().asShortText(), (k) -> Collections.newSetFromMap(new ConcurrentHashMap<>())).add(streamId);
if (streamId == 3) {
stream3Received.complete(null);
}
if (streamId < 5) {
Http2Headers outboundHeaders = new DefaultHttp2Headers()
.status("200")
.add("content-type", "text/plain")
.addInt("content-length", getPayload.length);
frameWriter().writeHeaders(ctx, streamId, outboundHeaders, 0, false, ctx.newPromise());
ctx.flush();
}
allRequestsReceived.countDown();
}
};
endpointDriver = new SimpleEndpointDriver(frameListenerSupplier);
endpointDriver.init();
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.build();
CompletableFuture<Void> stream3Cf = sendGetRequest();// stream ID 3
// Wait for the request to be received just to ensure that it is given ID 3
stream3Received.join();
CompletableFuture<Void> stream5Cf = sendGetRequest();// stream ID 5
allRequestsReceived.await(10, TimeUnit.SECONDS);
// send the GOAWAY first, specifying that everything after 3 is not processed
endpointDriver.channels.forEach(ch -> {
Set<Integer> streams = channelToStreams.getOrDefault(ch.id().asShortText(), Collections.emptySet());
if (streams.contains(3)) {
endpointDriver.goAway(ch, 3);
}
});
// now send the DATA for stream 3, which should still be valid
endpointDriver.channels.forEach(ch -> {
Set<Integer> streams = channelToStreams.getOrDefault(ch.id().asShortText(), Collections.emptySet());
if (streams.contains(3)) {
endpointDriver.data(ch, 3, getPayload);
}
});
waitForFuture(stream3Cf);
waitForFuture(stream5Cf);
assertThat(stream3Cf.isCompletedExceptionally()).isFalse();
assertThat(stream5Cf.isCompletedExceptionally()).isTrue();
stream5Cf.exceptionally(e -> {
assertThat(e).isInstanceOf(IOException.class);
return null;
});
}
private CompletableFuture<Void> sendGetRequest() {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.responseHandler(new SdkAsyncHttpResponseHandler() {
private SdkHttpResponse headers;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.headers = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
// Consume the stream in order to complete request
Flowable.fromPublisher(stream).subscribe(b -> {}, t -> {});
}
@Override
public void onError(Throwable error) {
}
})
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("http")
.host("localhost")
.port(endpointDriver.port())
.build())
.requestContentPublisher(new EmptyPublisher())
.build();
return netty.execute(req);
}
private static void waitForFuture(CompletableFuture<?> cf) {
try {
cf.get(2, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException t) {
} catch (TimeoutException t) {
throw new RuntimeException("Future did not complete after 2 seconds.", t);
}
}
// Minimal class to simulate an H2 endpoint
private static class SimpleEndpointDriver extends ChannelInitializer<SocketChannel> {
private List<SocketChannel> channels = new ArrayList<>();
private final NioEventLoopGroup group = new NioEventLoopGroup();
private final Supplier<Http2FrameListener> frameListenerSupplier;
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private AtomicInteger currentConnectionCount = new AtomicInteger(0);
public SimpleEndpointDriver(Supplier<Http2FrameListener> frameListenerSupplier) {
this.frameListenerSupplier = frameListenerSupplier;
}
public void init() throws InterruptedException {
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(new NioEventLoopGroup())
.childHandler(this)
.childOption(ChannelOption.SO_KEEPALIVE, true);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
}
public int port() {
return serverSock.localAddress().getPort();
}
public void goAway(SocketChannel ch, int lastStreamId) {
ByteBuf b = ch.alloc().buffer(9 + 8);
// Frame header
b.writeMedium(8); // Payload length
b.writeByte(0x7); // Type = GOAWAY
b.writeByte(0x0); // Flags
b.writeInt(0); // 0 = connection frame
// GOAWAY payload
b.writeInt(lastStreamId);
b.writeInt(0); // Error code
ch.writeAndFlush(b);
}
public void data(SocketChannel ch, int streamId, byte[] payload) {
ByteBuf b = ch.alloc().buffer(9 + payload.length);
// Header
b.writeMedium(payload.length); // Payload length
b.writeByte(0); // Type = DATA
b.writeByte(0x1); // 0x1 = EOF
b.writeInt(streamId);
// Payload
b.writeBytes(payload);
ch.writeAndFlush(b);
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
channels.add(ch);
ch.pipeline().addLast(new Http2ConnHandler(this, frameListenerSupplier.get()));
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
currentConnectionCount.incrementAndGet();
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
currentConnectionCount.decrementAndGet();
super.channelInactive(ctx);
}
}
private abstract class TestFrameListener extends Http2FrameAdapter {
private final Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter();
protected final Http2FrameWriter frameWriter() {
return frameWriter;
}
@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
frameWriter().writeSettings(ctx, new Http2Settings(), ctx.newPromise());
frameWriter().writeSettingsAck(ctx, ctx.newPromise());
ctx.flush();
}
}
private static class Http2ConnHandler extends ChannelDuplexHandler {
// Prior knowledge preface
private static final String PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
private static final AttributeKey<Boolean> H2_ESTABLISHED = AttributeKey.newInstance("h2-etablished");
private final Http2FrameReader frameReader = new DefaultHttp2FrameReader();
private final SimpleEndpointDriver simpleEndpointDriver;
private final Http2FrameListener frameListener;
public Http2ConnHandler(SimpleEndpointDriver simpleEndpointDriver, Http2FrameListener frameListener) {
this.simpleEndpointDriver = simpleEndpointDriver;
this.frameListener = frameListener;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg;
if (!isH2Established(ctx.channel())) {
String prefaceString = bb.readCharSequence(24, StandardCharsets.UTF_8).toString();
if (PREFACE.equals(prefaceString)) {
ctx.channel().attr(H2_ESTABLISHED).set(true);
}
}
frameReader.readFrame(ctx, bb, frameListener);
}
private boolean isH2Established(Channel ch) {
return Boolean.TRUE.equals(ch.attr(H2_ESTABLISHED).get());
}
}
}
| 1,103 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/H2ServerErrorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.HttpTestUtils.sendGetRequest;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
/**
* Testing the scenario where h2 server sends 5xx errors.
*/
public class H2ServerErrorTest {
private static final Logger LOGGER = Logger.loggerFor(ServerNotRespondingTest.class);
private SdkAsyncHttpClient netty;
private Server server;
@BeforeEach
public void setup() throws Exception {
server = new Server();
server.init();
netty = NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(3).build())
.protocol(Protocol.HTTP2)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
@AfterEach
public void teardown() throws InterruptedException {
if (server != null) {
server.shutdown();
}
server = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void serviceReturn500_newRequestShouldUseNewConnection() {
server.return500OnFirstRequest = true;
CompletableFuture<?> firstRequest = sendGetRequest(server.port(), netty);
firstRequest.join();
sendGetRequest(server.port(), netty).join();
assertThat(server.h2ConnectionCount.get()).isEqualTo(2);
}
@Test
public void serviceReturn200_newRequestShouldReuseExistingConnection() throws Exception {
server.return500OnFirstRequest = false;
CompletableFuture<?> firstRequest = sendGetRequest(server.port(), netty);
firstRequest.join();
// The request-complete-future does not await the channel-release-future
// Wait a small amount to allow the channel release to complete
Thread.sleep(100);
sendGetRequest(server.port(), netty).join();
assertThat(server.h2ConnectionCount.get()).isEqualTo(1);
}
private static class Server extends ChannelInitializer<Channel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private String[] channelIds = new String[5];
private final NioEventLoopGroup group = new NioEventLoopGroup();
private SslContext sslCtx;
private boolean return500OnFirstRequest;
private AtomicInteger h2ConnectionCount = new AtomicInteger(0);
void init() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
@Override
protected void initChannel(Channel ch) {
channelIds[h2ConnectionCount.get()] = ch.id().asShortText();
LOGGER.debug(() -> "init channel " + ch);
h2ConnectionCount.incrementAndGet();
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
Http2FrameCodec http2Codec = Http2FrameCodecBuilder.forServer()
.autoAckPingFrame(true)
.initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(1))
.build();
Http2MultiplexHandler http2Handler = new Http2MultiplexHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new MightReturn500StreamFrameHandler());
}
});
pipeline.addLast(http2Codec);
pipeline.addLast(http2Handler);
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
serverSock.close();
}
public int port() {
return serverSock.localAddress().getPort();
}
private class MightReturn500StreamFrameHandler extends SimpleChannelInboundHandler<Http2Frame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(true);
// returning 500 this is channel 1
if (channelIds[0].equals(ctx.channel().parent().id().asShortText()) && return500OnFirstRequest) {
LOGGER.info(() -> "This is the first request, returning 500" + ctx.channel());
Http2Headers headers = new DefaultHttp2Headers().status(INTERNAL_SERVER_ERROR.codeAsText());
ctx.write(new DefaultHttp2HeadersFrame(headers, false));
ctx.write(new DefaultHttp2DataFrame(true));
ctx.flush();
} else {
LOGGER.info(() -> "return empty data " + ctx.channel() + " frame " + frame.getClass());
Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
ctx.write(new DefaultHttp2HeadersFrame(headers, false));
ctx.write(dataFrame);
ctx.flush();
}
}
}
}
}
}
| 1,104 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/ServerNotRespondingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.timeout.ReadTimeoutException;
import io.reactivex.Flowable;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
/**
* Testing the scenario where the server fails to respond to periodic PING
*/
public class ServerNotRespondingTest {
private static final Logger LOGGER = Logger.loggerFor(ServerNotRespondingTest.class);
private SdkAsyncHttpClient netty;
private Server server;
@BeforeEach
public void setup() throws Exception {
server = new Server();
server.init();
netty = NettyNioAsyncHttpClient.builder()
.readTimeout(Duration.ofMillis(1000))
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(3).build())
.http2Configuration(h -> h.healthCheckPingPeriod(Duration.ofMillis(200)))
.protocol(Protocol.HTTP2)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
@AfterEach
public void teardown() throws InterruptedException {
if (server != null) {
server.shutdown();
}
server = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void connectionNotAckPing_newRequestShouldUseNewConnection() throws InterruptedException {
server.ackPingOnFirstChannel = false;
server.notRespondOnFirstChannel = false;
CompletableFuture<Void> firstRequest = sendGetRequest();
// First request should succeed
firstRequest.join();
// Wait for Ping to close the connection
Thread.sleep(200);
server.notRespondOnFirstChannel = false;
sendGetRequest().join();
assertThat(server.h2ConnectionCount.get()).isEqualTo(2);
assertThat(server.closedByClientH2ConnectionCount.get()).isEqualTo(1);
}
@Test
public void connectionNotRespond_newRequestShouldUseNewConnection() throws Exception {
server.ackPingOnFirstChannel = true;
server.notRespondOnFirstChannel = true;
// The first request picks up a non-responding channel and should fail. Channel 1
CompletableFuture<Void> firstRequest = sendGetRequest();
assertThatThrownBy(() -> firstRequest.join()).hasRootCauseInstanceOf(ReadTimeoutException.class);
// The second request should pick up a new healthy channel - Channel 2
sendGetRequest().join();
assertThat(server.h2ConnectionCount.get()).isEqualTo(2);
assertThat(server.closedByClientH2ConnectionCount.get()).isEqualTo(1);
}
private CompletableFuture<Void> sendGetRequest() {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.responseHandler(new SdkAsyncHttpResponseHandler() {
private SdkHttpResponse headers;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.headers = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
Flowable.fromPublisher(stream).forEach(b -> {
});
}
@Override
public void onError(Throwable error) {
}
})
.request(SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost")
.port(server.port())
.build())
.requestContentPublisher(new EmptyPublisher())
.build();
return netty.execute(req);
}
private static class Server extends ChannelInitializer<Channel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private String[] channelIds = new String[5];
private final NioEventLoopGroup group = new NioEventLoopGroup();
private SslContext sslCtx;
private AtomicInteger h2ConnectionCount = new AtomicInteger(0);
private AtomicInteger closedByClientH2ConnectionCount = new AtomicInteger(0);
private volatile boolean ackPingOnFirstChannel = false;
private volatile boolean notRespondOnFirstChannel = true;
void init() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
@Override
protected void initChannel(Channel ch) {
channelIds[h2ConnectionCount.get()] = ch.id().asShortText();
ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));
LOGGER.debug(() -> "init channel " + ch);
h2ConnectionCount.incrementAndGet();
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
Http2FrameCodec http2Codec = Http2FrameCodecBuilder.forServer()
//Disable auto ack ping
.autoAckPingFrame(false)
.initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(2))
.frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "WIRE"))
.build();
Http2MultiplexHandler http2Handler = new Http2MultiplexHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new MightNotRespondStreamFrameHandler());
}
});
pipeline.addLast(http2Codec);
pipeline.addLast(new MightNotRespondPingFrameHandler());
pipeline.addLast(new VerifyGoAwayFrameHandler());
pipeline.addLast(http2Handler);
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
serverSock.close();
}
public int port() {
return serverSock.localAddress().getPort();
}
public final class MightNotRespondPingFrameHandler extends SimpleChannelInboundHandler<Http2PingFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2PingFrame msg) {
if (channelIds[0].equals(ctx.channel().id().asShortText()) && !ackPingOnFirstChannel) {
// Not respond if this is the first request
LOGGER.info(() -> "yolo" + ctx.channel());
} else {
ctx.writeAndFlush(new DefaultHttp2PingFrame(msg.content(), true));
}
}
}
public final class VerifyGoAwayFrameHandler extends SimpleChannelInboundHandler<Http2GoAwayFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2GoAwayFrame msg) {
LOGGER.info(() -> "goaway" + ctx.channel());
closedByClientH2ConnectionCount.incrementAndGet();
msg.release();
}
}
private class MightNotRespondStreamFrameHandler extends SimpleChannelInboundHandler<Http2Frame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
// Not respond if this is channel 1
if (channelIds[0].equals(ctx.channel().parent().id().asShortText()) && notRespondOnFirstChannel) {
LOGGER.info(() -> "This is the first request, not responding" + ctx.channel());
} else {
DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(false);
try {
LOGGER.info(() -> "return empty data " + ctx.channel() + " frame " + frame.getClass());
Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
ctx.write(dataFrame);
ctx.write(new DefaultHttp2HeadersFrame(headers, true));
ctx.flush();
} finally {
dataFrame.release();
}
}
}
}
}
}
}
| 1,105 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/H1ServerErrorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import software.amazon.awssdk.http.SdkAsyncHttpClientH1TestSuite;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Testing the scenario where h1 server sends 5xx errors.
*/
public class H1ServerErrorTest extends SdkAsyncHttpClientH1TestSuite {
@Override
protected SdkAsyncHttpClient setupClient() {
return NettyNioAsyncHttpClient.builder()
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(2).build())
.protocol(Protocol.HTTP1_1)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
}
| 1,106 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/ServerConnectivityErrorMessageTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_TASK;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.reactivex.Flowable;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.SimpleHttpContentPublisher;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Logger;
public class ServerConnectivityErrorMessageTest {
private static final Logger LOGGER = Logger.loggerFor(ServerConnectivityErrorMessageTest.class);
private SdkAsyncHttpClient netty;
private Server server;
public static Collection<TestCase> testCases() {
return Arrays.asList(new TestCase(CloseTime.DURING_INIT, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_SSL_HANDSHAKE, "The connection was closed during the request."),
new TestCase(CloseTime.DURING_SSL_HANDSHAKE, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_REQUEST_PAYLOAD, "The connection was closed during the request."),
new TestCase(CloseTime.DURING_REQUEST_PAYLOAD, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_RESPONSE_HEADERS, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_RESPONSE_PAYLOAD, "Response had content-length"),
new TestCase(CloseTime.DURING_RESPONSE_PAYLOAD, "Response had content-length"));
}
public static Collection<TestCase> testCasesForHttpContinueResponse() {
return Arrays.asList(new TestCase(CloseTime.DURING_INIT, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_SSL_HANDSHAKE, "The connection was closed during the request."),
new TestCase(CloseTime.DURING_SSL_HANDSHAKE, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_REQUEST_PAYLOAD, "The connection was closed during the request."),
new TestCase(CloseTime.DURING_REQUEST_PAYLOAD, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_RESPONSE_HEADERS, "The connection was closed during the request."),
new TestCase(CloseTime.BEFORE_RESPONSE_PAYLOAD, "The connection was closed during the request."),
new TestCase(CloseTime.DURING_RESPONSE_PAYLOAD, "The connection was closed during the request."));
}
@AfterEach
public void teardown() throws InterruptedException {
if (server != null) {
server.shutdown();
}
server = null;
if (netty != null) {
netty.close();
}
netty = null;
}
@ParameterizedTest
@MethodSource("testCases")
void closeTimeHasCorrectMessage(TestCase testCase) throws Exception {
server = new Server(ServerConfig.builder().httpResponseStatus(HttpResponseStatus.OK).build());
setupTestCase(testCase);
server.closeTime = testCase.closeTime;
assertThat(captureException(RequestParams.builder()
.httpMethod(SdkHttpMethod.GET)
.contentPublisher(new EmptyPublisher())
.build()))
.as("Closing time: " + testCase.closeTime)
.hasMessageContaining(testCase.errorMessageSubstring);
}
@ParameterizedTest
@MethodSource("testCasesForHttpContinueResponse")
void closeTimeHasCorrectMessageWith100ContinueResponse(TestCase testCase) throws Exception {
server = new Server(ServerConfig.builder().httpResponseStatus(HttpResponseStatus.CONTINUE).build());
setupTestCase(testCase);
server.closeTime = testCase.closeTime;
assertThat(captureException(RequestParams.builder()
.httpMethod(SdkHttpMethod.PUT)
.addHeaderKeyValue(HttpHeaderNames.EXPECT.toString(),
Arrays.asList(HttpHeaderValues.CONTINUE.toString()))
.contentPublisher(new SimpleHttpContentPublisher("reqBody".getBytes(StandardCharsets.UTF_8)))
.build()));
}
public void setupTestCase(TestCase testCase) throws Exception {
server.init(testCase.closeTime);
netty = NettyNioAsyncHttpClient.builder()
.readTimeout(Duration.ofMillis(500))
.eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(3).build())
.protocol(Protocol.HTTP1_1)
.buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build());
}
private Throwable captureException(RequestParams requestParams) {
try {
sendCustomRequest(requestParams).get(10, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException e) {
throw new Error(e);
} catch (ExecutionException e) {
return e.getCause();
}
throw new AssertionError("Call did not fail as expected.");
}
private CompletableFuture<Void> sendCustomRequest(RequestParams requestParams) {
AsyncExecuteRequest req = AsyncExecuteRequest.builder()
.responseHandler(new SdkAsyncHttpResponseHandler() {
private SdkHttpResponse headers;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.headers = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
Flowable.fromPublisher(stream).forEach(b -> {
});
}
@Override
public void onError(Throwable error) {
}
})
.request(SdkHttpFullRequest.builder()
.method(requestParams.httpMethod())
.protocol("https")
.host("localhost")
.headers(requestParams.headersMap())
.port(server.port())
.build())
.requestContentPublisher(requestParams.contentPublisher())
.build();
return netty.execute(req);
}
private static class TestCase {
private CloseTime closeTime;
private String errorMessageSubstring;
private TestCase(CloseTime closeTime, String errorMessageSubstring) {
this.closeTime = closeTime;
this.errorMessageSubstring = errorMessageSubstring;
}
@Override
public String toString() {
return "Closure " + closeTime;
}
}
private enum CloseTime {
DURING_INIT,
BEFORE_SSL_HANDSHAKE,
DURING_SSL_HANDSHAKE,
BEFORE_REQUEST_PAYLOAD,
DURING_REQUEST_PAYLOAD,
BEFORE_RESPONSE_HEADERS,
BEFORE_RESPONSE_PAYLOAD,
DURING_RESPONSE_PAYLOAD
}
private static class ServerConfig {
private final HttpResponseStatus httpResponseStatus;
public static Builder builder(){
return new Builder();
}
private ServerConfig(Builder builder) {
this.httpResponseStatus = builder.httpResponseStatus;
}
public static class Builder {
private HttpResponseStatus httpResponseStatus;
public Builder httpResponseStatus(HttpResponseStatus httpResponseStatus){
this.httpResponseStatus = httpResponseStatus;
return this;
}
public ServerConfig build() {
return new ServerConfig(this);
}
}
}
private static class RequestParams{
private final SdkHttpMethod httpMethod;
private final SdkHttpContentPublisher contentPublisher;
private final Map<String, List<String>> headersMap;
public RequestParams(SdkHttpMethod httpMethod, SdkHttpContentPublisher contentPublisher,
Map<String, List<String>> headersMap) {
this.httpMethod = httpMethod;
this.contentPublisher = contentPublisher;
this.headersMap = headersMap;
}
public SdkHttpMethod httpMethod() {
return httpMethod;
}
public Map<String, List<String>> headersMap() {
return headersMap;
}
public SdkHttpContentPublisher contentPublisher() {
return contentPublisher;
}
public static Builder builder(){
return new Builder();
}
private static class Builder{
private SdkHttpMethod httpMethod;
private SdkHttpContentPublisher contentPublisher;
private Map<String, List<String>> headersMap = new HashMap<>();
public Builder httpMethod(SdkHttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public Builder contentPublisher(SdkHttpContentPublisher contentPublisher) {
this.contentPublisher = contentPublisher;
return this;
}
public Builder addHeaderKeyValue(String headerName, List<String> headerValues) {
headersMap.put(headerName, headerValues);
return this;
}
public RequestParams build(){
return new RequestParams(httpMethod, contentPublisher, headersMap);
}
}
}
private static class Server extends ChannelInitializer<Channel> {
private final NioEventLoopGroup group = new NioEventLoopGroup();
private CloseTime closeTime;
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private SslContext sslCtx;
private ServerConfig serverConfig;
public Server(ServerConfig serverConfig) {
this.serverConfig = serverConfig;
}
private void init(CloseTime closeTime) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
this.closeTime = closeTime;
}
public int port() {
return serverSock.localAddress().getPort();
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
serverSock.close();
}
@Override
protected void initChannel(Channel ch) {
LOGGER.info(() -> "Initializing channel " + ch);
if (closeTime == CloseTime.DURING_INIT) {
LOGGER.info(() -> "Closing channel during initialization " + ch);
ch.close();
return;
}
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new SslHandler(new FaultInjectionSslEngine(sslCtx.newEngine(ch.alloc()), ch), false));
pipeline.addLast(new HttpServerCodec());
FaultInjectionHttpHandler faultInjectionHttpHandler = new FaultInjectionHttpHandler();
faultInjectionHttpHandler.setHttpResponseStatus(serverConfig.httpResponseStatus);
pipeline.addLast(faultInjectionHttpHandler);
LOGGER.info(() -> "Channel initialized " + ch);
}
private class FaultInjectionSslEngine extends DelegatingSslEngine {
private final Channel channel;
private volatile boolean closed = false;
public FaultInjectionSslEngine(SSLEngine delegate, Channel channel) {
super(delegate);
this.channel = channel;
}
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
handleBeforeFailures();
return super.unwrap(src, dsts, offset, length);
}
@Override
public SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst) throws SSLException {
handleBeforeFailures();
return super.wrap(srcs, offset, length, dst);
}
private void handleBeforeFailures() {
if (getHandshakeStatus() == NOT_HANDSHAKING && closeTime == CloseTime.BEFORE_SSL_HANDSHAKE) {
closeChannel("Closing channel before handshake " + channel);
}
if ((getHandshakeStatus() == NEED_WRAP || getHandshakeStatus() == NEED_TASK || getHandshakeStatus() == NEED_UNWRAP)
&& closeTime == CloseTime.DURING_SSL_HANDSHAKE) {
closeChannel("Closing channel during handshake " + channel);
}
}
private void closeChannel(String message) {
if (!closed) {
LOGGER.info(() -> message);
closed = true;
channel.close();
}
}
}
private class FaultInjectionHttpHandler extends SimpleChannelInboundHandler<Object> {
private HttpResponseStatus httpResponseStatus = HttpResponseStatus.OK;
public void setHttpResponseStatus(HttpResponseStatus httpResponseStatus) {
this.httpResponseStatus = httpResponseStatus;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
LOGGER.info(() -> "Reading " + msg);
if (msg instanceof HttpRequest) {
if (closeTime == CloseTime.BEFORE_REQUEST_PAYLOAD) {
LOGGER.info(() -> "Closing channel before request payload " + ctx.channel());
ctx.channel().disconnect();
return;
}
}
if (msg instanceof HttpContent) {
if (closeTime == CloseTime.DURING_REQUEST_PAYLOAD) {
LOGGER.info(() -> "Closing channel during request payload handling " + ctx.channel());
ctx.close();
return;
}
if (msg instanceof LastHttpContent) {
if (closeTime == CloseTime.BEFORE_RESPONSE_HEADERS) {
LOGGER.info(() -> "Closing channel before response headers " + ctx.channel());
ctx.close();
return;
}
writeResponse(ctx);
}
}
}
private void writeResponse(ChannelHandlerContext ctx) {
int responseLength = 10 * 1024 * 1024; // 10 MB
HttpHeaders headers = new DefaultHttpHeaders().add("Content-Length", responseLength);
ctx.writeAndFlush(new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.httpResponseStatus, headers)).addListener(x -> {
if (closeTime == CloseTime.BEFORE_RESPONSE_PAYLOAD) {
LOGGER.info(() -> "Closing channel before response payload " + ctx.channel());
ctx.close();
return;
}
ByteBuf firstPartOfResponsePayload = ctx.alloc().buffer(1);
firstPartOfResponsePayload.writeByte(0);
ctx.writeAndFlush(new DefaultHttpContent(firstPartOfResponsePayload)).addListener(x2 -> {
if (closeTime == CloseTime.DURING_RESPONSE_PAYLOAD) {
LOGGER.info(() -> "Closing channel during response payload handling " + ctx.channel());
ctx.close();
return;
}
ByteBuf lastPartOfResponsePayload = ctx.alloc().buffer(responseLength - 1);
lastPartOfResponsePayload.writeBytes(new byte[responseLength - 1]);
ctx.writeAndFlush(new DefaultLastHttpContent(lastPartOfResponsePayload))
.addListener(ChannelFutureListener.CLOSE);
});
});
}
}
}
}
| 1,107 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/fault/PingTimeoutTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.fault;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.EmptyPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.Http2Configuration;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.internal.http2.PingFailedException;
/**
* Testing the scenario where the server never acks PING
*/
public class PingTimeoutTest {
@Rule
public ExpectedException expected = ExpectedException.none();
private Server server;
private SdkAsyncHttpClient netty;
@Before
public void methodSetup() throws Exception {
server = new Server();
server.init();
}
@After
public void methodTeardown() throws InterruptedException {
server.shutdown();
if (netty != null) {
netty.close();
}
netty = null;
}
@Test
public void pingHealthCheck_null_shouldThrowExceptionAfter5Sec() {
Instant a = Instant.now();
assertThatThrownBy(() -> makeRequest(null).join())
.hasMessageContaining("An error occurred on the connection")
.hasCauseInstanceOf(IOException.class)
.hasRootCauseInstanceOf(PingFailedException.class);
assertThat(Duration.between(a, Instant.now())).isBetween(Duration.ofSeconds(5), Duration.ofSeconds(7));
}
@Test
public void pingHealthCheck_10sec_shouldThrowExceptionAfter10Secs() {
Instant a = Instant.now();
assertThatThrownBy(() -> makeRequest(Duration.ofSeconds(10)).join()).hasCauseInstanceOf(IOException.class)
.hasMessageContaining("An error occurred on the connection")
.hasRootCauseInstanceOf(PingFailedException.class);
assertThat(Duration.between(a, Instant.now())).isBetween(Duration.ofSeconds(10), Duration.ofSeconds(12));
}
@Test
public void pingHealthCheck_0_disabled_shouldNotThrowException() throws Exception {
expected.expect(TimeoutException.class);
CompletableFuture<Void> requestFuture = makeRequest(Duration.ofMillis(0));
try {
requestFuture.get(8, TimeUnit.SECONDS);
} finally {
assertThat(requestFuture.isDone()).isFalse();
}
}
private CompletableFuture<Void> makeRequest(Duration healthCheckPingPeriod) {
netty = NettyNioAsyncHttpClient.builder()
.protocol(Protocol.HTTP2)
.http2Configuration(Http2Configuration.builder().healthCheckPingPeriod(healthCheckPingPeriod).build())
.build();
SdkHttpFullRequest request = SdkHttpFullRequest.builder()
.protocol("http")
.host("localhost")
.port(server.port())
.method(SdkHttpMethod.GET)
.build();
AsyncExecuteRequest executeRequest = AsyncExecuteRequest.builder()
.fullDuplex(false)
.request(request)
.requestContentPublisher(new EmptyPublisher())
.responseHandler(new SdkAsyncHttpResponseHandler() {
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Integer.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
});
}
@Override
public void onError(Throwable error) {
}
})
.build();
return netty.execute(executeRequest);
}
private static class Server extends ChannelInitializer<Channel> {
private ServerBootstrap bootstrap;
private ServerSocketChannel serverSock;
private String[] channelIds = new String[5];
private final NioEventLoopGroup group = new NioEventLoopGroup();
private SslContext sslCtx;
private AtomicInteger h2ConnectionCount = new AtomicInteger(0);
void init() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
bootstrap = new ServerBootstrap()
.channel(NioServerSocketChannel.class)
.group(group)
.childHandler(this);
serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel();
}
@Override
protected void initChannel(Channel ch) {
channelIds[h2ConnectionCount.get()] = ch.id().asShortText();
ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));
h2ConnectionCount.incrementAndGet();
ChannelPipeline pipeline = ch.pipeline();
Http2FrameCodec http2Codec = Http2FrameCodecBuilder.forServer()
// simulate not sending goaway
.decoupleCloseAndGoAway(true)
.autoAckPingFrame(false)
.initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(2))
.frameLogger(new Http2FrameLogger(LogLevel.DEBUG, "WIRE"))
.build();
Http2MultiplexHandler http2Handler = new Http2MultiplexHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new StreamHandler());
}
});
pipeline.addLast(http2Codec);
pipeline.addLast(http2Handler);
}
public void shutdown() throws InterruptedException {
group.shutdownGracefully().await();
serverSock.close();
}
public int port() {
return serverSock.localAddress().getPort();
}
}
private static final class StreamHandler extends SimpleChannelInboundHandler<Http2Frame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame http2Frame) throws Exception {
if (http2Frame instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) http2Frame;
if (dataFrame.isEndStream()) {
Http2Headers headers = new DefaultHttp2Headers().status("200");
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false));
ctx.executor().scheduleAtFixedRate(() -> {
DefaultHttp2DataFrame respData = new DefaultHttp2DataFrame(Unpooled.wrappedBuffer("hello".getBytes()), false);
ctx.writeAndFlush(respData);
}, 0, 2, TimeUnit.SECONDS);
}
}
}
}
}
| 1,108 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/SdkEventLoopGroup.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.Optional;
import java.util.concurrent.ThreadFactory;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelResolver;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
import software.amazon.awssdk.utils.Validate;
/**
* Provides {@link EventLoopGroup} and {@link ChannelFactory} for {@link NettyNioAsyncHttpClient}.
* <p>
* There are three ways to create a new instance.
*
* <ul>
* <li>using {@link #builder()} to provide custom configuration of {@link EventLoopGroup}.
* This is the preferred configuration method when you just want to customize the {@link EventLoopGroup}</li>
*
*
* <li>Using {@link #create(EventLoopGroup)} to provide a custom {@link EventLoopGroup}. {@link ChannelFactory} will
* be resolved based on the type of {@link EventLoopGroup} provided via
* {@link ChannelResolver#resolveSocketChannelFactory(EventLoopGroup)} and
* {@link ChannelResolver#resolveDatagramChannelFactory(EventLoopGroup)}
* </li>
*
* <li>Using {@link #create(EventLoopGroup, ChannelFactory)} to provide a custom {@link EventLoopGroup} and
* {@link ChannelFactory}
* </ul>
*
* <p>
* When configuring the {@link EventLoopGroup} of {@link NettyNioAsyncHttpClient}, if {@link SdkEventLoopGroup.Builder} is
* passed to {@link NettyNioAsyncHttpClient.Builder#eventLoopGroupBuilder},
* the {@link EventLoopGroup} is managed by the SDK and will be shutdown when the HTTP client is closed. Otherwise,
* if an instance of {@link SdkEventLoopGroup} is passed to {@link NettyNioAsyncHttpClient.Builder#eventLoopGroup},
* the {@link EventLoopGroup} <b>MUST</b> be closed by the caller when it is ready to be disposed. The SDK will not
* close the {@link EventLoopGroup} when the HTTP client is closed. See {@link EventLoopGroup#shutdownGracefully()} to
* properly close the event loop group.
*
* @see NettyNioAsyncHttpClient.Builder#eventLoopGroupBuilder(Builder)
* @see NettyNioAsyncHttpClient.Builder#eventLoopGroup(SdkEventLoopGroup)
*/
@SdkPublicApi
public final class SdkEventLoopGroup {
private final EventLoopGroup eventLoopGroup;
private final ChannelFactory<? extends Channel> channelFactory;
private final ChannelFactory<? extends DatagramChannel> datagramChannelFactory;
SdkEventLoopGroup(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory) {
Validate.paramNotNull(eventLoopGroup, "eventLoopGroup");
Validate.paramNotNull(channelFactory, "channelFactory");
this.eventLoopGroup = eventLoopGroup;
this.channelFactory = channelFactory;
this.datagramChannelFactory = ChannelResolver.resolveDatagramChannelFactory(eventLoopGroup);
}
/**
* Create an instance of {@link SdkEventLoopGroup} from the builder
*/
private SdkEventLoopGroup(DefaultBuilder builder) {
this.eventLoopGroup = resolveEventLoopGroup(builder);
this.channelFactory = resolveSocketChannelFactory(builder);
this.datagramChannelFactory = resolveDatagramChannelFactory(builder);
}
/**
* @return the {@link EventLoopGroup} to be used with Netty Http client.
*/
public EventLoopGroup eventLoopGroup() {
return eventLoopGroup;
}
/**
* @return the {@link ChannelFactory} to be used with Netty Http Client.
*/
public ChannelFactory<? extends Channel> channelFactory() {
return channelFactory;
}
/**
* @return the {@link ChannelFactory} for datagram channels to be used with Netty Http Client.
*/
public ChannelFactory<? extends DatagramChannel> datagramChannelFactory() {
return datagramChannelFactory;
}
/**
* Creates a new instance of SdkEventLoopGroup with {@link EventLoopGroup} and {@link ChannelFactory}
* to be used with {@link NettyNioAsyncHttpClient}.
*
* @param eventLoopGroup the EventLoopGroup to be used
* @param channelFactory the channel factor to be used
* @return a new instance of SdkEventLoopGroup
*/
public static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup, ChannelFactory<? extends Channel> channelFactory) {
return new SdkEventLoopGroup(eventLoopGroup, channelFactory);
}
/**
* Creates a new instance of SdkEventLoopGroup with {@link EventLoopGroup}.
*
* <p>
* {@link ChannelFactory} will be resolved based on the type of {@link EventLoopGroup} provided. IllegalArgumentException will
* be thrown for any unknown EventLoopGroup type.
*
* @param eventLoopGroup the EventLoopGroup to be used
* @return a new instance of SdkEventLoopGroup
*/
public static SdkEventLoopGroup create(EventLoopGroup eventLoopGroup) {
return create(eventLoopGroup, ChannelResolver.resolveSocketChannelFactory(eventLoopGroup));
}
public static Builder builder() {
return new DefaultBuilder();
}
private EventLoopGroup resolveEventLoopGroup(DefaultBuilder builder) {
int numThreads = Optional.ofNullable(builder.numberOfThreads).orElse(0);
ThreadFactory threadFactory = Optional.ofNullable(builder.threadFactory)
.orElseGet(() -> new ThreadFactoryBuilder()
.threadNamePrefix("aws-java-sdk-NettyEventLoop")
.build());
return new NioEventLoopGroup(numThreads, threadFactory);
/*
Need to investigate why epoll is raising channel inactive after successful response that causes
problems with retries.
if (Epoll.isAvailable() && isNotAwsLambda()) {
return new EpollEventLoopGroup(numThreads, resolveThreadFactory());
} else {
}*/
}
private ChannelFactory<? extends Channel> resolveSocketChannelFactory(DefaultBuilder builder) {
return builder.channelFactory;
}
private ChannelFactory<? extends DatagramChannel> resolveDatagramChannelFactory(DefaultBuilder builder) {
return builder.datagramChannelFactory;
}
private static ChannelFactory<? extends Channel> defaultSocketChannelFactory() {
return NioSocketChannel::new;
}
private static ChannelFactory<? extends DatagramChannel> defaultDatagramChannelFactory() {
return NioDatagramChannel::new;
}
/**
* A builder for {@link SdkEventLoopGroup}.
*
* <p>All implementations of this interface are mutable and not thread safe.
*/
public interface Builder {
/**
* Number of threads to use for the {@link EventLoopGroup}. If not set, the default
* Netty thread count is used (which is double the number of available processors unless the io.netty.eventLoopThreads
* system property is set.
*
* @param numberOfThreads Number of threads to use.
* @return This builder for method chaining.
*/
Builder numberOfThreads(Integer numberOfThreads);
/**
* {@link ThreadFactory} to create threads used by the {@link EventLoopGroup}. If not set,
* a generic thread factory is used.
*
* @param threadFactory ThreadFactory to use.
* @return This builder for method chaining.
*/
Builder threadFactory(ThreadFactory threadFactory);
/**
* {@link ChannelFactory} to create socket channels used by the {@link EventLoopGroup}. If not set,
* NioSocketChannel is used.
*
* @param channelFactory ChannelFactory to use.
* @return This builder for method chaining.
*/
Builder channelFactory(ChannelFactory<? extends Channel> channelFactory);
/**
* {@link ChannelFactory} to create datagram channels used by the {@link EventLoopGroup}. If not set,
* NioDatagramChannel is used.
*
* @param datagramChannelFactory ChannelFactory to use.
* @return This builder for method chaining.
*/
Builder datagramChannelFactory(ChannelFactory<? extends DatagramChannel> datagramChannelFactory);
SdkEventLoopGroup build();
}
private static final class DefaultBuilder implements Builder {
private Integer numberOfThreads;
private ThreadFactory threadFactory;
private ChannelFactory<? extends Channel> channelFactory = defaultSocketChannelFactory();
private ChannelFactory<? extends DatagramChannel> datagramChannelFactory = defaultDatagramChannelFactory();
private DefaultBuilder() {
}
@Override
public Builder numberOfThreads(Integer numberOfThreads) {
this.numberOfThreads = numberOfThreads;
return this;
}
public void setNumberOfThreads(Integer numberOfThreads) {
numberOfThreads(numberOfThreads);
}
@Override
public Builder threadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
return this;
}
public void setThreadFactory(ThreadFactory threadFactory) {
threadFactory(threadFactory);
}
@Override
public Builder channelFactory(ChannelFactory<? extends Channel> channelFactory) {
this.channelFactory = channelFactory;
return this;
}
public void setChannelFactory(ChannelFactory<? extends Channel> channelFactory) {
channelFactory(channelFactory);
}
@Override
public Builder datagramChannelFactory(ChannelFactory<? extends DatagramChannel> datagramChannelFactory) {
this.datagramChannelFactory = datagramChannelFactory;
return this;
}
public void setDatagramChannelFactory(ChannelFactory<? extends DatagramChannel> datagramChannelFactory) {
datagramChannelFactory(datagramChannelFactory);
}
@Override
public SdkEventLoopGroup build() {
return new SdkEventLoopGroup(this);
}
}
}
| 1,109 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/ProxyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.ProxyEnvironmentSetting;
import software.amazon.awssdk.utils.ProxySystemSetting;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Proxy configuration for {@link NettyNioAsyncHttpClient}. This class is used to configure an HTTP or HTTPS proxy to be used by
* the {@link NettyNioAsyncHttpClient}.
*
* @see NettyNioAsyncHttpClient.Builder#proxyConfiguration(ProxyConfiguration)
*/
@SdkPublicApi
public final class ProxyConfiguration implements ToCopyableBuilder<ProxyConfiguration.Builder, ProxyConfiguration> {
private final Boolean useSystemPropertyValues;
private final Boolean useEnvironmentVariablesValues;
private final String scheme;
private final String host;
private final int port;
private final String username;
private final String password;
private final Set<String> nonProxyHosts;
private ProxyConfiguration(BuilderImpl builder) {
this.useSystemPropertyValues = builder.useSystemPropertyValues;
this.useEnvironmentVariablesValues = builder.useEnvironmentVariablesValues;
this.scheme = builder.scheme;
ProxyConfigProvider proxyConfigProvider =
ProxyConfigProvider.fromSystemEnvironmentSettings(builder.useSystemPropertyValues,
builder.useEnvironmentVariablesValues,
builder.scheme);
this.host = resolveHost(builder, proxyConfigProvider);
this.port = resolvePort(builder, proxyConfigProvider);
this.username = resolveUserName(builder, proxyConfigProvider);
this.password = resolvePassword(builder, proxyConfigProvider);
this.nonProxyHosts = resolveNonProxyHosts(builder, proxyConfigProvider);
}
private static Set<String> resolveNonProxyHosts(BuilderImpl builder, ProxyConfigProvider proxyConfigProvider) {
if (builder.nonProxyHosts != null || proxyConfigProvider == null) {
return builder.nonProxyHosts;
} else {
return proxyConfigProvider.nonProxyHosts();
}
}
private static String resolvePassword(BuilderImpl builder, ProxyConfigProvider proxyConfigProvider) {
if (!StringUtils.isEmpty(builder.password) || proxyConfigProvider == null) {
return builder.password;
} else {
return proxyConfigProvider.password().orElseGet(() -> builder.password);
}
}
private static String resolveUserName(BuilderImpl builder, ProxyConfigProvider proxyConfigProvider) {
if (!StringUtils.isEmpty(builder.username) || proxyConfigProvider == null) {
return builder.username;
} else {
return proxyConfigProvider.userName().orElseGet(() -> builder.username);
}
}
private static int resolvePort(BuilderImpl builder, ProxyConfigProvider proxyConfigProvider) {
if (builder.port != 0 || proxyConfigProvider == null) {
return builder.port;
} else {
return proxyConfigProvider.port();
}
}
private static String resolveHost(BuilderImpl builder, ProxyConfigProvider proxyConfigProvider) {
if (builder.host != null || proxyConfigProvider == null) {
return builder.host;
} else {
return proxyConfigProvider.host();
}
}
public static Builder builder() {
return new BuilderImpl();
}
/**
* @return The proxy scheme.
*/
public String scheme() {
return scheme;
}
/**
* @return The proxy host from the configuration if set, else from the "https.proxyHost" or "http.proxyHost" system property,
* based on the scheme used, if @link ProxyConfiguration.Builder#useSystemPropertyValues(Boolean)} is set to true
*/
public String host() {
return host;
}
/**
* @return The proxy port from the configuration if set, else from the "https.proxyPort" or "http.proxyPort" system
* property, based on the scheme used, if {@link ProxyConfiguration.Builder#useSystemPropertyValues(Boolean)} is set to true
*/
public int port() {
return port;
}
/**
* @return The proxy username from the configuration if set, else from the "https.proxyUser" or "http.proxyUser" system
* property, based on the scheme used, if {@link ProxyConfiguration.Builder#useSystemPropertyValues(Boolean)} is set to true
* */
public String username() {
return username;
}
/**
* @return The proxy password from the configuration if set, else from the "https.proxyPassword" or "http.proxyPassword"
* system property, based on the scheme used, if {@link ProxyConfiguration.Builder#useSystemPropertyValues(Boolean)} is set
* to true
* */
public String password() {
return password;
}
/**
* @return The set of hosts that should not be proxied. If the value is not set, the value present by "http.nonProxyHost"
* system property is returned. If system property is also not set, an unmodifiable empty set is returned.
*/
public Set<String> nonProxyHosts() {
return Collections.unmodifiableSet(nonProxyHosts != null ? nonProxyHosts : Collections.emptySet());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProxyConfiguration that = (ProxyConfiguration) o;
if (port != that.port) {
return false;
}
if (scheme != null ? !scheme.equals(that.scheme) : that.scheme != null) {
return false;
}
if (host != null ? !host.equals(that.host) : that.host != null) {
return false;
}
if (username != null ? !username.equals(that.username) : that.username != null) {
return false;
}
if (password != null ? !password.equals(that.password) : that.password != null) {
return false;
}
return nonProxyHosts.equals(that.nonProxyHosts);
}
@Override
public int hashCode() {
int result = scheme != null ? scheme.hashCode() : 0;
result = 31 * result + (host != null ? host.hashCode() : 0);
result = 31 * result + port;
result = 31 * result + nonProxyHosts.hashCode();
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* Builder for {@link ProxyConfiguration}.
*/
public interface Builder extends CopyableBuilder<Builder, ProxyConfiguration> {
/**
* Set the hostname of the proxy.
*
* @param host The proxy host.
* @return This object for method chaining.
*/
Builder host(String host);
/**
* Set the port that the proxy expects connections on.
*
* @param port The proxy port.
* @return This object for method chaining.
*/
Builder port(int port);
/**
* The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}.
* <p>
* The client defaults to {@code http} if none is given.
*
* @param scheme The proxy scheme.
* @return This object for method chaining.
*/
Builder scheme(String scheme);
/**
* Set the set of hosts that should not be proxied. Any request whose host portion matches any of the patterns
* given in the set will be sent to the remote host directly instead of through the proxy.
*
* @param nonProxyHosts The set of hosts that should not be proxied.
* @return This object for method chaining.
*/
Builder nonProxyHosts(Set<String> nonProxyHosts);
/**
* Set the username used to authenticate with the proxy username.
*
* @param username The proxy username.
* @return This object for method chaining.
*/
Builder username(String username);
/**
* Set the password used to authenticate with the proxy password.
*
* @param password The proxy password.
* @return This object for method chaining.
*/
Builder password(String password);
/**
* Set the option whether to use system property values from {@link ProxySystemSetting} if any of the config options
* are missing. The value is set to "true" by default which means SDK will automatically use system property values if
* options are not provided during building the {@link ProxyConfiguration} object. To disable this behaviour, set this
* value to false.It is important to note that when this property is set to "true," all proxy settings will exclusively
* be obtained from System Property Values, and no partial settings will be obtained from Environment Variable Values.
*
* @param useSystemPropertyValues The option whether to use system property values
* @return This object for method chaining.
*/
Builder useSystemPropertyValues(Boolean useSystemPropertyValues);
/**
* Set the option whether to use environment variable values for {@link ProxyEnvironmentSetting} if any of the config
* options are missing. The value is set to "true" by default, enabling the SDK to automatically use environment variable
* values for proxy configuration options that are not provided during building the {@link ProxyConfiguration} object. To
* disable this behavior, set this value to "false".It is important to note that when this property is set to "true," all
* proxy settings will exclusively originate from Environment Variable Values, and no partial settings will be obtained
* from System Property Values.
*
* @param useEnvironmentVariablesValues The option whether to use environment variable values
* @return This object for method chaining.
*/
Builder useEnvironmentVariableValues(Boolean useEnvironmentVariablesValues);
}
private static final class BuilderImpl implements Builder {
private String scheme = "http";
private String host;
private int port = 0;
private String username;
private String password;
private Set<String> nonProxyHosts;
private Boolean useSystemPropertyValues = Boolean.TRUE;
private Boolean useEnvironmentVariablesValues = Boolean.TRUE;
private BuilderImpl() {
}
private BuilderImpl(ProxyConfiguration proxyConfiguration) {
this.useSystemPropertyValues = proxyConfiguration.useSystemPropertyValues;
this.useEnvironmentVariablesValues = proxyConfiguration.useEnvironmentVariablesValues;
this.scheme = proxyConfiguration.scheme;
this.host = proxyConfiguration.host;
this.port = proxyConfiguration.port;
this.nonProxyHosts = proxyConfiguration.nonProxyHosts != null ?
new HashSet<>(proxyConfiguration.nonProxyHosts) : null;
this.username = proxyConfiguration.username;
this.password = proxyConfiguration.password;
}
@Override
public Builder scheme(String scheme) {
this.scheme = scheme;
return this;
}
@Override
public Builder host(String host) {
this.host = host;
return this;
}
@Override
public Builder port(int port) {
this.port = port;
return this;
}
@Override
public Builder nonProxyHosts(Set<String> nonProxyHosts) {
if (nonProxyHosts != null) {
this.nonProxyHosts = new HashSet<>(nonProxyHosts);
} else {
this.nonProxyHosts = Collections.emptySet();
}
return this;
}
@Override
public Builder username(String username) {
this.username = username;
return this;
}
@Override
public Builder password(String password) {
this.password = password;
return this;
}
@Override
public Builder useSystemPropertyValues(Boolean useSystemPropertyValues) {
this.useSystemPropertyValues = useSystemPropertyValues;
return this;
}
public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) {
useSystemPropertyValues(useSystemPropertyValues);
}
@Override
public Builder useEnvironmentVariableValues(Boolean useEnvironmentVariablesValues) {
this.useEnvironmentVariablesValues = useEnvironmentVariablesValues;
return this;
}
public void setUseEnvironmentVariablesValues(Boolean useEnvironmentVariablesValues) {
useEnvironmentVariableValues(useEnvironmentVariablesValues);
}
@Override
public ProxyConfiguration build() {
return new ProxyConfiguration(this);
}
}
} | 1,110 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import static software.amazon.awssdk.http.HttpMetric.HTTP_CLIENT_NAME;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.runAndLogError;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslProvider;
import java.net.SocketOptions;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SystemPropertyTlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.internal.AwaitCloseChannelPoolMap;
import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration;
import software.amazon.awssdk.http.nio.netty.internal.NettyRequestExecutor;
import software.amazon.awssdk.http.nio.netty.internal.NonManagedEventLoopGroup;
import software.amazon.awssdk.http.nio.netty.internal.RequestContext;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelOptions;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPoolMap;
import software.amazon.awssdk.http.nio.netty.internal.SharedSdkEventLoopGroup;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.Either;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkAsyncHttpClient} that uses a Netty non-blocking HTTP client to communicate with the service.
*
* <p>This can be created via {@link #builder()}</p>
*/
@SdkPublicApi
public final class NettyNioAsyncHttpClient implements SdkAsyncHttpClient {
private static final String CLIENT_NAME = "NettyNio";
private static final NettyClientLogger log = NettyClientLogger.getLogger(NettyNioAsyncHttpClient.class);
private static final long MAX_STREAMS_ALLOWED = 4294967295L; // unsigned 32-bit, 2^32 -1
private static final int DEFAULT_INITIAL_WINDOW_SIZE = 1_048_576; // 1MiB
// Override connection idle timeout for Netty http client to reduce the frequency of "server failed to complete the
// response error". see https://github.com/aws/aws-sdk-java-v2/issues/1122
private static final AttributeMap NETTY_HTTP_DEFAULTS =
AttributeMap.builder()
.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, Duration.ofSeconds(5))
.build();
private final SdkEventLoopGroup sdkEventLoopGroup;
private final SdkChannelPoolMap<URI, ? extends SdkChannelPool> pools;
private final NettyConfiguration configuration;
private NettyNioAsyncHttpClient(DefaultBuilder builder, AttributeMap serviceDefaultsMap) {
this.configuration = new NettyConfiguration(serviceDefaultsMap);
Protocol protocol = serviceDefaultsMap.get(SdkHttpConfigurationOption.PROTOCOL);
this.sdkEventLoopGroup = eventLoopGroup(builder);
Http2Configuration http2Configuration = builder.http2Configuration;
long maxStreams = resolveMaxHttp2Streams(builder.maxHttp2Streams, http2Configuration);
int initialWindowSize = resolveInitialWindowSize(http2Configuration);
this.pools = AwaitCloseChannelPoolMap.builder()
.sdkChannelOptions(builder.sdkChannelOptions)
.configuration(configuration)
.protocol(protocol)
.maxStreams(maxStreams)
.initialWindowSize(initialWindowSize)
.healthCheckPingPeriod(resolveHealthCheckPingPeriod(http2Configuration))
.sdkEventLoopGroup(sdkEventLoopGroup)
.sslProvider(resolveSslProvider(builder))
.proxyConfiguration(builder.proxyConfiguration)
.useNonBlockingDnsResolver(builder.useNonBlockingDnsResolver)
.build();
}
@SdkTestInternalApi
NettyNioAsyncHttpClient(SdkEventLoopGroup sdkEventLoopGroup,
SdkChannelPoolMap<URI, ? extends SdkChannelPool> pools,
NettyConfiguration configuration) {
this.sdkEventLoopGroup = sdkEventLoopGroup;
this.pools = pools;
this.configuration = configuration;
}
@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest request) {
RequestContext ctx = createRequestContext(request);
ctx.metricCollector().reportMetric(HTTP_CLIENT_NAME, clientName()); // TODO: Can't this be done in core?
return new NettyRequestExecutor(ctx).execute();
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Create a {@link NettyNioAsyncHttpClient} with the default properties
*
* @return an {@link NettyNioAsyncHttpClient}
*/
public static SdkAsyncHttpClient create() {
return new DefaultBuilder().build();
}
private RequestContext createRequestContext(AsyncExecuteRequest request) {
SdkChannelPool pool = pools.get(poolKey(request.request()));
return new RequestContext(pool, sdkEventLoopGroup.eventLoopGroup(), request, configuration);
}
private SdkEventLoopGroup eventLoopGroup(DefaultBuilder builder) {
Validate.isTrue(builder.eventLoopGroup == null || builder.eventLoopGroupBuilder == null,
"The eventLoopGroup and the eventLoopGroupFactory can't both be configured.");
return Either.fromNullable(builder.eventLoopGroup, builder.eventLoopGroupBuilder)
.map(e -> e.map(this::nonManagedEventLoopGroup, SdkEventLoopGroup.Builder::build))
.orElseGet(SharedSdkEventLoopGroup::get);
}
private static URI poolKey(SdkHttpRequest sdkRequest) {
return invokeSafely(() -> new URI(sdkRequest.protocol(), null, sdkRequest.host(),
sdkRequest.port(), null, null, null));
}
private SslProvider resolveSslProvider(DefaultBuilder builder) {
if (builder.sslProvider != null) {
return builder.sslProvider;
}
return SslContext.defaultClientProvider();
}
private long resolveMaxHttp2Streams(Integer topLevelValue, Http2Configuration http2Configuration) {
if (topLevelValue != null) {
return topLevelValue;
}
if (http2Configuration == null || http2Configuration.maxStreams() == null) {
return MAX_STREAMS_ALLOWED;
}
return Math.min(http2Configuration.maxStreams(), MAX_STREAMS_ALLOWED);
}
private int resolveInitialWindowSize(Http2Configuration http2Configuration) {
if (http2Configuration == null || http2Configuration.initialWindowSize() == null) {
return DEFAULT_INITIAL_WINDOW_SIZE;
}
return http2Configuration.initialWindowSize();
}
private Duration resolveHealthCheckPingPeriod(Http2Configuration http2Configuration) {
if (http2Configuration != null) {
return http2Configuration.healthCheckPingPeriod();
}
return null;
}
private SdkEventLoopGroup nonManagedEventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
return SdkEventLoopGroup.create(new NonManagedEventLoopGroup(eventLoopGroup.eventLoopGroup()),
eventLoopGroup.channelFactory());
}
@Override
public void close() {
runAndLogError(log, "Unable to close channel pools", pools::close);
runAndLogError(log, "Unable to shutdown event loop", () ->
closeEventLoopUninterruptibly(sdkEventLoopGroup.eventLoopGroup()));
}
private void closeEventLoopUninterruptibly(EventLoopGroup eventLoopGroup) throws ExecutionException {
try {
eventLoopGroup.shutdownGracefully(EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS,
EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS,
TimeUnit.SECONDS)
.get(EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (TimeoutException e) {
log.error(null, () -> String.format("Shutting down Netty EventLoopGroup did not complete within %s seconds",
EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS));
}
}
@Override
public String clientName() {
return CLIENT_NAME;
}
@SdkTestInternalApi
NettyConfiguration configuration() {
return configuration;
}
/**
* Builder that allows configuration of the Netty NIO HTTP implementation. Use {@link #builder()} to configure and construct
* a Netty HTTP client.
*/
public interface Builder extends SdkAsyncHttpClient.Builder<NettyNioAsyncHttpClient.Builder> {
/**
* Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections. For HTTP/2
* the number of connections that will be used depends on the max streams allowed per connection.
*
* <p>
* If the maximum number of concurrent requests is exceeded they may be queued in the HTTP client (see
* {@link #maxPendingConnectionAcquires(Integer)}</p>) and can cause increased latencies. If the client is overloaded
* enough such that the pending connection queue fills up, subsequent requests may be rejected or time out
* (see {@link #connectionAcquisitionTimeout(Duration)}).
*
* @param maxConcurrency New value for max concurrency.
* @return This builder for method chaining.
*/
Builder maxConcurrency(Integer maxConcurrency);
/**
* The maximum number of pending acquires allowed. Once this exceeds, acquire tries will be failed.
*
* @param maxPendingAcquires Max number of pending acquires
* @return This builder for method chaining.
*/
Builder maxPendingConnectionAcquires(Integer maxPendingAcquires);
/**
* The amount of time to wait for a read on a socket before an exception is thrown.
* Specify {@code Duration.ZERO} to disable.
*
* @param readTimeout timeout duration
* @return this builder for method chaining.
*/
Builder readTimeout(Duration readTimeout);
/**
* The amount of time to wait for a write on a socket before an exception is thrown.
* Specify {@code Duration.ZERO} to disable.
*
* @param writeTimeout timeout duration
* @return this builder for method chaining.
*/
Builder writeTimeout(Duration writeTimeout);
/**
* The amount of time to wait when initially establishing a connection before giving up and timing out.
*
* @param timeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionTimeout(Duration timeout);
/**
* The amount of time to wait when acquiring a connection from the pool before giving up and timing out.
* @param connectionAcquisitionTimeout the timeout duration
* @return this builder for method chaining.
*/
Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout);
/**
* The maximum amount of time that a connection should be allowed to remain open, regardless of usage frequency.
*
* Unlike {@link #readTimeout(Duration)} and {@link #writeTimeout(Duration)}, this will never close a connection that
* is currently in use, so long-lived connections may remain open longer than this time. In particular, an HTTP/2
* connection won't be closed as long as there is at least one stream active on the connection.
*/
Builder connectionTimeToLive(Duration connectionTimeToLive);
/**
* Configure the maximum amount of time that a connection should be allowed to remain open while idle. Currently has no
* effect if {@link #useIdleConnectionReaper(Boolean)} is false.
*
* Unlike {@link #readTimeout(Duration)} and {@link #writeTimeout(Duration)}, this will never close a connection that
* is currently in use, so long-lived connections may remain open longer than this time.
*/
Builder connectionMaxIdleTime(Duration maxIdleConnectionTimeout);
/**
* Configure the maximum amount of time that a TLS handshake is allowed to take from the time the CLIENT HELLO
* message is sent to the time the client and server have fully negotiated ciphers and exchanged keys.
* @param tlsNegotiationTimeout the timeout duration
*
* <p>
* By default, it's 10 seconds.
*
* @return this builder for method chaining.
*/
Builder tlsNegotiationTimeout(Duration tlsNegotiationTimeout);
/**
* Configure whether the idle connections in the connection pool should be closed.
* <p>
* When enabled, connections left idling for longer than {@link #connectionMaxIdleTime(Duration)} will be
* closed. This will not close connections currently in use. By default, this is enabled.
*/
Builder useIdleConnectionReaper(Boolean useConnectionReaper);
/**
* Sets the {@link SdkEventLoopGroup} to use for the Netty HTTP client. This event loop group may be shared
* across multiple HTTP clients for better resource and thread utilization. The preferred way to create
* an {@link EventLoopGroup} is by using the {@link SdkEventLoopGroup#builder()} method which will choose the
* optimal implementation per the platform.
*
* <p>The {@link EventLoopGroup} <b>MUST</b> be closed by the caller when it is ready to
* be disposed. The SDK will not close the {@link EventLoopGroup} when the HTTP client is closed. See
* {@link EventLoopGroup#shutdownGracefully()} to properly close the event loop group.</p>
*
* <p>This configuration method is only recommended when you wish to share an {@link EventLoopGroup}
* with multiple clients. If you do not need to share the group it is recommended to use
* {@link #eventLoopGroupBuilder(SdkEventLoopGroup.Builder)} as the SDK will handle its cleanup when
* the HTTP client is closed.</p>
*
* @param eventLoopGroup Netty {@link SdkEventLoopGroup} to use.
* @return This builder for method chaining.
* @see SdkEventLoopGroup
*/
Builder eventLoopGroup(SdkEventLoopGroup eventLoopGroup);
/**
* Sets the {@link SdkEventLoopGroup.Builder} which will be used to create the {@link SdkEventLoopGroup} for the Netty
* HTTP client. This allows for custom configuration of the Netty {@link EventLoopGroup}.
*
* <p>The {@link EventLoopGroup} created by the builder is managed by the SDK and will be shutdown
* when the HTTP client is closed.</p>
*
* <p>This is the preferred configuration method when you just want to customize the {@link EventLoopGroup}
* but not share it across multiple HTTP clients. If you do wish to share an {@link EventLoopGroup}, see
* {@link #eventLoopGroup(SdkEventLoopGroup)}</p>
*
* @param eventLoopGroupBuilder {@link SdkEventLoopGroup.Builder} to use.
* @return This builder for method chaining.
* @see SdkEventLoopGroup.Builder
*/
Builder eventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder);
/**
* Sets the HTTP protocol to use (i.e. HTTP/1.1 or HTTP/2). Not all services support HTTP/2.
*
* @param protocol Protocol to use.
* @return This builder for method chaining.
*/
Builder protocol(Protocol protocol);
/**
* Configure whether to enable or disable TCP KeepAlive.
* The configuration will be passed to the socket option {@link SocketOptions#SO_KEEPALIVE}.
* <p>
* By default, this is disabled.
* <p>
* When enabled, the actual KeepAlive mechanism is dependent on the Operating System and therefore additional TCP
* KeepAlive values (like timeout, number of packets, etc) must be configured via the Operating System (sysctl on
* Linux/Mac, and Registry values on Windows).
*/
Builder tcpKeepAlive(Boolean keepConnectionAlive);
/**
* Configures additional {@link ChannelOption} which will be used to create Netty Http client. This allows custom
* configuration for Netty.
*
* <p>
* If a {@link ChannelOption} was previously configured, the old value is replaced.
*
* @param channelOption {@link ChannelOption} to set
* @param value See {@link ChannelOption} to find the type of value for each option
* @return This builder for method chaining.
*/
Builder putChannelOption(ChannelOption channelOption, Object value);
/**
* Sets the max number of concurrent streams for an HTTP/2 connection. This setting is only respected when the HTTP/2
* protocol is used.
*
* <p>Note that this cannot exceed the value of the MAX_CONCURRENT_STREAMS setting returned by the service. If it
* does the service setting is used instead.</p>
*
* @param maxHttp2Streams Max concurrent HTTP/2 streams per connection.
* @return This builder for method chaining.
*
* @deprecated Use {@link #http2Configuration(Http2Configuration)} along with
* {@link Http2Configuration.Builder#maxStreams(Long)} instead.
*/
Builder maxHttp2Streams(Integer maxHttp2Streams);
/**
* Sets the {@link SslProvider} to be used in the Netty client.
*
* <p>If not configured, {@link SslContext#defaultClientProvider()} will be used to determine the SslProvider.
*
* <p>Note that you might need to add other dependencies if not using JDK's default Ssl Provider.
* See https://netty.io/wiki/requirements-for-4.x.html#transport-security-tls
*
* @param sslProvider the SslProvider
* @return the builder of the method chaining.
*/
Builder sslProvider(SslProvider sslProvider);
/**
* Set the proxy configuration for this client. The configured proxy will be used to proxy any HTTP request
* destined for any host that does not match any of the hosts in configured non proxy hosts.
*
* @param proxyConfiguration The proxy configuration.
* @return The builder for method chaining.
* @see ProxyConfiguration#nonProxyHosts()
*/
Builder proxyConfiguration(ProxyConfiguration proxyConfiguration);
/**
* Set the {@link TlsKeyManagersProvider} for this client. The {@code KeyManager}s will be used by the client to
* authenticate itself with the remote server if necessary when establishing the TLS connection.
* <p>
* If no provider is configured, the client will default to {@link SystemPropertyTlsKeyManagersProvider}. To
* disable any automatic resolution via the system properties, use {@link TlsKeyManagersProvider#noneProvider()}.
*
* @param keyManagersProvider The {@code TlsKeyManagersProvider}.
* @return The builder for method chaining.
*/
Builder tlsKeyManagersProvider(TlsKeyManagersProvider keyManagersProvider);
/**
* Configure the {@link TlsTrustManagersProvider} that will provide the {@link javax.net.ssl.TrustManager}s to use
* when constructing the SSL context.
*
* @param trustManagersProvider The {@code TlsKeyManagersProvider}.
* @return The builder for method chaining.
*/
Builder tlsTrustManagersProvider(TlsTrustManagersProvider trustManagersProvider);
/**
* Set the HTTP/2 specific configuration for this client.
* <p>
* <b>Note:</b>If {@link #maxHttp2Streams(Integer)} and {@link Http2Configuration#maxStreams()} are both set,
* the value set using {@link #maxHttp2Streams(Integer)} takes precedence.
*
* @param http2Configuration The HTTP/2 configuration object.
* @return the builder for method chaining.
*/
Builder http2Configuration(Http2Configuration http2Configuration);
/**
* Set the HTTP/2 specific configuration for this client.
* <p>
* <b>Note:</b>If {@link #maxHttp2Streams(Integer)} and {@link Http2Configuration#maxStreams()} are both set,
* the value set using {@link #maxHttp2Streams(Integer)} takes precedence.
*
* @param http2ConfigurationBuilderConsumer The consumer of the HTTP/2 configuration builder object.
* @return the builder for method chaining.
*/
Builder http2Configuration(Consumer<Http2Configuration.Builder> http2ConfigurationBuilderConsumer);
/**
* Configure whether to use a non-blocking dns resolver or not. False by default, as netty's default dns resolver is
* blocking; it namely calls java.net.InetAddress.getByName.
* <p>
* When enabled, a non-blocking dns resolver will be used instead, by modifying netty's bootstrap configuration.
* See https://netty.io/news/2016/05/26/4-1-0-Final.html
*/
Builder useNonBlockingDnsResolver(Boolean useNonBlockingDnsResolver);
}
/**
* Factory that allows more advanced configuration of the Netty NIO HTTP implementation. Use {@link #builder()} to
* configure and construct an immutable instance of the factory.
*/
private static final class DefaultBuilder implements Builder {
private final AttributeMap.Builder standardOptions = AttributeMap.builder();
private SdkChannelOptions sdkChannelOptions = new SdkChannelOptions();
private SdkEventLoopGroup eventLoopGroup;
private SdkEventLoopGroup.Builder eventLoopGroupBuilder;
private Integer maxHttp2Streams;
private Http2Configuration http2Configuration;
private SslProvider sslProvider;
private ProxyConfiguration proxyConfiguration;
private Boolean useNonBlockingDnsResolver;
private DefaultBuilder() {
}
@Override
public Builder maxConcurrency(Integer maxConcurrency) {
standardOptions.put(SdkHttpConfigurationOption.MAX_CONNECTIONS, maxConcurrency);
return this;
}
public void setMaxConcurrency(Integer maxConnectionsPerEndpoint) {
maxConcurrency(maxConnectionsPerEndpoint);
}
@Override
public Builder maxPendingConnectionAcquires(Integer maxPendingAcquires) {
standardOptions.put(SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES, maxPendingAcquires);
return this;
}
public void setMaxPendingConnectionAcquires(Integer maxPendingAcquires) {
maxPendingConnectionAcquires(maxPendingAcquires);
}
@Override
public Builder readTimeout(Duration readTimeout) {
Validate.isNotNegative(readTimeout, "readTimeout");
standardOptions.put(SdkHttpConfigurationOption.READ_TIMEOUT, readTimeout);
return this;
}
public void setReadTimeout(Duration readTimeout) {
readTimeout(readTimeout);
}
@Override
public Builder writeTimeout(Duration writeTimeout) {
Validate.isNotNegative(writeTimeout, "writeTimeout");
standardOptions.put(SdkHttpConfigurationOption.WRITE_TIMEOUT, writeTimeout);
return this;
}
public void setWriteTimeout(Duration writeTimeout) {
writeTimeout(writeTimeout);
}
@Override
public Builder connectionTimeout(Duration timeout) {
Validate.isPositive(timeout, "connectionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, timeout);
return this;
}
public void setConnectionTimeout(Duration connectionTimeout) {
connectionTimeout(connectionTimeout);
}
@Override
public Builder connectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
Validate.isPositive(connectionAcquisitionTimeout, "connectionAcquisitionTimeout");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT, connectionAcquisitionTimeout);
return this;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
connectionAcquisitionTimeout(connectionAcquisitionTimeout);
}
@Override
public Builder connectionTimeToLive(Duration connectionTimeToLive) {
Validate.isNotNegative(connectionTimeToLive, "connectionTimeToLive");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE, connectionTimeToLive);
return this;
}
public void setConnectionTimeToLive(Duration connectionTimeToLive) {
connectionTimeToLive(connectionTimeToLive);
}
@Override
public Builder connectionMaxIdleTime(Duration connectionMaxIdleTime) {
Validate.isPositive(connectionMaxIdleTime, "connectionMaxIdleTime");
standardOptions.put(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT, connectionMaxIdleTime);
return this;
}
public void setConnectionMaxIdleTime(Duration connectionMaxIdleTime) {
connectionMaxIdleTime(connectionMaxIdleTime);
}
@Override
public Builder useIdleConnectionReaper(Boolean useIdleConnectionReaper) {
standardOptions.put(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS, useIdleConnectionReaper);
return this;
}
public void setUseIdleConnectionReaper(Boolean useIdleConnectionReaper) {
useIdleConnectionReaper(useIdleConnectionReaper);
}
@Override
public Builder tlsNegotiationTimeout(Duration tlsNegotiationTimeout) {
Validate.isPositive(tlsNegotiationTimeout, "tlsNegotiationTimeout");
standardOptions.put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT, tlsNegotiationTimeout);
return this;
}
public void setTlsNegotiationTimeout(Duration tlsNegotiationTimeout) {
tlsNegotiationTimeout(tlsNegotiationTimeout);
}
@Override
public Builder eventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
this.eventLoopGroup = eventLoopGroup;
return this;
}
public void setEventLoopGroup(SdkEventLoopGroup eventLoopGroup) {
eventLoopGroup(eventLoopGroup);
}
@Override
public Builder eventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder) {
this.eventLoopGroupBuilder = eventLoopGroupBuilder;
return this;
}
public void setEventLoopGroupBuilder(SdkEventLoopGroup.Builder eventLoopGroupBuilder) {
eventLoopGroupBuilder(eventLoopGroupBuilder);
}
@Override
public Builder protocol(Protocol protocol) {
standardOptions.put(SdkHttpConfigurationOption.PROTOCOL, protocol);
return this;
}
public void setProtocol(Protocol protocol) {
protocol(protocol);
}
@Override
public Builder tcpKeepAlive(Boolean keepConnectionAlive) {
standardOptions.put(SdkHttpConfigurationOption.TCP_KEEPALIVE, keepConnectionAlive);
return this;
}
public void setTcpKeepAlive(Boolean keepConnectionAlive) {
tcpKeepAlive(keepConnectionAlive);
}
@Override
public Builder putChannelOption(ChannelOption channelOption, Object value) {
this.sdkChannelOptions.putOption(channelOption, value);
return this;
}
@Override
public Builder maxHttp2Streams(Integer maxHttp2Streams) {
this.maxHttp2Streams = maxHttp2Streams;
return this;
}
public void setMaxHttp2Streams(Integer maxHttp2Streams) {
maxHttp2Streams(maxHttp2Streams);
}
@Override
public Builder sslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider;
return this;
}
public void setSslProvider(SslProvider sslProvider) {
sslProvider(sslProvider);
}
@Override
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
proxyConfiguration(proxyConfiguration);
}
@Override
public Builder tlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
this.standardOptions.put(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER, tlsKeyManagersProvider);
return this;
}
public void setTlsKeyManagersProvider(TlsKeyManagersProvider tlsKeyManagersProvider) {
tlsKeyManagersProvider(tlsKeyManagersProvider);
}
@Override
public Builder tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
standardOptions.put(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER, tlsTrustManagersProvider);
return this;
}
public void setTlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) {
tlsTrustManagersProvider(tlsTrustManagersProvider);
}
@Override
public Builder http2Configuration(Http2Configuration http2Configuration) {
this.http2Configuration = http2Configuration;
return this;
}
@Override
public Builder http2Configuration(Consumer<Http2Configuration.Builder> http2ConfigurationBuilderConsumer) {
Http2Configuration.Builder builder = Http2Configuration.builder();
http2ConfigurationBuilderConsumer.accept(builder);
return http2Configuration(builder.build());
}
public void setHttp2Configuration(Http2Configuration http2Configuration) {
http2Configuration(http2Configuration);
}
@Override
public Builder useNonBlockingDnsResolver(Boolean useNonBlockingDnsResolver) {
this.useNonBlockingDnsResolver = useNonBlockingDnsResolver;
return this;
}
public void setUseNonBlockingDnsResolver(Boolean useNonBlockingDnsResolver) {
useNonBlockingDnsResolver(useNonBlockingDnsResolver);
}
@Override
public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) {
if (standardOptions.get(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT) == null) {
standardOptions.put(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT,
standardOptions.get(SdkHttpConfigurationOption.CONNECTION_TIMEOUT));
}
return new NettyNioAsyncHttpClient(this, standardOptions.build()
.merge(serviceDefaults)
.merge(NETTY_HTTP_DEFAULTS)
.merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS));
}
}
}
| 1,111 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/NettySdkAsyncHttpService.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpService;
/**
* Service binding for the Netty default implementation. Allows SDK to pick this up automatically from the classpath.
*/
@SdkPublicApi
public class NettySdkAsyncHttpService implements SdkAsyncHttpService {
@Override
public SdkAsyncHttpClient.Builder createAsyncHttpClientFactory() {
return NettyNioAsyncHttpClient.builder();
}
}
| 1,112 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/Http2Configuration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration specific to HTTP/2 connections.
*/
@SdkPublicApi
public final class Http2Configuration implements ToCopyableBuilder<Http2Configuration.Builder, Http2Configuration> {
private final Long maxStreams;
private final Integer initialWindowSize;
private final Duration healthCheckPingPeriod;
private Http2Configuration(DefaultBuilder builder) {
this.maxStreams = builder.maxStreams;
this.initialWindowSize = builder.initialWindowSize;
this.healthCheckPingPeriod = builder.healthCheckPingPeriod;
}
/**
* @return The maximum number of streams to be created per HTTP/2 connection.
*/
public Long maxStreams() {
return maxStreams;
}
/**
* @return The initial window size for an HTTP/2 stream.
*/
public Integer initialWindowSize() {
return initialWindowSize;
}
/**
* @return The health check period for an HTTP/2 connection.
*/
public Duration healthCheckPingPeriod() {
return healthCheckPingPeriod;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Http2Configuration that = (Http2Configuration) o;
if (maxStreams != null ? !maxStreams.equals(that.maxStreams) : that.maxStreams != null) {
return false;
}
return initialWindowSize != null ? initialWindowSize.equals(that.initialWindowSize) : that.initialWindowSize == null;
}
@Override
public int hashCode() {
int result = maxStreams != null ? maxStreams.hashCode() : 0;
result = 31 * result + (initialWindowSize != null ? initialWindowSize.hashCode() : 0);
return result;
}
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder extends CopyableBuilder<Builder, Http2Configuration> {
/**
* Sets the max number of concurrent streams per connection.
*
* <p>Note that this cannot exceed the value of the MAX_CONCURRENT_STREAMS setting returned by the service. If it
* does the service setting is used instead.</p>
*
* @param maxStreams Max concurrent HTTP/2 streams per connection.
* @return This builder for method chaining.
*/
Builder maxStreams(Long maxStreams);
/**
* Sets initial window size of a stream. This setting is only respected when the HTTP/2 protocol is used.
*
* See <a href="https://tools.ietf.org/html/rfc7540#section-6.5.2">https://tools.ietf.org/html/rfc7540#section-6.5.2</a>
* for more information about this parameter.
*
* @param initialWindowSize The initial window size of a stream.
* @return This builder for method chaining.
*/
Builder initialWindowSize(Integer initialWindowSize);
/**
* Sets the period that the Netty client will send {@code PING} frames to the remote endpoint to check the
* health of the connection. The default value is {@link
* software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration#HTTP2_CONNECTION_PING_TIMEOUT_SECONDS}. To
* disable this feature, set a duration of 0.
*
* @param healthCheckPingPeriod The ping period.
* @return This builder for method chaining.
*/
Builder healthCheckPingPeriod(Duration healthCheckPingPeriod);
}
private static final class DefaultBuilder implements Builder {
private Long maxStreams;
private Integer initialWindowSize;
private Duration healthCheckPingPeriod;
private DefaultBuilder() {
}
private DefaultBuilder(Http2Configuration http2Configuration) {
this.maxStreams = http2Configuration.maxStreams;
this.initialWindowSize = http2Configuration.initialWindowSize;
this.healthCheckPingPeriod = http2Configuration.healthCheckPingPeriod;
}
@Override
public Builder maxStreams(Long maxStreams) {
this.maxStreams = Validate.isPositiveOrNull(maxStreams, "maxStreams");
return this;
}
public void setMaxStreams(Long maxStreams) {
maxStreams(maxStreams);
}
@Override
public Builder initialWindowSize(Integer initialWindowSize) {
this.initialWindowSize = Validate.isPositiveOrNull(initialWindowSize, "initialWindowSize");
return this;
}
public void setInitialWindowSize(Integer initialWindowSize) {
initialWindowSize(initialWindowSize);
}
@Override
public Builder healthCheckPingPeriod(Duration healthCheckPingPeriod) {
this.healthCheckPingPeriod = healthCheckPingPeriod;
return this;
}
public void setHealthCheckPingPeriod(Duration healthCheckPingPeriod) {
healthCheckPingPeriod(healthCheckPingPeriod);
}
@Override
public Http2Configuration build() {
return new Http2Configuration(this);
}
}
}
| 1,113 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/IdleConnectionReaperHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* A handler that closes unused channels that have not had any traffic on them for a configurable amount of time.
*/
@SdkInternalApi
public class IdleConnectionReaperHandler extends IdleStateHandler {
private static final NettyClientLogger log = NettyClientLogger.getLogger(IdleConnectionReaperHandler.class);
private final int maxIdleTimeMillis;
public IdleConnectionReaperHandler(int maxIdleTimeMillis) {
super(0, 0, maxIdleTimeMillis, TimeUnit.MILLISECONDS);
this.maxIdleTimeMillis = maxIdleTimeMillis;
}
@Override
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent event) {
assert ctx.channel().eventLoop().inEventLoop();
boolean channelNotInUse = Boolean.FALSE.equals(ctx.channel().attr(ChannelAttributeKey.IN_USE).get());
if (channelNotInUse && ctx.channel().isOpen()) {
log.debug(ctx.channel(), () -> "Closing unused connection (" + ctx.channel().id() + ") because it has been idle for "
+ "longer than " + maxIdleTimeMillis + " milliseconds.");
ctx.close();
}
}
}
| 1,114 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SimpleChannelPoolAwareChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
final class SimpleChannelPoolAwareChannelPool implements SdkChannelPool {
private final SdkChannelPool delegate;
private final BetterSimpleChannelPool simpleChannelPool;
SimpleChannelPoolAwareChannelPool(SdkChannelPool delegate, BetterSimpleChannelPool simpleChannelPool) {
this.delegate = delegate;
this.simpleChannelPool = simpleChannelPool;
}
@Override
public Future<Channel> acquire() {
return delegate.acquire();
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
return delegate.acquire(promise);
}
@Override
public Future<Void> release(Channel channel) {
return delegate.release(channel);
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
return delegate.release(channel, promise);
}
@Override
public void close() {
delegate.close();
}
public BetterSimpleChannelPool underlyingSimpleChannelPool() {
return simpleChannelPool;
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
return delegate.collectChannelPoolMetrics(metrics);
}
}
| 1,115 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/OneTimeReadTimeoutHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A one-time read timeout handler that removes itself from the pipeline after
* the next successful read.
*/
@SdkInternalApi
public final class OneTimeReadTimeoutHandler extends ReadTimeoutHandler {
OneTimeReadTimeoutHandler(Duration timeout) {
super(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.pipeline().remove(this);
super.channelRead(ctx, msg);
}
}
| 1,116 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/StaticKeyManagerFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Factory that simply returns a statically provided set of {@link KeyManager}s.
*/
@SdkInternalApi
public final class StaticKeyManagerFactory extends KeyManagerFactory {
private StaticKeyManagerFactory(KeyManager[] keyManagers) {
super(new StaticKeyManagerFactorySpi(keyManagers), null, null);
}
public static StaticKeyManagerFactory create(KeyManager[] keyManagers) {
return new StaticKeyManagerFactory(keyManagers);
}
}
| 1,117 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/CancellableAcquireChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* Simple decorator {@link ChannelPool} that attempts to complete the promise
* given to {@link #acquire(Promise)} with the channel acquired from the underlying
* pool. If it fails (because the promise is already done), the acquired channel
* is closed then released back to the delegate.
*/
@SdkInternalApi
public final class CancellableAcquireChannelPool implements SdkChannelPool {
private final EventExecutor executor;
private final SdkChannelPool delegatePool;
public CancellableAcquireChannelPool(EventExecutor executor, SdkChannelPool delegatePool) {
this.executor = executor;
this.delegatePool = delegatePool;
}
@Override
public Future<Channel> acquire() {
return this.acquire(executor.newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> acquirePromise) {
Future<Channel> channelFuture = delegatePool.acquire(executor.newPromise());
channelFuture.addListener((Future<Channel> f) -> {
if (f.isSuccess()) {
Channel ch = f.getNow();
if (!acquirePromise.trySuccess(ch)) {
ch.close().addListener(closeFuture -> delegatePool.release(ch));
}
} else {
acquirePromise.tryFailure(f.cause());
}
});
return acquirePromise;
}
@Override
public Future<Void> release(Channel channel) {
return delegatePool.release(channel);
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
return delegatePool.release(channel, promise);
}
@Override
public void close() {
delegatePool.close();
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
return delegatePool.collectChannelPoolMetrics(metrics);
}
}
| 1,118 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyRequestExecutor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.HttpMetric.CONCURRENCY_ACQUIRE_DURATION;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTE_FUTURE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTION_ID_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_COMPLETE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_CONTENT_LENGTH;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_DATA_READ;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.STREAMING_COMPLETE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.NettyRequestMetrics.measureTimeTaken;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import io.netty.util.Attribute;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.http2.FlushOnReadHandler;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2StreamExceptionHandler;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2ToHttpInboundAdapter;
import software.amazon.awssdk.http.nio.netty.internal.http2.HttpToHttp2OutboundAdapter;
import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler;
import software.amazon.awssdk.http.nio.netty.internal.nrs.StreamedHttpRequest;
import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class NettyRequestExecutor {
private static final NettyClientLogger log = NettyClientLogger.getLogger(NettyRequestExecutor.class);
private static final RequestAdapter REQUEST_ADAPTER_HTTP2 = new RequestAdapter(Protocol.HTTP2);
private static final RequestAdapter REQUEST_ADAPTER_HTTP1_1 = new RequestAdapter(Protocol.HTTP1_1);
private static final AtomicLong EXECUTION_COUNTER = new AtomicLong(0L);
private final long executionId = EXECUTION_COUNTER.incrementAndGet();
private final RequestContext context;
private CompletableFuture<Void> executeFuture;
private Channel channel;
private RequestAdapter requestAdapter;
public NettyRequestExecutor(RequestContext context) {
this.context = context;
}
@SuppressWarnings("unchecked")
public CompletableFuture<Void> execute() {
Promise<Channel> channelFuture = context.eventLoopGroup().next().newPromise();
executeFuture = createExecutionFuture(channelFuture);
acquireChannel(channelFuture);
channelFuture.addListener((GenericFutureListener) this::makeRequestListener);
return executeFuture;
}
private void acquireChannel(Promise<Channel> channelFuture) {
NettyRequestMetrics.ifMetricsAreEnabled(context.metricCollector(), metrics -> {
measureTimeTaken(channelFuture, duration -> {
metrics.reportMetric(CONCURRENCY_ACQUIRE_DURATION, duration);
});
});
context.channelPool().acquire(channelFuture);
}
/**
* Convenience method to create the execution future and set up the cancellation logic.
*
* @param channelPromise The Netty future holding the channel.
*
* @return The created execution future.
*/
private CompletableFuture<Void> createExecutionFuture(Promise<Channel> channelPromise) {
CompletableFuture<Void> metricsFuture = initiateMetricsCollection();
CompletableFuture<Void> future = new CompletableFuture<>();
future.whenComplete((r, t) -> {
verifyMetricsWereCollected(metricsFuture);
if (t == null) {
return;
}
if (!channelPromise.tryFailure(t)) {
// Couldn't fail promise, it's already done
if (!channelPromise.isSuccess()) {
return;
}
Channel ch = channelPromise.getNow();
try {
ch.eventLoop().submit(() -> {
Attribute<Long> executionIdKey = ch.attr(EXECUTION_ID_KEY);
if (ch.attr(IN_USE) != null && ch.attr(IN_USE).get() && executionIdKey != null) {
ch.pipeline().fireExceptionCaught(new FutureCancelledException(this.executionId, t));
} else {
ch.close().addListener(closeFuture -> context.channelPool().release(ch));
}
});
} catch (Throwable exc) {
log.warn(ch, () -> "Unable to add a task to cancel the request to channel's EventLoop", exc);
}
}
});
return future;
}
private CompletableFuture<Void> initiateMetricsCollection() {
MetricCollector metricCollector = context.metricCollector();
if (!NettyRequestMetrics.metricsAreEnabled(metricCollector)) {
return null;
}
return context.channelPool().collectChannelPoolMetrics(metricCollector);
}
private void verifyMetricsWereCollected(CompletableFuture<Void> metricsFuture) {
if (metricsFuture == null) {
return;
}
if (!metricsFuture.isDone()) {
log.debug(null, () -> "HTTP request metric collection did not finish in time, so results may be incomplete.");
metricsFuture.cancel(false);
return;
}
metricsFuture.exceptionally(t -> {
log.debug(null, () -> "HTTP request metric collection failed, so results may be incomplete.", t);
return null;
});
}
private void makeRequestListener(Future<Channel> channelFuture) {
if (channelFuture.isSuccess()) {
channel = channelFuture.getNow();
NettyUtils.doInEventLoop(channel.eventLoop(), () -> {
try {
configureChannel();
configurePipeline();
makeRequest();
} catch (Throwable t) {
closeAndRelease(channel);
handleFailure(channel, () -> "Failed to initiate request to " + endpoint(), t);
}
});
} else {
handleFailure(channel, () -> "Failed to create connection to " + endpoint(), channelFuture.cause());
}
}
private void configureChannel() {
channel.attr(EXECUTION_ID_KEY).set(executionId);
channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture);
channel.attr(REQUEST_CONTEXT_KEY).set(context);
channel.attr(RESPONSE_COMPLETE_KEY).set(false);
channel.attr(STREAMING_COMPLETE_KEY).set(false);
channel.attr(RESPONSE_CONTENT_LENGTH).set(null);
channel.attr(RESPONSE_DATA_READ).set(null);
channel.attr(CHANNEL_DIAGNOSTICS).get().incrementRequestCount();
}
private void configurePipeline() throws IOException {
Protocol protocol = ChannelAttributeKey.getProtocolNow(channel);
ChannelPipeline pipeline = channel.pipeline();
switch (protocol) {
case HTTP2:
pipeline.addLast(new Http2ToHttpInboundAdapter());
pipeline.addLast(new HttpToHttp2OutboundAdapter());
pipeline.addLast(Http2StreamExceptionHandler.create());
requestAdapter = REQUEST_ADAPTER_HTTP2;
break;
case HTTP1_1:
requestAdapter = REQUEST_ADAPTER_HTTP1_1;
break;
default:
throw new IOException("Unknown protocol: " + protocol);
}
if (protocol == Protocol.HTTP2) {
pipeline.addLast(FlushOnReadHandler.getInstance());
}
pipeline.addLast(new HttpStreamsClientHandler());
pipeline.addLast(ResponseHandler.getInstance());
// It's possible that the channel could become inactive between checking it out from the pool, and adding our response
// handler (which will monitor for it going inactive from now on).
// Make sure it's active here, or the request will never complete: https://github.com/aws/aws-sdk-java-v2/issues/1207
if (!channel.isActive()) {
throw new IOException(NettyUtils.closedChannelMessage(channel));
}
}
private void makeRequest() {
HttpRequest request = requestAdapter.adapt(context.executeRequest().request());
writeRequest(request);
}
private void writeRequest(HttpRequest request) {
channel.pipeline().addFirst(new WriteTimeoutHandler(context.configuration().writeTimeoutMillis(),
TimeUnit.MILLISECONDS));
StreamedRequest streamedRequest = new StreamedRequest(request,
context.executeRequest().requestContentPublisher());
channel.writeAndFlush(streamedRequest)
.addListener(wireCall -> {
// Done writing so remove the idle write timeout handler
ChannelUtils.removeIfExists(channel.pipeline(), WriteTimeoutHandler.class);
if (wireCall.isSuccess()) {
NettyRequestMetrics.publishHttp2StreamMetrics(context.metricCollector(), channel);
if (context.executeRequest().fullDuplex()) {
return;
}
channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeoutMillis(),
TimeUnit.MILLISECONDS));
channel.read();
} else {
// TODO: Are there cases where we can keep the channel open?
closeAndRelease(channel);
handleFailure(channel, () -> "Failed to make request to " + endpoint(), wireCall.cause());
}
});
if (shouldExplicitlyTriggerRead()) {
// Should only add an one-time ReadTimeoutHandler to 100 Continue request.
if (is100ContinueExpected()) {
channel.pipeline().addFirst(new OneTimeReadTimeoutHandler(Duration.ofMillis(context.configuration()
.readTimeoutMillis())));
} else {
channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeoutMillis(),
TimeUnit.MILLISECONDS));
}
channel.read();
}
}
/**
* It should explicitly trigger Read for the following situations:
*
* - FullDuplex calls need to start reading at the same time we make the request.
* - Request with "Expect: 100-continue" header should read the 100 continue response.
*
* @return true if it should explicitly read from channel
*/
private boolean shouldExplicitlyTriggerRead() {
return context.executeRequest().fullDuplex() || is100ContinueExpected();
}
private boolean is100ContinueExpected() {
return context.executeRequest()
.request()
.firstMatchingHeader("Expect")
.filter(b -> b.equalsIgnoreCase("100-continue"))
.isPresent();
}
private URI endpoint() {
return context.executeRequest().request().getUri();
}
private void handleFailure(Channel channel, Supplier<String> msgSupplier, Throwable cause) {
log.debug(channel, msgSupplier, cause);
cause = NettyUtils.decorateException(channel, cause);
context.handler().onError(cause);
executeFuture.completeExceptionally(cause);
}
/**
* Close and release the channel back to the pool.
*
* @param channel The channel.
*/
private void closeAndRelease(Channel channel) {
log.trace(channel, () -> String.format("closing and releasing channel %s", channel.id().asLongText()));
channel.attr(KEEP_ALIVE).set(false);
channel.close();
context.channelPool().release(channel);
}
/**
* Just delegates to {@link HttpRequest} for all methods.
*/
static class DelegateHttpRequest implements HttpRequest {
protected final HttpRequest request;
DelegateHttpRequest(HttpRequest request) {
this.request = request;
}
@Override
public HttpRequest setMethod(HttpMethod method) {
this.request.setMethod(method);
return this;
}
@Override
public HttpRequest setUri(String uri) {
this.request.setUri(uri);
return this;
}
@Override
public HttpMethod getMethod() {
return this.request.method();
}
@Override
public HttpMethod method() {
return request.method();
}
@Override
public String getUri() {
return this.request.uri();
}
@Override
public String uri() {
return request.uri();
}
@Override
public HttpVersion getProtocolVersion() {
return this.request.protocolVersion();
}
@Override
public HttpVersion protocolVersion() {
return request.protocolVersion();
}
@Override
public HttpRequest setProtocolVersion(HttpVersion version) {
this.request.setProtocolVersion(version);
return this;
}
@Override
public HttpHeaders headers() {
return this.request.headers();
}
@Override
public DecoderResult getDecoderResult() {
return this.request.decoderResult();
}
@Override
public DecoderResult decoderResult() {
return request.decoderResult();
}
@Override
public void setDecoderResult(DecoderResult result) {
this.request.setDecoderResult(result);
}
@Override
public String toString() {
return this.getClass().getName() + "(" + this.request.toString() + ")";
}
}
/**
* Decorator around {@link StreamedHttpRequest} to adapt a publisher of {@link ByteBuffer} (i.e. {@link
* software.amazon.awssdk.http.async.SdkHttpContentPublisher}) to a publisher of {@link HttpContent}.
* <p>
* This publisher also prevents the adapted publisher from publishing more content to the subscriber than
* the specified 'Content-Length' of the request.
*/
private static class StreamedRequest extends DelegateHttpRequest implements StreamedHttpRequest {
private final Publisher<ByteBuffer> publisher;
private final Optional<Long> requestContentLength;
private long written = 0L;
private boolean done;
private Subscription subscription;
StreamedRequest(HttpRequest request, Publisher<ByteBuffer> publisher) {
super(request);
this.publisher = publisher;
this.requestContentLength = contentLength(request);
}
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
publisher.subscribe(new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription subscription) {
StreamedRequest.this.subscription = subscription;
subscriber.onSubscribe(subscription);
}
@Override
public void onNext(ByteBuffer contentBytes) {
if (done) {
return;
}
try {
int newLimit = clampedBufferLimit(contentBytes.remaining());
contentBytes.limit(contentBytes.position() + newLimit);
ByteBuf contentByteBuf = Unpooled.wrappedBuffer(contentBytes);
HttpContent content = new DefaultHttpContent(contentByteBuf);
subscriber.onNext(content);
written += newLimit;
if (!shouldContinuePublishing()) {
done = true;
subscription.cancel();
subscriber.onComplete();
}
} catch (Throwable t) {
onError(t);
}
}
@Override
public void onError(Throwable t) {
if (!done) {
done = true;
subscription.cancel();
subscriber.onError(t);
}
}
@Override
public void onComplete() {
if (!done) {
Long expectedContentLength = requestContentLength.orElse(null);
if (expectedContentLength != null && written < expectedContentLength) {
onError(new IllegalStateException("Request content was only " + written + " bytes, but the specified "
+ "content-length was " + expectedContentLength + " bytes."));
} else {
done = true;
subscriber.onComplete();
}
}
}
});
}
private int clampedBufferLimit(int bufLen) {
return requestContentLength.map(cl ->
(int) Math.min(cl - written, bufLen)
).orElse(bufLen);
}
private boolean shouldContinuePublishing() {
return requestContentLength.map(cl -> written < cl).orElse(true);
}
private static Optional<Long> contentLength(HttpRequest request) {
String value = request.headers().get("Content-Length");
if (value != null) {
try {
return Optional.of(Long.parseLong(value));
} catch (NumberFormatException e) {
log.warn(null, () -> "Unable to parse 'Content-Length' header. Treating it as non existent.");
}
}
return Optional.empty();
}
}
}
| 1,119 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/OldConnectionReaperHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.utils.Validate;
/**
* A handler that will close channels after they have reached their time-to-live, regardless of usage.
*
* Channels that are not in use will be closed immediately, and channels that are in use will be closed when they are next
* released to the underlying connection pool (via {@link ChannelAttributeKey#CLOSE_ON_RELEASE}).
*/
@SdkInternalApi
public class OldConnectionReaperHandler extends ChannelDuplexHandler {
private static final NettyClientLogger log = NettyClientLogger.getLogger(OldConnectionReaperHandler.class);
private final int connectionTtlMillis;
private ScheduledFuture<?> channelKiller;
public OldConnectionReaperHandler(int connectionTtlMillis) {
Validate.isPositive(connectionTtlMillis, "connectionTtlMillis");
this.connectionTtlMillis = connectionTtlMillis;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
initialize(ctx);
super.handlerAdded(ctx);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
initialize(ctx);
super.channelActive(ctx);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
initialize(ctx);
super.channelRegistered(ctx);
}
private void initialize(ChannelHandlerContext ctx) {
if (channelKiller == null) {
channelKiller = ctx.channel().eventLoop().schedule(() -> closeChannel(ctx),
connectionTtlMillis,
TimeUnit.MILLISECONDS);
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
destroy();
}
private void destroy() {
if (channelKiller != null) {
channelKiller.cancel(false);
channelKiller = null;
}
}
private void closeChannel(ChannelHandlerContext ctx) {
assert ctx.channel().eventLoop().inEventLoop();
if (ctx.channel().isOpen()) {
if (Boolean.FALSE.equals(ctx.channel().attr(ChannelAttributeKey.IN_USE).get())) {
log.debug(ctx.channel(), () -> "Closing unused connection (" + ctx.channel().id() + ") because it has reached "
+ "its maximum time to live of " + connectionTtlMillis + " milliseconds.");
ctx.close();
} else {
log.debug(ctx.channel(), () -> "Connection (" + ctx.channel().id() + ") will be closed during its next release, "
+ "because it has reached its maximum time to live of " + connectionTtlMillis
+ " milliseconds.");
ctx.channel().attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true);
}
}
channelKiller = null;
}
}
| 1,120 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/AutoReadEnableChannelPoolListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Enables auto read on idle channels so that any data that a service sends while it's idling can be handled.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class AutoReadEnableChannelPoolListener implements ListenerInvokingChannelPool.ChannelPoolListener {
private static final AutoReadEnableChannelPoolListener INSTANCE = new AutoReadEnableChannelPoolListener();
private AutoReadEnableChannelPoolListener() {
}
@Override
public void channelReleased(Channel channel) {
channel.config().setAutoRead(true);
}
public static AutoReadEnableChannelPoolListener create() {
return INSTANCE;
}
}
| 1,121 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/BetterSimpleChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.channel.pool.SimpleChannelPool;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Extension of {@link SimpleChannelPool} to add an asynchronous close method
*/
@SdkInternalApi
public final class BetterSimpleChannelPool extends SimpleChannelPool {
private final CompletableFuture<Boolean> closeFuture;
BetterSimpleChannelPool(Bootstrap bootstrap, ChannelPoolHandler handler) {
super(bootstrap, handler);
closeFuture = new CompletableFuture<>();
}
@Override
public void close() {
super.close();
closeFuture.complete(true);
}
CompletableFuture<Boolean> closeFuture() {
return closeFuture;
}
} | 1,122 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/HealthCheckedChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* An implementation of {@link ChannelPool} that validates the health of its connections.
*
* This wraps another {@code ChannelPool}, and verifies:
* <ol>
* <li>All connections acquired from the underlying channel pool are in the active state.</li>
* <li>All connections released into the underlying pool that are not active, are closed before they are released.</li>
* </ol>
*
* Acquisitions that fail due to an unhealthy underlying channel are retried until a healthy channel can be returned, or the
* {@link NettyConfiguration#connectionAcquireTimeoutMillis()} timeout is reached.
*/
@SdkInternalApi
public class HealthCheckedChannelPool implements SdkChannelPool {
private final EventLoopGroup eventLoopGroup;
private final int acquireTimeoutMillis;
private final SdkChannelPool delegate;
public HealthCheckedChannelPool(EventLoopGroup eventLoopGroup,
NettyConfiguration configuration,
SdkChannelPool delegate) {
this.eventLoopGroup = eventLoopGroup;
this.acquireTimeoutMillis = configuration.connectionAcquireTimeoutMillis();
this.delegate = delegate;
}
@Override
public Future<Channel> acquire() {
return acquire(eventLoopGroup.next().newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> resultFuture) {
// Schedule a task to time out this acquisition, in case we can't acquire a channel fast enough.
ScheduledFuture<?> timeoutFuture =
eventLoopGroup.schedule(() -> timeoutAcquire(resultFuture), acquireTimeoutMillis, TimeUnit.MILLISECONDS);
tryAcquire(resultFuture, timeoutFuture);
return resultFuture;
}
/**
* Time out the provided acquire future, if it hasn't already been completed.
*/
private void timeoutAcquire(Promise<Channel> resultFuture) {
resultFuture.tryFailure(new TimeoutException("Acquire operation took longer than " + acquireTimeoutMillis +
" milliseconds."));
}
/**
* Try to acquire a channel from the underlying pool. This will keep retrying the acquisition until the provided result
* future is completed.
*
* @param resultFuture The future that should be completed with the acquired channel. If this is completed external to this
* function, this function will stop trying to acquire a channel.
* @param timeoutFuture The future for the timeout task. This future will be cancelled when a channel is acquired.
*/
private void tryAcquire(Promise<Channel> resultFuture, ScheduledFuture<?> timeoutFuture) {
// Something else completed the future (probably a timeout). Stop trying to get a channel.
if (resultFuture.isDone()) {
return;
}
Promise<Channel> delegateFuture = eventLoopGroup.next().newPromise();
delegate.acquire(delegateFuture);
delegateFuture.addListener(f -> ensureAcquiredChannelIsHealthy(delegateFuture, resultFuture, timeoutFuture));
}
/**
* Validate that the channel returned by the underlying channel pool is healthy. If so, complete the result future with the
* channel returned by the underlying pool. If not, close the channel and try to get a different one.
*
* @param delegateFuture A completed promise as a result of invoking delegate.acquire().
* @param resultFuture The future that should be completed with the healthy, acquired channel.
* @param timeoutFuture The future for the timeout task. This future will be cancelled when a channel is acquired.
*/
private void ensureAcquiredChannelIsHealthy(Promise<Channel> delegateFuture,
Promise<Channel> resultFuture,
ScheduledFuture<?> timeoutFuture) {
// If our delegate failed to connect, forward down the failure. Don't try again.
if (!delegateFuture.isSuccess()) {
timeoutFuture.cancel(false);
resultFuture.tryFailure(delegateFuture.cause());
return;
}
// If our delegate gave us an unhealthy connection, close it and try to get a new one.
Channel channel = delegateFuture.getNow();
if (!isHealthy(channel)) {
channel.close();
delegate.release(channel);
tryAcquire(resultFuture, timeoutFuture);
return;
}
// Cancel the timeout (best effort), and return back the healthy channel.
timeoutFuture.cancel(false);
if (!resultFuture.trySuccess(channel)) {
// If we couldn't give the channel to the result future (because it failed for some other reason),
// just return it to the pool.
release(channel);
}
}
@Override
public Future<Void> release(Channel channel) {
closeIfUnhealthy(channel);
return delegate.release(channel);
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
closeIfUnhealthy(channel);
return delegate.release(channel, promise);
}
@Override
public void close() {
delegate.close();
}
/**
* Close the provided channel, if it's considered unhealthy.
*/
private void closeIfUnhealthy(Channel channel) {
if (!isHealthy(channel)) {
channel.close();
}
}
/**
* Determine whether the provided channel is 'healthy' enough to use.
*/
private boolean isHealthy(Channel channel) {
// There might be cases where the channel is not reusable but still active at the moment
// See https://github.com/aws/aws-sdk-java-v2/issues/1380
if (channel.attr(KEEP_ALIVE).get() != null && !channel.attr(KEEP_ALIVE).get()) {
return false;
}
return channel.isActive();
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
return delegate.collectChannelPoolMetrics(metrics);
}
}
| 1,123 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.pool.ChannelPool;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* A {@link ChannelPool} implementation that allows a caller to asynchronously retrieve channel-pool related metrics via
* {@link #collectChannelPoolMetrics(MetricCollector)}.
*/
@SdkInternalApi
public interface SdkChannelPool extends ChannelPool {
/**
* Collect channel pool metrics into the provided {@link MetricCollector} collection, completing the returned future when
* all metric publishing is complete.
*
* @param metrics The collection to which all metrics should be added.
* @return A future that is completed when all metric publishing is complete.
*/
CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics);
}
| 1,124 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/DelegatingEventLoopGroup.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.ScheduledFuture;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* {@link EventLoopGroup} that just delegates to another {@link EventLoopGroup}. Useful for extending or building decorators.
*/
@SdkInternalApi
public abstract class DelegatingEventLoopGroup implements EventLoopGroup {
private final EventLoopGroup delegate;
protected DelegatingEventLoopGroup(EventLoopGroup delegate) {
this.delegate = delegate;
}
/**
* @return The {@link EventLoopGroup} being delegated to.
*/
public EventLoopGroup getDelegate() {
return delegate;
}
@Override
public boolean isShuttingDown() {
return delegate.isShuttingDown();
}
@Override
public Future<?> shutdownGracefully() {
return shutdownGracefully(EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS, EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
return delegate.shutdownGracefully(quietPeriod, timeout, unit);
}
@Override
public Future<?> terminationFuture() {
return delegate.terminationFuture();
}
@Override
public void shutdown() {
delegate.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate.awaitTermination(timeout, unit);
}
@Override
public EventLoop next() {
return delegate.next();
}
@Override
public Iterator<EventExecutor> iterator() {
return delegate.iterator();
}
@Override
public Future<?> submit(Runnable task) {
return delegate.submit(task);
}
@Override
public <T> List<java.util.concurrent.Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws
InterruptedException {
return delegate.invokeAll(tasks);
}
@Override
public <T> List<java.util.concurrent.Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout,
TimeUnit unit) throws InterruptedException {
return delegate.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return delegate.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException,
TimeoutException {
return delegate.invokeAny(tasks, timeout, unit);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return delegate.submit(task, result);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return delegate.submit(task);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return delegate.schedule(command, delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return delegate.schedule(callable, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override
public ChannelFuture register(Channel channel) {
return delegate.register(channel);
}
@Override
public ChannelFuture register(ChannelPromise promise) {
return delegate.register(promise);
}
@Override
public ChannelFuture register(Channel channel, ChannelPromise promise) {
return delegate.register(channel, promise);
}
@Override
public void execute(Runnable command) {
delegate.execute(command);
}
}
| 1,125 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SslContextProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManagerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SystemPropertyTlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class SslContextProvider {
private static final NettyClientLogger log = NettyClientLogger.getLogger(SslContextProvider.class);
private final Protocol protocol;
private final SslProvider sslProvider;
private final TrustManagerFactory trustManagerFactory;
private final KeyManagerFactory keyManagerFactory;
public SslContextProvider(NettyConfiguration configuration, Protocol protocol, SslProvider sslProvider) {
this.protocol = protocol;
this.sslProvider = sslProvider;
this.trustManagerFactory = getTrustManager(configuration);
this.keyManagerFactory = getKeyManager(configuration);
}
public SslContext sslContext() {
try {
return SslContextBuilder.forClient()
.sslProvider(sslProvider)
.ciphers(getCiphers(), SupportedCipherSuiteFilter.INSTANCE)
.trustManager(trustManagerFactory)
.keyManager(keyManagerFactory)
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
}
/**
* HTTP/2: per Rfc7540, there is a blocked list of cipher suites for HTTP/2, so setting
* the recommended cipher suites directly here
*
* HTTP/1.1: return null so that the default ciphers suites will be used
* https://github.com/netty/netty/blob/0dc246eb129796313b58c1dbdd674aa289f72cad/handler/src/main/java/io/netty/handler/ssl
* /SslUtils.java
*/
private List<String> getCiphers() {
return protocol == Protocol.HTTP2 ? Http2SecurityUtil.CIPHERS : null;
}
private TrustManagerFactory getTrustManager(NettyConfiguration configuration) {
TlsTrustManagersProvider tlsTrustManagersProvider = configuration.tlsTrustManagersProvider();
Validate.isTrue(tlsTrustManagersProvider == null || !configuration.trustAllCertificates(),
"A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");
if (tlsTrustManagersProvider != null) {
return StaticTrustManagerFactory.create(tlsTrustManagersProvider.trustManagers());
}
if (configuration.trustAllCertificates()) {
log.warn(null, () -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
+ "used for testing.");
return InsecureTrustManagerFactory.INSTANCE;
}
// return null so that the system default trust manager will be used
return null;
}
private KeyManagerFactory getKeyManager(NettyConfiguration configuration) {
if (configuration.tlsKeyManagersProvider() != null) {
KeyManager[] keyManagers = configuration.tlsKeyManagersProvider().keyManagers();
if (keyManagers != null) {
return StaticKeyManagerFactory.create(keyManagers);
}
}
KeyManager[] systemPropertyKeyManagers = SystemPropertyTlsKeyManagersProvider.create().keyManagers();
return systemPropertyKeyManagers == null ? null : StaticKeyManagerFactory.create(systemPropertyKeyManagers);
}
}
| 1,126 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelledException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
final class FutureCancelledException extends RuntimeException {
private final long executionId;
FutureCancelledException(long executionId, Throwable cause) {
super(cause);
this.executionId = executionId;
}
long getExecutionId() {
return executionId;
}
}
| 1,127 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/InUseTrackingChannelPoolListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE;
import io.netty.channel.Channel;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.ListenerInvokingChannelPool.ChannelPoolListener;
import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils;
/**
* Marks {@link Channel}s as in-use when they are leased from the pool. An in-use channel is not eligible to be closed by {@link
* IdleConnectionReaperHandler} or {@link OldConnectionReaperHandler}.
*/
@SdkInternalApi
public final class InUseTrackingChannelPoolListener implements ChannelPoolListener {
private static final InUseTrackingChannelPoolListener INSTANCE = new InUseTrackingChannelPoolListener();
private InUseTrackingChannelPoolListener() {
}
public static InUseTrackingChannelPoolListener create() {
return INSTANCE;
}
@Override
public void channelAcquired(Channel channel) {
channel.attr(IN_USE).set(true);
ChannelUtils.getAttribute(channel, CHANNEL_DIAGNOSTICS).ifPresent(ChannelDiagnostics::stopIdleTimer);
}
@Override
public void channelReleased(Channel channel) {
channel.attr(IN_USE).set(false);
ChannelUtils.getAttribute(channel, CHANNEL_DIAGNOSTICS).ifPresent(ChannelDiagnostics::startIdleTimer);
}
}
| 1,128 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/HandlerRemovingChannelPoolListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.removeIfExists;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.ListenerInvokingChannelPool.ChannelPoolListener;
import software.amazon.awssdk.http.nio.netty.internal.http2.FlushOnReadHandler;
import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler;
/**
* Removes any per-request {@link ChannelHandler} from the pipeline when releasing it to the pool.
*/
@SdkInternalApi
public final class HandlerRemovingChannelPoolListener implements ChannelPoolListener {
private static final HandlerRemovingChannelPoolListener INSTANCE = new HandlerRemovingChannelPoolListener();
private HandlerRemovingChannelPoolListener() {
}
public static HandlerRemovingChannelPoolListener create() {
return INSTANCE;
}
@Override
public void channelReleased(Channel channel) {
// Only remove per request handler if the channel is registered
// or open since DefaultChannelPipeline would remove handlers if
// channel is closed and unregistered
if (channel.isOpen() || channel.isRegistered()) {
removeIfExists(channel.pipeline(),
HttpStreamsClientHandler.class,
FlushOnReadHandler.class,
ResponseHandler.class,
ReadTimeoutHandler.class,
WriteTimeoutHandler.class);
}
}
}
| 1,129 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/UnusedChannelExceptionHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.getAttribute;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.TimeoutException;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* A handler for exceptions occurring on channels not current in use (according to {@link ChannelAttributeKey#IN_USE}). This
* does nothing if the channel is currently in use. If it's not currently in use, it will close the channel and log an
* appropriate notification.
*
* This prevents spamming customer logs when errors (eg. connection resets) occur on an unused channel.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class UnusedChannelExceptionHandler extends ChannelInboundHandlerAdapter {
public static final UnusedChannelExceptionHandler INSTANCE = new UnusedChannelExceptionHandler();
private static final NettyClientLogger log = NettyClientLogger.getLogger(UnusedChannelExceptionHandler.class);
private UnusedChannelExceptionHandler() {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
boolean channelInUse = getAttribute(ctx.channel(), ChannelAttributeKey.IN_USE).orElse(false);
if (channelInUse) {
ctx.fireExceptionCaught(cause);
} else {
ctx.close();
Optional<CompletableFuture<Void>> executeFuture = getAttribute(ctx.channel(), ChannelAttributeKey.EXECUTE_FUTURE_KEY);
if (executeFuture.isPresent() && !executeFuture.get().isDone()) {
log.error(ctx.channel(), () -> "An exception occurred on an channel (" + ctx.channel().id() + ") that was not "
+ "in use, but was associated with a future that wasn't completed. This "
+ "indicates a bug in the Java SDK, where a future was not completed while the "
+ "channel was in use. The channel has been closed, and the future will be "
+ "completed to prevent any ongoing issues.", cause);
executeFuture.get().completeExceptionally(cause);
} else if (isNettyIoException(cause) || hasNettyIoExceptionCause(cause)) {
log.debug(ctx.channel(),
() -> "An I/O exception (" + cause.getMessage() + ") occurred on a channel (" + ctx.channel().id() +
") that was not in use. The channel has been closed. This is usually normal.");
} else {
log.warn(ctx.channel(), () -> "A non-I/O exception occurred on a channel (" + ctx.channel().id() + ") that was "
+ "not in use. The channel has been closed to prevent any ongoing issues.", cause);
}
}
}
public static UnusedChannelExceptionHandler getInstance() {
return INSTANCE;
}
private boolean isNettyIoException(Throwable cause) {
return cause instanceof IOException || cause instanceof TimeoutException;
}
private boolean hasNettyIoExceptionCause(Throwable cause) {
return cause.getCause() != null && isNettyIoException(cause.getCause());
}
}
| 1,130 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTE_FUTURE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_COMPLETE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_CONTENT_LENGTH;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_DATA_READ;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_STATUS_CODE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.STREAMING_COMPLETE_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ExceptionHandlingUtils.tryCatch;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ExceptionHandlingUtils.tryCatchFinally;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.util.ReferenceCountUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkCancellationException;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2ResetSendingSubscription;
import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler;
import software.amazon.awssdk.http.nio.netty.internal.nrs.StreamedHttpResponse;
import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.utils.FunctionalUtils.UnsafeRunnable;
import software.amazon.awssdk.utils.async.DelegatingSubscription;
@Sharable
@SdkInternalApi
public class ResponseHandler extends SimpleChannelInboundHandler<HttpObject> {
private static final NettyClientLogger log = NettyClientLogger.getLogger(ResponseHandler.class);
private static final ResponseHandler INSTANCE = new ResponseHandler();
private ResponseHandler() {
}
@Override
protected void channelRead0(ChannelHandlerContext channelContext, HttpObject msg) throws Exception {
RequestContext requestContext = channelContext.channel().attr(REQUEST_CONTEXT_KEY).get();
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
SdkHttpResponse sdkResponse = SdkHttpFullResponse.builder()
.headers(fromNettyHeaders(response.headers()))
.statusCode(response.status().code())
.statusText(response.status().reasonPhrase())
.build();
channelContext.channel().attr(RESPONSE_STATUS_CODE).set(response.status().code());
channelContext.channel().attr(RESPONSE_CONTENT_LENGTH).set(responseContentLength(response));
channelContext.channel().attr(KEEP_ALIVE).set(shouldKeepAlive(response));
ChannelUtils.getAttribute(channelContext.channel(), CHANNEL_DIAGNOSTICS)
.ifPresent(ChannelDiagnostics::incrementResponseCount);
requestContext.handler().onHeaders(sdkResponse);
}
CompletableFuture<Void> ef = executeFuture(channelContext);
if (msg instanceof StreamedHttpResponse) {
requestContext.handler().onStream(
new DataCountingPublisher(channelContext,
new PublisherAdapter((StreamedHttpResponse) msg, channelContext,
requestContext, ef)));
} else if (msg instanceof FullHttpResponse) {
ByteBuf fullContent = null;
try {
// Be prepared to take care of (ignore) a trailing LastHttpResponse
// from the HttpClientCodec if there is one.
channelContext.pipeline().replace(HttpStreamsClientHandler.class,
channelContext.name() + "-LastHttpContentSwallower",
LastHttpContentSwallower.getInstance());
fullContent = ((FullHttpResponse) msg).content();
ByteBuffer bb = copyToByteBuffer(fullContent);
requestContext.handler().onStream(new DataCountingPublisher(channelContext,
new FullResponseContentPublisher(channelContext,
bb, ef)));
try {
validateResponseContentLength(channelContext);
finalizeResponse(requestContext, channelContext);
} catch (IOException e) {
exceptionCaught(channelContext, e);
}
} finally {
Optional.ofNullable(fullContent).ifPresent(ByteBuf::release);
}
}
}
private Long responseContentLength(HttpResponse response) {
String length = response.headers().get(HttpHeaderNames.CONTENT_LENGTH);
if (length == null) {
return null;
}
return Long.parseLong(length);
}
private static void validateResponseContentLength(ChannelHandlerContext ctx) throws IOException {
if (!shouldValidateResponseContentLength(ctx)) {
return;
}
Long contentLengthHeader = ctx.channel().attr(RESPONSE_CONTENT_LENGTH).get();
Long actualContentLength = ctx.channel().attr(RESPONSE_DATA_READ).get();
if (contentLengthHeader == null) {
return;
}
if (actualContentLength == null) {
actualContentLength = 0L;
}
if (actualContentLength.equals(contentLengthHeader)) {
return;
}
throw new IOException("Response had content-length of " + contentLengthHeader + " bytes, but only received "
+ actualContentLength + " bytes before the connection was closed.");
}
private static boolean shouldValidateResponseContentLength(ChannelHandlerContext ctx) {
RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get();
// HEAD requests may return Content-Length without a payload
if (requestContext.executeRequest().request().method() == SdkHttpMethod.HEAD) {
return false;
}
// 304 responses may contain Content-Length without a payload
Integer responseStatusCode = ctx.channel().attr(RESPONSE_STATUS_CODE).get();
if (responseStatusCode != null && responseStatusCode == HttpResponseStatus.NOT_MODIFIED.code()) {
return false;
}
return true;
}
/**
* Finalize the response by completing the execute future and release the channel pool being used.
*
* @param requestContext the request context
* @param channelContext the channel context
*/
private static void finalizeResponse(RequestContext requestContext, ChannelHandlerContext channelContext) {
channelContext.channel().attr(RESPONSE_COMPLETE_KEY).set(true);
executeFuture(channelContext).complete(null);
if (!channelContext.channel().attr(KEEP_ALIVE).get()) {
closeAndRelease(channelContext);
} else {
requestContext.channelPool().release(channelContext.channel());
}
}
private boolean shouldKeepAlive(HttpResponse response) {
if (HttpStatusFamily.of(response.status().code()) == HttpStatusFamily.SERVER_ERROR) {
return false;
}
return HttpUtil.isKeepAlive(response);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get();
log.debug(ctx.channel(), () -> "Exception processing request: " + requestContext.executeRequest().request(), cause);
Throwable throwable = NettyUtils.decorateException(ctx.channel(), cause);
executeFuture(ctx).completeExceptionally(throwable);
runAndLogError(ctx.channel(), () -> "Fail to execute SdkAsyncHttpResponseHandler#onError",
() -> requestContext.handler().onError(throwable));
runAndLogError(ctx.channel(), () -> "Could not release channel back to the pool", () -> closeAndRelease(ctx));
}
@Override
public void channelInactive(ChannelHandlerContext handlerCtx) {
notifyIfResponseNotCompleted(handlerCtx);
}
public static ResponseHandler getInstance() {
return INSTANCE;
}
/**
* Close the channel and release it back into the pool.
*
* @param ctx Context for channel
*/
private static void closeAndRelease(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
channel.attr(KEEP_ALIVE).set(false);
RequestContext requestContext = channel.attr(REQUEST_CONTEXT_KEY).get();
ctx.close();
requestContext.channelPool().release(channel);
}
/**
* Runs a given {@link UnsafeRunnable} and logs an error without throwing.
*
* @param errorMsg Message to log with exception thrown.
* @param runnable Action to perform.
*/
private static void runAndLogError(Channel ch, Supplier<String> errorMsg, UnsafeRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
log.error(ch, errorMsg, e);
}
}
private static Map<String, List<String>> fromNettyHeaders(HttpHeaders headers) {
return headers.entries().stream()
.collect(groupingBy(Map.Entry::getKey,
mapping(Map.Entry::getValue, Collectors.toList())));
}
private static ByteBuffer copyToByteBuffer(ByteBuf byteBuf) {
ByteBuffer bb = ByteBuffer.allocate(byteBuf.readableBytes());
byteBuf.getBytes(byteBuf.readerIndex(), bb);
bb.flip();
return bb;
}
private static CompletableFuture<Void> executeFuture(ChannelHandlerContext ctx) {
return ctx.channel().attr(EXECUTE_FUTURE_KEY).get();
}
static class PublisherAdapter implements Publisher<ByteBuffer> {
private final StreamedHttpResponse response;
private final ChannelHandlerContext channelContext;
private final RequestContext requestContext;
private final CompletableFuture<Void> executeFuture;
private final AtomicBoolean isDone = new AtomicBoolean(false);
PublisherAdapter(StreamedHttpResponse response, ChannelHandlerContext channelContext,
RequestContext requestContext, CompletableFuture<Void> executeFuture) {
this.response = response;
this.channelContext = channelContext;
this.requestContext = requestContext;
this.executeFuture = executeFuture;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
response.subscribe(new Subscriber<HttpContent>() {
@Override
public void onSubscribe(Subscription subscription) {
subscriber.onSubscribe(new OnCancelSubscription(resolveSubscription(subscription),
this::onCancel));
}
private Subscription resolveSubscription(Subscription subscription) {
// For HTTP2 we send a RST_STREAM frame on cancel to stop the service from sending more data
if (ChannelAttributeKey.getProtocolNow(channelContext.channel()) == Protocol.HTTP2) {
return new Http2ResetSendingSubscription(channelContext, subscription);
} else {
return subscription;
}
}
private void onCancel() {
if (!isDone.compareAndSet(false, true)) {
return;
}
try {
SdkCancellationException e = new SdkCancellationException(
"Subscriber cancelled before all events were published");
log.warn(channelContext.channel(), () -> "Subscriber cancelled before all events were published");
executeFuture.completeExceptionally(e);
} finally {
runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool",
() -> closeAndRelease(channelContext));
}
}
@Override
public void onNext(HttpContent httpContent) {
// isDone may be true if the subscriber cancelled
if (isDone.get()) {
ReferenceCountUtil.release(httpContent);
return;
}
// Needed to prevent use-after-free bug if the subscriber's onNext is asynchronous
ByteBuffer byteBuffer =
tryCatchFinally(() -> copyToByteBuffer(httpContent.content()),
this::onError,
httpContent::release);
//As per reactive-streams rule 2.13, we should not call subscriber#onError when
//exception is thrown from subscriber#onNext
if (byteBuffer != null) {
tryCatch(() -> subscriber.onNext(byteBuffer),
this::notifyError);
}
}
@Override
public void onError(Throwable t) {
if (!isDone.compareAndSet(false, true)) {
return;
}
try {
runAndLogError(channelContext.channel(),
() -> String.format("Subscriber %s threw an exception in onError.", subscriber),
() -> subscriber.onError(t));
notifyError(t);
} finally {
runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool",
() -> closeAndRelease(channelContext));
}
}
@Override
public void onComplete() {
// For HTTP/2 it's possible to get an onComplete after we cancel due to the channel becoming
// inactive. We guard against that here and just ignore the signal (see HandlerPublisher)
if (!isDone.compareAndSet(false, true)) {
return;
}
try {
validateResponseContentLength(channelContext);
try {
runAndLogError(channelContext.channel(),
() -> String.format("Subscriber %s threw an exception in onComplete.", subscriber),
subscriber::onComplete);
} finally {
finalizeResponse(requestContext, channelContext);
}
} catch (IOException e) {
notifyError(e);
runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool",
() -> closeAndRelease(channelContext));
}
}
private void notifyError(Throwable throwable) {
SdkAsyncHttpResponseHandler handler = requestContext.handler();
runAndLogError(channelContext.channel(),
() -> String.format("SdkAsyncHttpResponseHandler %s threw an exception in onError.", handler),
() -> handler.onError(throwable));
executeFuture.completeExceptionally(throwable);
}
});
}
}
/**
* Decorator around a {@link Subscription} to notify if a cancellation occurs.
*/
private static class OnCancelSubscription extends DelegatingSubscription {
private final Runnable onCancel;
private OnCancelSubscription(Subscription subscription, Runnable onCancel) {
super(subscription);
this.onCancel = onCancel;
}
@Override
public void cancel() {
onCancel.run();
super.cancel();
}
}
static class FullResponseContentPublisher implements Publisher<ByteBuffer> {
private final ChannelHandlerContext channelContext;
private final ByteBuffer fullContent;
private final CompletableFuture<Void> executeFuture;
private boolean running = true;
private Subscriber<? super ByteBuffer> subscriber;
FullResponseContentPublisher(ChannelHandlerContext channelContext, ByteBuffer fullContent,
CompletableFuture<Void> executeFuture) {
this.channelContext = channelContext;
this.fullContent = fullContent;
this.executeFuture = executeFuture;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
if (this.subscriber != null) {
subscriber.onComplete();
return;
}
this.subscriber = subscriber;
channelContext.channel().attr(ChannelAttributeKey.SUBSCRIBER_KEY)
.set(subscriber);
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
if (running) {
running = false;
if (l <= 0) {
subscriber.onError(new IllegalArgumentException("Demand must be positive!"));
} else {
if (fullContent.hasRemaining()) {
subscriber.onNext(fullContent);
}
subscriber.onComplete();
executeFuture.complete(null);
}
}
}
@Override
public void cancel() {
running = false;
}
});
}
}
private void notifyIfResponseNotCompleted(ChannelHandlerContext handlerCtx) {
RequestContext requestCtx = handlerCtx.channel().attr(REQUEST_CONTEXT_KEY).get();
Boolean responseCompleted = handlerCtx.channel().attr(RESPONSE_COMPLETE_KEY).get();
Boolean isStreamingComplete = handlerCtx.channel().attr(STREAMING_COMPLETE_KEY).get();
handlerCtx.channel().attr(KEEP_ALIVE).set(false);
if (!Boolean.TRUE.equals(responseCompleted) && !Boolean.TRUE.equals(isStreamingComplete)) {
IOException err = new IOException(NettyUtils.closedChannelMessage(handlerCtx.channel()));
runAndLogError(handlerCtx.channel(), () -> "Fail to execute SdkAsyncHttpResponseHandler#onError",
() -> requestCtx.handler().onError(err));
executeFuture(handlerCtx).completeExceptionally(err);
runAndLogError(handlerCtx.channel(), () -> "Could not release channel", () -> closeAndRelease(handlerCtx));
}
}
private static final class DataCountingPublisher implements Publisher<ByteBuffer> {
private final ChannelHandlerContext ctx;
private final Publisher<ByteBuffer> delegate;
private DataCountingPublisher(ChannelHandlerContext ctx, Publisher<ByteBuffer> delegate) {
this.ctx = ctx;
this.delegate = delegate;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
delegate.subscribe(new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription subscription) {
subscriber.onSubscribe(subscription);
}
@Override
public void onNext(ByteBuffer byteBuffer) {
Long responseDataSoFar = ctx.channel().attr(RESPONSE_DATA_READ).get();
if (responseDataSoFar == null) {
responseDataSoFar = 0L;
}
ctx.channel().attr(RESPONSE_DATA_READ).set(responseDataSoFar + byteBuffer.remaining());
subscriber.onNext(byteBuffer);
}
@Override
public void onError(Throwable throwable) {
subscriber.onError(throwable);
}
@Override
public void onComplete() {
subscriber.onComplete();
}
});
}
}
} | 1,131 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelPoolMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.pool.ChannelPoolMap;
import java.io.Closeable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Replacement for {@link io.netty.channel.pool.AbstractChannelPoolMap}. This implementation guarantees
* only one instance of a {@link ChannelPool} is created for each key.
*/
// TODO do we need to use this for H2?
@SdkInternalApi
public abstract class SdkChannelPoolMap<K, P extends ChannelPool>
implements ChannelPoolMap<K, P>, Iterable<Map.Entry<K, P>>, Closeable {
private final ConcurrentMap<K, P> map = new ConcurrentHashMap<>();
@Override
public final P get(K key) {
return map.computeIfAbsent(key, this::newPool);
}
/**
* Remove the {@link ChannelPool} from this {@link io.netty.channel.pool.AbstractChannelPoolMap}. Returns {@code true} if
* removed, {@code false} otherwise.
*
* Please note that {@code null} keys are not allowed.
*/
public final boolean remove(K key) {
P pool = map.remove(paramNotNull(key, "key"));
if (pool != null) {
pool.close();
return true;
}
return false;
}
@Override
public final Iterator<Map.Entry<K, P>> iterator() {
return new ReadOnlyIterator<>(map.entrySet().iterator());
}
/**
* Returns the number of {@link ChannelPool}s currently in this {@link io.netty.channel.pool.AbstractChannelPoolMap}.
*/
public final int size() {
return map.size();
}
/**
* Returns {@code true} if the {@link io.netty.channel.pool.AbstractChannelPoolMap} is empty, otherwise {@code false}.
*/
public final boolean isEmpty() {
return map.isEmpty();
}
@Override
public final boolean contains(K key) {
return map.containsKey(paramNotNull(key, "key"));
}
/**
* Called once a new {@link ChannelPool} needs to be created as non exists yet for the {@code key}.
*/
protected abstract P newPool(K key);
@Override
public void close() {
map.keySet().forEach(this::remove);
}
public final Map<K, P> pools() {
return Collections.unmodifiableMap(new HashMap<>(map));
}
/**
* {@link Iterator} that prevents removal.
*
* @param <T> Type of object being iterated.
*/
private final class ReadOnlyIterator<T> implements Iterator<T> {
private final Iterator<? extends T> iterator;
private ReadOnlyIterator(Iterator<? extends T> iterator) {
this.iterator = paramNotNull(iterator, "iterator");
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public T next() {
return this.iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Read-only iterator doesn't support removal.");
}
}
}
| 1,132 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTION_ID_KEY;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Closes the channel if the execution future has been cancelled.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class FutureCancelHandler extends ChannelInboundHandlerAdapter {
private static final NettyClientLogger LOG = NettyClientLogger.getLogger(FutureCancelHandler.class);
private static final FutureCancelHandler INSTANCE = new FutureCancelHandler();
private FutureCancelHandler() {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
if (!(e instanceof FutureCancelledException)) {
ctx.fireExceptionCaught(e);
return;
}
FutureCancelledException cancelledException = (FutureCancelledException) e;
Long channelExecutionId = executionId(ctx);
if (channelExecutionId == null) {
RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get();
LOG.warn(ctx.channel(), () -> String.format("Received a cancellation exception on a channel that doesn't have an "
+ "execution Id attached. Exception's execution ID is %d. "
+ "Exception is being ignored. Closing the channel",
executionId(ctx)));
ctx.close();
requestContext.channelPool().release(ctx.channel());
} else if (currentRequestCancelled(channelExecutionId, cancelledException)) {
RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get();
requestContext.handler().onError(e);
ctx.fireExceptionCaught(new IOException("Request cancelled"));
ctx.close();
requestContext.channelPool().release(ctx.channel());
} else {
LOG.debug(ctx.channel(), () -> String.format("Received a cancellation exception but it did not match the current "
+ "execution ID. Exception's execution ID is %d, but the current ID on "
+ "the channel is %d. Exception is being ignored.",
cancelledException.getExecutionId(),
executionId(ctx)));
}
}
public static FutureCancelHandler getInstance() {
return INSTANCE;
}
private static boolean currentRequestCancelled(long executionId, FutureCancelledException e) {
return e.getExecutionId() == executionId;
}
private static Long executionId(ChannelHandlerContext ctx) {
Attribute<Long> attr = ctx.channel().attr(EXECUTION_ID_KEY);
if (attr == null) {
return null;
}
return attr.get();
}
}
| 1,133 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ProxyTunnelInitHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.net.URI;
import java.util.Base64;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.utils.StringUtils;
/**
* Handler that initializes the HTTP tunnel.
*/
@SdkInternalApi
public final class ProxyTunnelInitHandler extends ChannelDuplexHandler {
public static final NettyClientLogger log = NettyClientLogger.getLogger(ProxyTunnelInitHandler.class);
private final ChannelPool sourcePool;
private final String username;
private final String password;
private final URI remoteHost;
private final Promise<Channel> initPromise;
private final Supplier<HttpClientCodec> httpCodecSupplier;
public ProxyTunnelInitHandler(ChannelPool sourcePool, String proxyUsername, String proxyPassword, URI remoteHost,
Promise<Channel> initPromise) {
this(sourcePool, proxyUsername, proxyPassword, remoteHost, initPromise, HttpClientCodec::new);
}
public ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise) {
this(sourcePool, null, null, remoteHost, initPromise, HttpClientCodec::new);
}
@SdkTestInternalApi
public ProxyTunnelInitHandler(ChannelPool sourcePool, String prosyUsername, String proxyPassword,
URI remoteHost, Promise<Channel> initPromise, Supplier<HttpClientCodec> httpCodecSupplier) {
this.sourcePool = sourcePool;
this.remoteHost = remoteHost;
this.initPromise = initPromise;
this.username = prosyUsername;
this.password = proxyPassword;
this.httpCodecSupplier = httpCodecSupplier;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ChannelPipeline pipeline = ctx.pipeline();
pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get());
HttpRequest connectRequest = connectRequest();
ctx.channel().writeAndFlush(connectRequest).addListener(f -> {
if (!f.isSuccess()) {
handleConnectRequestFailure(ctx, f.cause());
}
});
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
if (ctx.pipeline().get(HttpClientCodec.class) != null) {
ctx.pipeline().remove(HttpClientCodec.class);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
if (response.status().code() == 200) {
ctx.pipeline().remove(this);
// Note: we leave the SslHandler here (if we added it)
initPromise.setSuccess(ctx.channel());
return;
}
}
// Fail if we received any other type of message or we didn't get a 200 from the proxy
ctx.pipeline().remove(this);
ctx.close();
sourcePool.release(ctx.channel());
initPromise.setFailure(new IOException("Could not connect to proxy"));
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
if (!initPromise.isDone()) {
handleConnectRequestFailure(ctx, null);
} else {
log.debug(ctx.channel(), () -> "The proxy channel (" + ctx.channel().id() + ") is inactive");
closeAndRelease(ctx);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (!initPromise.isDone()) {
handleConnectRequestFailure(ctx, cause);
} else {
log.debug(ctx.channel(), () -> "An exception occurred on the proxy tunnel channel (" + ctx.channel().id() + "). " +
"The channel has been closed to prevent any ongoing issues.", cause);
closeAndRelease(ctx);
}
}
private void handleConnectRequestFailure(ChannelHandlerContext ctx, Throwable cause) {
closeAndRelease(ctx);
String errorMsg = "Unable to send CONNECT request to proxy";
IOException ioException = cause == null ? new IOException(errorMsg) :
new IOException(errorMsg, cause);
initPromise.setFailure(ioException);
}
private void closeAndRelease(ChannelHandlerContext ctx) {
ctx.close();
sourcePool.release(ctx.channel());
}
private HttpRequest connectRequest() {
String uri = getUri();
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri,
Unpooled.EMPTY_BUFFER, false);
request.headers().add(HttpHeaderNames.HOST, uri);
if (!StringUtils.isEmpty(this.username) && !StringUtils.isEmpty(this.password)) {
String authToken = String.format("%s:%s", this.username, this.password);
String authB64 = Base64.getEncoder().encodeToString(authToken.getBytes(CharsetUtil.UTF_8));
request.headers().add(HttpHeaderNames.PROXY_AUTHORIZATION, String.format("Basic %s", authB64));
}
return request;
}
private String getUri() {
return remoteHost.getHost() + ":" + remoteHost.getPort();
}
}
| 1,134 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/RequestContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.EventLoopGroup;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
@SdkInternalApi
public final class RequestContext {
private final SdkChannelPool channelPool;
private final EventLoopGroup eventLoopGroup;
private final AsyncExecuteRequest executeRequest;
private final NettyConfiguration configuration;
private final MetricCollector metricCollector;
public RequestContext(SdkChannelPool channelPool,
EventLoopGroup eventLoopGroup,
AsyncExecuteRequest executeRequest,
NettyConfiguration configuration) {
this.channelPool = channelPool;
this.eventLoopGroup = eventLoopGroup;
this.executeRequest = executeRequest;
this.configuration = configuration;
this.metricCollector = executeRequest.metricCollector().orElseGet(NoOpMetricCollector::create);
}
public SdkChannelPool channelPool() {
return channelPool;
}
public EventLoopGroup eventLoopGroup() {
return eventLoopGroup;
}
public AsyncExecuteRequest executeRequest() {
return executeRequest;
}
/**
* Convenience method to retrieve the {@link SdkAsyncHttpResponseHandler} contained in the {@link AsyncExecuteRequest}
* returned by {@link #executeRequest}.
*
* @return The response handler for this request.
*/
public SdkAsyncHttpResponseHandler handler() {
return executeRequest().responseHandler();
}
public NettyConfiguration configuration() {
return configuration;
}
public MetricCollector metricCollector() {
return metricCollector;
}
}
| 1,135 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/LastHttpContentSwallower.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.LastHttpContent;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Simple handler that swallows the next read object if it is an instance of
* {@code LastHttpContent}, then removes itself from the pipeline.
* <p>
* This handler is sharable.
*/
@SdkInternalApi
@ChannelHandler.Sharable
final class LastHttpContentSwallower extends SimpleChannelInboundHandler<HttpObject> {
private static final LastHttpContentSwallower INSTANCE = new LastHttpContentSwallower();
private LastHttpContentSwallower() {
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject obj) {
if (obj instanceof LastHttpContent) {
// Queue another read to make up for the one we just ignored
ctx.read();
} else {
ctx.fireChannelRead(obj);
}
// Remove self from pipeline since we only care about potentially
// ignoring the very first message
ctx.pipeline().remove(this);
}
public static LastHttpContentSwallower getInstance() {
return INSTANCE;
}
}
| 1,136 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SharedSdkEventLoopGroup.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.SUCCEEDED_FUTURE;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
/**
* Provides access and manages a shared {@link SdkEventLoopGroup}. Uses reference counting to keep track of how many HTTP
* clients are using the shared event loop group and will automatically close it when that count reaches zero. Event loop
* group is lazily initialized for the first time and and subsequent requests after the count reaches zero.
*/
@SdkInternalApi
public final class SharedSdkEventLoopGroup {
/**
* Lazily initialized shared default event loop group.
*/
private static SdkEventLoopGroup sharedSdkEventLoopGroup;
/**
* Reference count of clients using the shared event loop group.
*/
private static int referenceCount = 0;
private SharedSdkEventLoopGroup() {
}
/**
* @return The default {@link SdkEventLoopGroup} that will be shared across all service clients.
* This is used when the customer does not specify a custom {@link SdkEventLoopGroup} or {@link SdkEventLoopGroup.Builder}.
* Each SdkEventLoopGroup returned is wrapped with a new {@link ReferenceCountingEventLoopGroup}.
*/
@SdkInternalApi
public static synchronized SdkEventLoopGroup get() {
if (sharedSdkEventLoopGroup == null) {
sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build();
}
referenceCount++;
return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()),
sharedSdkEventLoopGroup.channelFactory());
}
/**
* Decrement the reference count and close if necessary.
*
* @param quietPeriod the quite period to use
* @param timeout the timeout to use
* @param unit the time unit
*
* @return the close future. If the shared event loop group is still being used, return a completed close future,
* otherwise return the future from {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit)};
*/
private static synchronized Future<?> decrementReference(long quietPeriod, long timeout, TimeUnit unit) {
referenceCount--;
if (referenceCount == 0) {
Future<?> shutdownGracefully =
sharedSdkEventLoopGroup.eventLoopGroup().shutdownGracefully(quietPeriod, timeout, unit);
sharedSdkEventLoopGroup = null;
return shutdownGracefully;
}
return SUCCEEDED_FUTURE;
}
@SdkTestInternalApi
static synchronized int referenceCount() {
return referenceCount;
}
/**
* Special event loop group that prevents shutdown and decrements the reference count when the event loop group
* is closed.
*/
private static class ReferenceCountingEventLoopGroup extends DelegatingEventLoopGroup {
private final AtomicBoolean hasBeenClosed = new AtomicBoolean(false);
private ReferenceCountingEventLoopGroup(EventLoopGroup delegate) {
super(delegate);
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
// Only want to decrement the reference the first time it's closed. Shutdown is idempotent and may be
// called multiple times.
if (hasBeenClosed.compareAndSet(false, true)) {
return decrementReference(quietPeriod, timeout, unit);
}
return SUCCEEDED_FUTURE;
}
}
}
| 1,137 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/AwaitCloseChannelPoolMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslProvider;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.ProxyConfiguration;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
import software.amazon.awssdk.http.nio.netty.internal.http2.HttpOrHttp2ChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Implementation of {@link SdkChannelPoolMap} that awaits channel pools to be closed upon closing.
*/
@SdkInternalApi
public final class AwaitCloseChannelPoolMap extends SdkChannelPoolMap<URI, SimpleChannelPoolAwareChannelPool> {
private static final NettyClientLogger log = NettyClientLogger.getLogger(AwaitCloseChannelPoolMap.class);
private static final ChannelPoolHandler NOOP_HANDLER = new ChannelPoolHandler() {
@Override
public void channelReleased(Channel ch) throws Exception {
}
@Override
public void channelAcquired(Channel ch) throws Exception {
}
@Override
public void channelCreated(Channel ch) throws Exception {
}
};
// IMPORTANT: If the default bootstrap provider is changed, ensure that the new implementation is compliant with
// DNS resolver testing in BootstrapProviderTest, specifically that no caching of hostname lookups is taking place.
private static final Function<Builder, BootstrapProvider> DEFAULT_BOOTSTRAP_PROVIDER =
b -> new BootstrapProvider(b.sdkEventLoopGroup, b.configuration, b.sdkChannelOptions);
private final Map<URI, Boolean> shouldProxyForHostCache = new ConcurrentHashMap<>();
private final NettyConfiguration configuration;
private final Protocol protocol;
private final long maxStreams;
private final Duration healthCheckPingPeriod;
private final int initialWindowSize;
private final SslProvider sslProvider;
private final ProxyConfiguration proxyConfiguration;
private final BootstrapProvider bootstrapProvider;
private final SslContextProvider sslContextProvider;
private final Boolean useNonBlockingDnsResolver;
private AwaitCloseChannelPoolMap(Builder builder, Function<Builder, BootstrapProvider> createBootStrapProvider) {
this.configuration = builder.configuration;
this.protocol = builder.protocol;
this.maxStreams = builder.maxStreams;
this.healthCheckPingPeriod = builder.healthCheckPingPeriod;
this.initialWindowSize = builder.initialWindowSize;
this.sslProvider = builder.sslProvider;
this.proxyConfiguration = builder.proxyConfiguration;
this.bootstrapProvider = createBootStrapProvider.apply(builder);
this.sslContextProvider = new SslContextProvider(configuration, protocol, sslProvider);
this.useNonBlockingDnsResolver = builder.useNonBlockingDnsResolver;
}
private AwaitCloseChannelPoolMap(Builder builder) {
this(builder, DEFAULT_BOOTSTRAP_PROVIDER);
}
@SdkTestInternalApi
AwaitCloseChannelPoolMap(Builder builder,
Map<URI, Boolean> shouldProxyForHostCache,
BootstrapProvider bootstrapProvider) {
this(builder, bootstrapProvider == null ? DEFAULT_BOOTSTRAP_PROVIDER : b -> bootstrapProvider);
if (shouldProxyForHostCache != null) {
this.shouldProxyForHostCache.putAll(shouldProxyForHostCache);
}
}
public static Builder builder() {
return new Builder();
}
@Override
protected SimpleChannelPoolAwareChannelPool newPool(URI key) {
SslContext sslContext = needSslContext(key) ? sslContextProvider.sslContext() : null;
Bootstrap bootstrap = createBootstrap(key);
AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>();
ChannelPipelineInitializer pipelineInitializer = new ChannelPipelineInitializer(protocol,
sslContext,
sslProvider,
maxStreams,
initialWindowSize,
healthCheckPingPeriod,
channelPoolRef,
configuration,
key);
BetterSimpleChannelPool tcpChannelPool;
ChannelPool baseChannelPool;
if (shouldUseProxyForHost(key)) {
tcpChannelPool = new BetterSimpleChannelPool(bootstrap, NOOP_HANDLER);
baseChannelPool = new Http1TunnelConnectionPool(bootstrap.config().group().next(), tcpChannelPool, sslContext,
proxyAddress(key), proxyConfiguration.username(), proxyConfiguration.password(),
key, pipelineInitializer, configuration);
} else {
tcpChannelPool = new BetterSimpleChannelPool(bootstrap, pipelineInitializer);
baseChannelPool = tcpChannelPool;
}
SdkChannelPool wrappedPool = wrapBaseChannelPool(bootstrap, baseChannelPool);
channelPoolRef.set(wrappedPool);
return new SimpleChannelPoolAwareChannelPool(wrappedPool, tcpChannelPool);
}
@Override
public void close() {
log.trace(null, () -> "Closing channel pools");
// If there is a new pool being added while we are iterating the pools, there might be a
// race condition between the close call of the newly acquired pool and eventLoopGroup.shutdown and it
// could cause the eventLoopGroup#shutdownGracefully to hang before it times out.
// If a new pool is being added while super.close() is running, it might be left open because
// the underlying pool map is a ConcurrentHashMap and it doesn't guarantee strong consistency for retrieval
// operations. See https://github.com/aws/aws-sdk-java-v2/pull/1200#discussion_r277906715
Collection<SimpleChannelPoolAwareChannelPool> channelPools = pools().values();
super.close();
try {
CompletableFuture.allOf(channelPools.stream()
.map(pool -> pool.underlyingSimpleChannelPool().closeFuture())
.toArray(CompletableFuture[]::new))
.get(CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException | TimeoutException e) {
throw new RuntimeException(e);
}
}
private Bootstrap createBootstrap(URI poolKey) {
String host = bootstrapHost(poolKey);
int port = bootstrapPort(poolKey);
return bootstrapProvider.createBootstrap(host, port, useNonBlockingDnsResolver);
}
private boolean shouldUseProxyForHost(URI remoteAddr) {
if (proxyConfiguration == null) {
return false;
}
return shouldProxyForHostCache.computeIfAbsent(remoteAddr, (uri) ->
proxyConfiguration.nonProxyHosts().stream().noneMatch(h -> uri.getHost().matches(h))
);
}
private String bootstrapHost(URI remoteHost) {
if (shouldUseProxyForHost(remoteHost)) {
return proxyConfiguration.host();
}
return remoteHost.getHost();
}
private int bootstrapPort(URI remoteHost) {
if (shouldUseProxyForHost(remoteHost)) {
return proxyConfiguration.port();
}
return remoteHost.getPort();
}
private URI proxyAddress(URI remoteHost) {
if (!shouldUseProxyForHost(remoteHost)) {
return null;
}
String scheme = proxyConfiguration.scheme();
if (scheme == null) {
scheme = "http";
}
try {
return new URI(scheme, null, proxyConfiguration.host(), proxyConfiguration.port(), null, null,
null);
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to construct proxy URI", e);
}
}
private SdkChannelPool wrapBaseChannelPool(Bootstrap bootstrap, ChannelPool channelPool) {
// Wrap the channel pool such that the ChannelAttributeKey.CLOSE_ON_RELEASE flag is honored.
channelPool = new HonorCloseOnReleaseChannelPool(channelPool);
// Wrap the channel pool such that HTTP 2 channels won't be released to the underlying pool while they're still in use.
SdkChannelPool sdkChannelPool = new HttpOrHttp2ChannelPool(channelPool,
bootstrap.config().group(),
configuration.maxConnections(),
configuration);
sdkChannelPool = new ListenerInvokingChannelPool(bootstrap.config().group(), sdkChannelPool, Arrays.asList(
// Add a listener that disables auto reads on acquired connections.
AutoReadDisableChannelPoolListener.create(),
// Add a listener that ensures acquired channels are marked IN_USE and thus not eligible for certain idle timeouts.
InUseTrackingChannelPoolListener.create(),
// Add a listener that removes request-specific handlers with each request.
HandlerRemovingChannelPoolListener.create(),
// Add a listener that enables auto reads on released connections.
AutoReadEnableChannelPoolListener.create()
));
// Wrap the channel pool such that an individual channel can only be released to the underlying pool once.
sdkChannelPool = new ReleaseOnceChannelPool(sdkChannelPool);
// Wrap the channel pool to guarantee all channels checked out are healthy, and all unhealthy channels checked in are
// closed.
sdkChannelPool = new HealthCheckedChannelPool(bootstrap.config().group(), configuration, sdkChannelPool);
// Wrap the channel pool such that if the Promise given to acquire(Promise) is done when the channel is acquired
// from the underlying pool, the channel is closed and released.
sdkChannelPool = new CancellableAcquireChannelPool(bootstrap.config().group().next(), sdkChannelPool);
return sdkChannelPool;
}
private boolean needSslContext(URI targetAddress) {
URI proxyAddress = proxyAddress(targetAddress);
boolean needContext = targetAddress.getScheme().equalsIgnoreCase("https")
|| proxyAddress != null && proxyAddress.getScheme().equalsIgnoreCase("https");
return needContext;
}
public static class Builder {
private SdkChannelOptions sdkChannelOptions;
private SdkEventLoopGroup sdkEventLoopGroup;
private NettyConfiguration configuration;
private Protocol protocol;
private long maxStreams;
private int initialWindowSize;
private Duration healthCheckPingPeriod;
private SslProvider sslProvider;
private ProxyConfiguration proxyConfiguration;
private Boolean useNonBlockingDnsResolver;
private Builder() {
}
public Builder sdkChannelOptions(SdkChannelOptions sdkChannelOptions) {
this.sdkChannelOptions = sdkChannelOptions;
return this;
}
public Builder sdkEventLoopGroup(SdkEventLoopGroup sdkEventLoopGroup) {
this.sdkEventLoopGroup = sdkEventLoopGroup;
return this;
}
public Builder configuration(NettyConfiguration configuration) {
this.configuration = configuration;
return this;
}
public Builder protocol(Protocol protocol) {
this.protocol = protocol;
return this;
}
public Builder maxStreams(long maxStreams) {
this.maxStreams = maxStreams;
return this;
}
public Builder initialWindowSize(int initialWindowSize) {
this.initialWindowSize = initialWindowSize;
return this;
}
public Builder healthCheckPingPeriod(Duration healthCheckPingPeriod) {
this.healthCheckPingPeriod = healthCheckPingPeriod;
return this;
}
public Builder sslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider;
return this;
}
public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) {
this.proxyConfiguration = proxyConfiguration;
return this;
}
public Builder useNonBlockingDnsResolver(Boolean useNonBlockingDnsResolver) {
this.useNonBlockingDnsResolver = useNonBlockingDnsResolver;
return this;
}
public AwaitCloseChannelPoolMap build() {
return new AwaitCloseChannelPoolMap(this);
}
}
}
| 1,138 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelPipelineInitializer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.HTTP2_CONNECTION_PING_TIMEOUT_SECONDS;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.newSslHandler;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.pool.AbstractChannelPoolHandler;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslProvider;
import java.net.URI;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2GoAwayEventListener;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2PingHandler;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2SettingsFrameHandler;
/**
* ChannelPoolHandler to configure the client pipeline.
*/
@SdkInternalApi
public final class ChannelPipelineInitializer extends AbstractChannelPoolHandler {
private final Protocol protocol;
private final SslContext sslCtx;
private final SslProvider sslProvider;
private final long clientMaxStreams;
private final int clientInitialWindowSize;
private final Duration healthCheckPingPeriod;
private final AtomicReference<ChannelPool> channelPoolRef;
private final NettyConfiguration configuration;
private final URI poolKey;
public ChannelPipelineInitializer(Protocol protocol,
SslContext sslCtx,
SslProvider sslProvider,
long clientMaxStreams,
int clientInitialWindowSize,
Duration healthCheckPingPeriod,
AtomicReference<ChannelPool> channelPoolRef,
NettyConfiguration configuration,
URI poolKey) {
this.protocol = protocol;
this.sslCtx = sslCtx;
this.sslProvider = sslProvider;
this.clientMaxStreams = clientMaxStreams;
this.clientInitialWindowSize = clientInitialWindowSize;
this.healthCheckPingPeriod = healthCheckPingPeriod;
this.channelPoolRef = channelPoolRef;
this.configuration = configuration;
this.poolKey = poolKey;
}
@Override
public void channelCreated(Channel ch) {
ch.attr(CHANNEL_DIAGNOSTICS).set(new ChannelDiagnostics(ch));
ch.attr(PROTOCOL_FUTURE).set(new CompletableFuture<>());
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = newSslHandler(sslCtx, ch.alloc(), poolKey.getHost(), poolKey.getPort(),
configuration.tlsHandshakeTimeout());
pipeline.addLast(sslHandler);
pipeline.addLast(SslCloseCompletionEventHandler.getInstance());
// Use unpooled allocator to avoid increased heap memory usage from Netty 4.1.43.
// See https://github.com/netty/netty/issues/9768
if (sslProvider == SslProvider.JDK) {
ch.config().setOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT);
}
}
if (protocol == Protocol.HTTP2) {
configureHttp2(ch, pipeline);
} else {
configureHttp11(ch, pipeline);
}
if (configuration.reapIdleConnections()) {
pipeline.addLast(new IdleConnectionReaperHandler(configuration.idleTimeoutMillis()));
}
if (configuration.connectionTtlMillis() > 0) {
pipeline.addLast(new OldConnectionReaperHandler(configuration.connectionTtlMillis()));
}
pipeline.addLast(FutureCancelHandler.getInstance());
// Only add it for h1 channel because it does not apply to
// h2 connection channel. It will be attached
// to stream channels when they are created.
if (protocol == Protocol.HTTP1_1) {
pipeline.addLast(UnusedChannelExceptionHandler.getInstance());
}
pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
}
private void configureHttp2(Channel ch, ChannelPipeline pipeline) {
// Using Http2FrameCodecBuilder and Http2MultiplexHandler based on 4.1.37 release notes
// https://netty.io/news/2019/06/28/4-1-37-Final.html
Http2FrameCodec codec =
Http2FrameCodecBuilder.forClient()
.headerSensitivityDetector((name, value) -> lowerCase(name.toString()).equals("authorization"))
.initialSettings(Http2Settings.defaultSettings().initialWindowSize(clientInitialWindowSize))
.frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
.build();
// Connection listeners have higher priority than handlers, in the eyes of the Http2FrameCodec. The Http2FrameCodec will
// close any connections when a GOAWAY is received, but we'd like to send a "GOAWAY happened" exception instead of just
// closing the connection. Because of this, we use a go-away listener instead of a handler, so that we can send the
// exception before the Http2FrameCodec closes the connection itself.
codec.connection().addListener(new Http2GoAwayEventListener(ch));
pipeline.addLast(codec);
ch.attr(HTTP2_CONNECTION).set(codec.connection());
ch.attr(HTTP2_INITIAL_WINDOW_SIZE).set(clientInitialWindowSize);
pipeline.addLast(new Http2MultiplexHandler(new NoOpChannelInitializer()));
pipeline.addLast(new Http2SettingsFrameHandler(ch, clientMaxStreams, channelPoolRef));
if (healthCheckPingPeriod == null) {
pipeline.addLast(new Http2PingHandler(HTTP2_CONNECTION_PING_TIMEOUT_SECONDS * 1_000));
} else if (healthCheckPingPeriod.toMillis() > 0) {
pipeline.addLast(new Http2PingHandler(saturatedCast(healthCheckPingPeriod.toMillis())));
}
}
private void configureHttp11(Channel ch, ChannelPipeline pipeline) {
pipeline.addLast(new HttpClientCodec());
ch.attr(PROTOCOL_FUTURE).get().complete(Protocol.HTTP1_1);
}
private static class NoOpChannelInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) {
}
}
}
| 1,139 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/HonorCloseOnReleaseChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Wrap a channel pool so that {@link ChannelAttributeKey#CLOSE_ON_RELEASE} is honored when a channel is released to the
* underlying pool.
*
* When a channel is released and {@link ChannelAttributeKey#CLOSE_ON_RELEASE} is true on the channel, the channel will be closed
* before it is released to the underlying pool.
*/
@SdkInternalApi
public class HonorCloseOnReleaseChannelPool implements ChannelPool {
private static final NettyClientLogger log = NettyClientLogger.getLogger(HonorCloseOnReleaseChannelPool.class);
private final ChannelPool delegatePool;
public HonorCloseOnReleaseChannelPool(ChannelPool delegatePool) {
this.delegatePool = delegatePool;
}
@Override
public Future<Channel> acquire() {
return delegatePool.acquire();
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
return delegatePool.acquire(promise);
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, channel.eventLoop().newPromise());
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
doInEventLoop(channel.eventLoop(), () -> {
boolean shouldCloseOnRelease = Boolean.TRUE.equals(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get());
if (shouldCloseOnRelease && channel.isOpen() && !channel.eventLoop().isShuttingDown()) {
log.debug(channel, () -> "Closing connection (" + channel.id() + "), instead of releasing it.");
channel.close();
}
delegatePool.release(channel, promise);
}).addListener(f -> {
if (!f.isSuccess()) {
promise.tryFailure(f.cause());
}
});
return promise;
}
@Override
public void close() {
delegatePool.close();
}
}
| 1,140 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/RequestAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
@SdkInternalApi
public final class RequestAdapter {
private static final String HOST = "Host";
private static final List<String> IGNORE_HEADERS = Collections.singletonList(HOST);
private final Protocol protocol;
public RequestAdapter(Protocol protocol) {
this.protocol = Validate.paramNotNull(protocol, "protocol");
}
public HttpRequest adapt(SdkHttpRequest sdkRequest) {
HttpMethod method = toNettyHttpMethod(sdkRequest.method());
HttpHeaders headers = new DefaultHttpHeaders();
String uri = encodedPathAndQueryParams(sdkRequest);
// All requests start out as HTTP/1.1 objects, even if they will
// ultimately be sent over HTTP2. Conversion to H2 is handled at a
// later stage if necessary; see HttpToHttp2OutboundAdapter.
DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers);
addHeadersToRequest(request, sdkRequest);
return request;
}
private static HttpMethod toNettyHttpMethod(SdkHttpMethod method) {
return HttpMethod.valueOf(method.name());
}
private static String encodedPathAndQueryParams(SdkHttpRequest sdkRequest) {
String encodedPath = sdkRequest.encodedPath();
if (StringUtils.isBlank(encodedPath)) {
encodedPath = "/";
}
String encodedQueryParams = sdkRequest.encodedQueryParameters()
.map(queryParams -> "?" + queryParams)
.orElse("");
return encodedPath + encodedQueryParams;
}
/**
* Configures the headers in the specified Netty HTTP request.
*/
private void addHeadersToRequest(DefaultHttpRequest httpRequest, SdkHttpRequest request) {
httpRequest.headers().add(HOST, getHostHeaderValue(request));
String scheme = request.getUri().getScheme();
if (Protocol.HTTP2 == protocol && !StringUtils.isBlank(scheme)) {
httpRequest.headers().add(ExtensionHeaderNames.SCHEME.text(), scheme);
}
// Copy over any other headers already in our request
request.forEachHeader((name, value) -> {
// Skip the Host header to avoid sending it twice, which will interfere with some signing schemes.
if (!IGNORE_HEADERS.contains(name)) {
value.forEach(h -> httpRequest.headers().add(name, h));
}
});
}
private String getHostHeaderValue(SdkHttpRequest request) {
return SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port())
? request.host()
: request.host() + ":" + request.port();
}
}
| 1,141 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/AutoReadDisableChannelPoolListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Disables auto read on in-use channels to allow upper layers to take care of flow control.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class AutoReadDisableChannelPoolListener implements ListenerInvokingChannelPool.ChannelPoolListener {
private static final AutoReadDisableChannelPoolListener INSTANCE = new AutoReadDisableChannelPoolListener();
private AutoReadDisableChannelPoolListener() {
}
@Override
public void channelAcquired(Channel channel) {
channel.config().setAutoRead(false);
}
public static AutoReadDisableChannelPoolListener create() {
return INSTANCE;
}
}
| 1,142 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ReleaseOnceChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.pool.FixedChannelPool;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.SucceededFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* Wrapper around a {@link ChannelPool} to protect it from having the same channel released twice. This can
* cause issues in {@link FixedChannelPool} and {@link Http2MultiplexedChannelPool} which has a simple
* mechanism to track leased connections.
*/
@SdkInternalApi
public class ReleaseOnceChannelPool implements SdkChannelPool {
private static final AttributeKey<AtomicBoolean> IS_RELEASED = NettyUtils.getOrCreateAttributeKey(
"software.amazon.awssdk.http.nio.netty.internal.http2.ReleaseOnceChannelPool.isReleased");
private final SdkChannelPool delegate;
public ReleaseOnceChannelPool(SdkChannelPool delegate) {
this.delegate = delegate;
}
@Override
public Future<Channel> acquire() {
return delegate.acquire().addListener(onAcquire());
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
return delegate.acquire(promise).addListener(onAcquire());
}
private GenericFutureListener<Future<Channel>> onAcquire() {
return future -> {
if (future.isSuccess()) {
future.getNow().attr(IS_RELEASED).set(new AtomicBoolean(false));
}
};
}
@Override
public Future<Void> release(Channel channel) {
if (shouldRelease(channel)) {
return delegate.release(channel);
} else {
return new SucceededFuture<>(channel.eventLoop(), null);
}
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
if (shouldRelease(channel)) {
return delegate.release(channel, promise);
} else {
return promise.setSuccess(null);
}
}
private boolean shouldRelease(Channel channel) {
// IS_RELEASED may be null if this channel was not acquired by this pool. This can happen
// for HTTP/2 when we release the parent socket channel
return channel.attr(IS_RELEASED).get() == null
|| channel.attr(IS_RELEASED).get().compareAndSet(false, true);
}
@Override
public void close() {
delegate.close();
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
return delegate.collectChannelPoolMetrics(metrics);
}
}
| 1,143 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SslCloseCompletionEventHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.getAttribute;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.ssl.SslCloseCompletionEvent;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Handles {@link SslCloseCompletionEvent}s that are sent whenever an SSL channel
* goes inactive. This most commonly occurs on a tls_close sent by the server. Channels
* in this state can't be reused so they must be closed.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class SslCloseCompletionEventHandler extends ChannelInboundHandlerAdapter {
private static final SslCloseCompletionEventHandler INSTANCE = new SslCloseCompletionEventHandler();
private SslCloseCompletionEventHandler() {
}
/**
* {@inheritDoc}
*
* Close the channel if the event is {@link SslCloseCompletionEvent} and the channel is unused.
* If the channel is being used, it will be closed in {@link ResponseHandler}
*
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
boolean channelInUse = getAttribute(ctx.channel(), ChannelAttributeKey.IN_USE).orElse(false);
if (!channelInUse && evt instanceof SslCloseCompletionEvent) {
ctx.close();
} else {
ctx.fireUserEventTriggered(evt);
}
}
public static SslCloseCompletionEventHandler getInstance() {
return INSTANCE;
}
}
| 1,144 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelAttributeKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2FrameStream;
import io.netty.util.AttributeKey;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.http2.PingTracker;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
/**
* Keys for attributes attached via {@link io.netty.channel.Channel#attr(AttributeKey)}.
*/
@SdkInternalApi
public final class ChannelAttributeKey {
/**
* Future that when a protocol (http/1.1 or h2) has been selected.
*/
public static final AttributeKey<CompletableFuture<Protocol>> PROTOCOL_FUTURE = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.protocolFuture");
/**
* Reference to {@link Http2MultiplexedChannelPool} which stores information about leased streams for a multiplexed
* connection.
*/
public static final AttributeKey<Http2MultiplexedChannelPool> HTTP2_MULTIPLEXED_CHANNEL_POOL =
NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2MultiplexedChannelPool");
public static final AttributeKey<PingTracker> PING_TRACKER =
NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.h2.pingTracker");
public static final AttributeKey<Http2Connection> HTTP2_CONNECTION =
NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2Connection");
public static final AttributeKey<Integer> HTTP2_INITIAL_WINDOW_SIZE =
NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2InitialWindowSize");
/**
* Value of the MAX_CONCURRENT_STREAMS from the server's SETTING frame.
*/
public static final AttributeKey<Long> MAX_CONCURRENT_STREAMS = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.maxConcurrentStreams");
/**
* The {@link Http2FrameStream} associated with this stream channel. This is added to stream channels when they are created,
* before they are fully initialized.
*/
public static final AttributeKey<Http2FrameStream> HTTP2_FRAME_STREAM = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.http2FrameStream");
public static final AttributeKey<ChannelDiagnostics> CHANNEL_DIAGNOSTICS = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.channelDiagnostics");
/**
* {@link AttributeKey} to keep track of whether the streaming is completed and this is set to true when we receive the *
* {@link LastHttpContent}.
*/
public static final AttributeKey<Boolean> STREAMING_COMPLETE_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.streamingComplete");
/**
* {@link AttributeKey} to keep track of whether we should close the connection after this request
* has completed.
*/
static final AttributeKey<Boolean> KEEP_ALIVE = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.keepAlive");
/**
* Attribute key for {@link RequestContext}.
*/
static final AttributeKey<RequestContext> REQUEST_CONTEXT_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.requestContext");
static final AttributeKey<Subscriber<? super ByteBuffer>> SUBSCRIBER_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.subscriber");
static final AttributeKey<Boolean> RESPONSE_COMPLETE_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.responseComplete");
static final AttributeKey<Integer> RESPONSE_STATUS_CODE = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.responseStatusCode");
static final AttributeKey<Long> RESPONSE_CONTENT_LENGTH = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.responseContentLength");
static final AttributeKey<Long> RESPONSE_DATA_READ = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.responseDataRead");
static final AttributeKey<CompletableFuture<Void>> EXECUTE_FUTURE_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.executeFuture");
static final AttributeKey<Long> EXECUTION_ID_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.executionId");
/**
* Whether the channel is still in use
*/
static final AttributeKey<Boolean> IN_USE = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.inUse");
/**
* Whether the channel should be closed once it is released.
*/
static final AttributeKey<Boolean> CLOSE_ON_RELEASE = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.closeOnRelease");
private ChannelAttributeKey() {
}
/**
* Gets the protocol of the channel assuming that it has already been negotiated.
*
* @param channel Channel to get protocol for.
* @return Protocol of channel.
*/
static Protocol getProtocolNow(Channel channel) {
// For HTTP/2 the protocol future will be on the parent socket channel
return (channel.parent() == null ? channel : channel.parent())
.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().join();
}
}
| 1,145 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelDiagnostics.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import java.time.Duration;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.ToString;
/**
* Diagnostic information that may be useful to help with debugging during error scenarios.
*/
@SdkInternalApi
public class ChannelDiagnostics {
private final Channel channel;
private final Instant channelCreationTime;
private int requestCount = 0;
private int responseCount = 0;
private long idleStart = -1;
private long idleStop = -1;
public ChannelDiagnostics(Channel channel) {
this.channel = channel;
this.channelCreationTime = Instant.now();
}
public void incrementRequestCount() {
++this.requestCount;
}
public void incrementResponseCount() {
++responseCount;
}
public int responseCount() {
return responseCount;
}
public void startIdleTimer() {
idleStart = System.nanoTime();
}
public void stopIdleTimer() {
idleStop = System.nanoTime();
}
public Duration lastIdleDuration() {
// Channel started, then stopped idling
if (idleStart > 0 && idleStop > idleStart) {
return Duration.ofNanos(idleStop - idleStart);
}
// Channel currently idling
if (idleStart > 0) {
return Duration.ofNanos(System.nanoTime() - idleStart);
}
return null;
}
@Override
public String toString() {
return ToString.builder("ChannelDiagnostics")
.add("channel", channel)
.add("channelAge", Duration.between(channelCreationTime, Instant.now()))
.add("requestCount", requestCount)
.add("responseCount", responseCount)
.add("lastIdleDuration", lastIdleDuration())
.build();
}
}
| 1,146 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/StaticKeyManagerFactorySpi.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import java.security.KeyStore;
import java.util.Arrays;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactorySpi;
import javax.net.ssl.ManagerFactoryParameters;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Validate;
/**
* Factory SPI that simply returns a statically provided set of {@link KeyManager}s.
*/
@SdkInternalApi
public final class StaticKeyManagerFactorySpi extends KeyManagerFactorySpi {
private final KeyManager[] keyManagers;
public StaticKeyManagerFactorySpi(KeyManager[] keyManagers) {
Validate.paramNotNull(keyManagers, "keyManagers");
this.keyManagers = Arrays.copyOf(keyManagers, keyManagers.length);
}
@Override
protected void engineInit(KeyStore ks, char[] password) {
throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory");
}
@Override
protected void engineInit(ManagerFactoryParameters spec) {
throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory");
}
@Override
protected KeyManager[] engineGetKeyManagers() {
return keyManagers;
}
}
| 1,147 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/BootstrapProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import java.net.InetSocketAddress;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup;
/**
* The primary purpose of this Bootstrap provider is to ensure that all Bootstraps created by it are 'unresolved'
* InetSocketAddress. This is to prevent Netty from caching the resolved address of a host and then re-using it in
* subsequent connection attempts, and instead deferring to the JVM to handle address resolution and caching.
*/
@SdkInternalApi
public class BootstrapProvider {
private final SdkEventLoopGroup sdkEventLoopGroup;
private final NettyConfiguration nettyConfiguration;
private final SdkChannelOptions sdkChannelOptions;
BootstrapProvider(SdkEventLoopGroup sdkEventLoopGroup,
NettyConfiguration nettyConfiguration,
SdkChannelOptions sdkChannelOptions) {
this.sdkEventLoopGroup = sdkEventLoopGroup;
this.nettyConfiguration = nettyConfiguration;
this.sdkChannelOptions = sdkChannelOptions;
}
/**
* Creates a Bootstrap for a specific host and port with an unresolved InetSocketAddress as the remoteAddress.
*
* @param host The unresolved remote hostname
* @param port The remote port
* @param useNonBlockingDnsResolver If true, uses the default non-blocking DNS resolver from Netty. Otherwise, the default
* JDK blocking DNS resolver will be used.
* @return A newly created Bootstrap using the configuration this provider was initialized with, and having an unresolved
* remote address.
*/
public Bootstrap createBootstrap(String host, int port, Boolean useNonBlockingDnsResolver) {
Bootstrap bootstrap =
new Bootstrap()
.group(sdkEventLoopGroup.eventLoopGroup())
.channelFactory(sdkEventLoopGroup.channelFactory())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfiguration.connectTimeoutMillis())
.option(ChannelOption.SO_KEEPALIVE, nettyConfiguration.tcpKeepAlive())
.remoteAddress(InetSocketAddress.createUnresolved(host, port));
if (Boolean.TRUE.equals(useNonBlockingDnsResolver)) {
bootstrap.resolver(DnsResolverLoader.init(sdkEventLoopGroup.datagramChannelFactory()));
}
sdkChannelOptions.channelOptions().forEach(bootstrap::option);
return bootstrap;
}
}
| 1,148 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NonManagedEventLoopGroup.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.SUCCEEDED_FUTURE;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Decorator around {@link EventLoopGroup} that prevents it from being shutdown. Used when the customer passes in a
* custom {@link EventLoopGroup} that may be shared and thus is not managed by the SDK.
*/
@SdkInternalApi
public final class NonManagedEventLoopGroup extends DelegatingEventLoopGroup {
public NonManagedEventLoopGroup(EventLoopGroup delegate) {
super(delegate);
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
return SUCCEEDED_FUTURE;
}
}
| 1,149 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ListenerInvokingChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.consumeOrPropagate;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.http2.HttpOrHttp2ChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* A {@link SdkChannelPool} that wraps and delegates to another {@link SdkChannelPool} while invoking {@link ChannelPoolListener}s
* for important events that occur.
* <p>
* {@link ChannelPoolListener} is similar to Netty's {@link ChannelPoolHandler} interface, but by invoking them as part of a
* {@link SdkChannelPool} wrapper, we are given more control over when they are invoked. For example, {@link
* HttpOrHttp2ChannelPool} may choose not to release HTTP/2 stream channels to the lowest-level pool (and instead store the
* channels in its own pool), but by instrumenting listeners that sit on top of this layer, we are still given visibility into
* these events occurring.
*/
@SdkInternalApi
public final class ListenerInvokingChannelPool implements SdkChannelPool {
private final SdkChannelPool delegatePool;
private final Supplier<Promise<Channel>> promiseFactory;
private final List<ChannelPoolListener> listeners;
/**
* Listener which is called for various actions performed on a {@link SdkChannelPool}. All listener events are guaranteed to
* be invoked as part of the {@link Channel}'s {@link EventLoop}.
*/
@SdkInternalApi
public interface ChannelPoolListener {
/**
* Called <b>after</b> a {@link Channel} was acquired by calling {@link SdkChannelPool#acquire()} or {@link
* SdkChannelPool#acquire(Promise)}.
* <p>
* This method will be called by the {@link EventLoop} of the {@link Channel}.
*/
default void channelAcquired(Channel channel) {
}
/**
* Called <b>before</b> a {@link Channel} is released by calling {@link SdkChannelPool#release(Channel)} or {@link
* SdkChannelPool#release(Channel, Promise)}.
* <p>
* This method will be called by the {@link EventLoop} of the {@link Channel}.
*/
default void channelReleased(Channel channel) {
}
}
public ListenerInvokingChannelPool(EventLoopGroup eventLoopGroup,
SdkChannelPool delegatePool,
List<ChannelPoolListener> listeners) {
this(() -> eventLoopGroup.next().newPromise(), delegatePool, listeners);
}
public ListenerInvokingChannelPool(Supplier<Promise<Channel>> promiseFactory,
SdkChannelPool delegatePool,
List<ChannelPoolListener> listeners) {
this.delegatePool = delegatePool;
this.promiseFactory = promiseFactory;
this.listeners = listeners;
}
@Override
public Future<Channel> acquire() {
return acquire(promiseFactory.get());
}
@Override
public Future<Channel> acquire(Promise<Channel> returnFuture) {
delegatePool.acquire(promiseFactory.get())
.addListener(consumeOrPropagate(returnFuture, channel -> {
NettyUtils.doInEventLoop(channel.eventLoop(), () -> {
invokeChannelAcquired(channel);
returnFuture.trySuccess(channel);
}, returnFuture);
}));
return returnFuture;
}
private void invokeChannelAcquired(Channel channel) {
listeners.forEach(listener -> listener.channelAcquired(channel));
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, channel.eventLoop().newPromise());
}
@Override
public Future<Void> release(Channel channel, Promise<Void> returnFuture) {
NettyUtils.doInEventLoop(channel.eventLoop(), () -> {
invokeChannelReleased(channel);
delegatePool.release(channel, returnFuture);
}, returnFuture);
return returnFuture;
}
private void invokeChannelReleased(Channel channel) {
listeners.forEach(listener -> listener.channelReleased(channel));
}
@Override
public void close() {
delegatePool.close();
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
return delegatePool.collectChannelPoolMetrics(metrics);
}
}
| 1,150 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/Http1TunnelConnectionPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.newSslHandler;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoop;
import io.netty.channel.pool.ChannelPool;
import io.netty.channel.pool.ChannelPoolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* Connection pool that knows how to establish a tunnel using the HTTP CONNECT method.
*/
@SdkInternalApi
public class Http1TunnelConnectionPool implements ChannelPool {
static final AttributeKey<Boolean> TUNNEL_ESTABLISHED_KEY = NettyUtils.getOrCreateAttributeKey(
"aws.http.nio.netty.async.Http1TunnelConnectionPool.tunnelEstablished");
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http1TunnelConnectionPool.class);
private final EventLoop eventLoop;
private final ChannelPool delegate;
private final SslContext sslContext;
private final URI proxyAddress;
private final String proxyUser;
private final String proxyPassword;
private final URI remoteAddress;
private final ChannelPoolHandler handler;
private final InitHandlerSupplier initHandlerSupplier;
private final NettyConfiguration nettyConfiguration;
public Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, String proxyUsername, String proxyPassword,
URI remoteAddress, ChannelPoolHandler handler, NettyConfiguration nettyConfiguration) {
this(eventLoop, delegate, sslContext,
proxyAddress, proxyUsername, proxyPassword, remoteAddress, handler,
ProxyTunnelInitHandler::new, nettyConfiguration);
}
public Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler,
NettyConfiguration nettyConfiguration) {
this(eventLoop, delegate, sslContext,
proxyAddress, null, null, remoteAddress, handler,
ProxyTunnelInitHandler::new, nettyConfiguration);
}
@SdkTestInternalApi
Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext,
URI proxyAddress, String proxyUser, String proxyPassword, URI remoteAddress,
ChannelPoolHandler handler, InitHandlerSupplier initHandlerSupplier,
NettyConfiguration nettyConfiguration) {
this.eventLoop = eventLoop;
this.delegate = delegate;
this.sslContext = sslContext;
this.proxyAddress = proxyAddress;
this.proxyUser = proxyUser;
this.proxyPassword = proxyPassword;
this.remoteAddress = remoteAddress;
this.handler = handler;
this.initHandlerSupplier = initHandlerSupplier;
this.nettyConfiguration = nettyConfiguration;
}
@Override
public Future<Channel> acquire() {
return acquire(eventLoop.newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
delegate.acquire(eventLoop.newPromise()).addListener((Future<Channel> f) -> {
if (f.isSuccess()) {
setupChannel(f.getNow(), promise);
} else {
promise.setFailure(f.cause());
}
});
return promise;
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, eventLoop.newPromise());
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
return delegate.release(channel, promise);
}
@Override
public void close() {
delegate.close();
}
private void setupChannel(Channel ch, Promise<Channel> acquirePromise) {
if (isTunnelEstablished(ch)) {
log.debug(ch, () -> String.format("Tunnel already established for %s", ch.id().asShortText()));
acquirePromise.setSuccess(ch);
return;
}
log.debug(ch, () -> String.format("Tunnel not yet established for channel %s. Establishing tunnel now.",
ch.id().asShortText()));
Promise<Channel> tunnelEstablishedPromise = eventLoop.newPromise();
SslHandler sslHandler = createSslHandlerIfNeeded(ch.alloc());
if (sslHandler != null) {
ch.pipeline().addLast(sslHandler);
}
ch.pipeline().addLast(initHandlerSupplier.newInitHandler(delegate, proxyUser, proxyPassword, remoteAddress,
tunnelEstablishedPromise));
tunnelEstablishedPromise.addListener((Future<Channel> f) -> {
if (f.isSuccess()) {
Channel tunnel = f.getNow();
handler.channelCreated(tunnel);
tunnel.attr(TUNNEL_ESTABLISHED_KEY).set(true);
acquirePromise.setSuccess(tunnel);
} else {
ch.close();
delegate.release(ch);
Throwable cause = f.cause();
log.error(ch, () -> String.format("Unable to establish tunnel for channel %s", ch.id().asShortText()), cause);
acquirePromise.setFailure(cause);
}
});
}
private SslHandler createSslHandlerIfNeeded(ByteBufAllocator alloc) {
if (sslContext == null) {
return null;
}
String scheme = proxyAddress.getScheme();
if (!"https".equals(StringUtils.lowerCase(scheme))) {
return null;
}
return newSslHandler(sslContext, alloc, proxyAddress.getHost(), proxyAddress.getPort(),
nettyConfiguration.tlsHandshakeTimeout());
}
private static boolean isTunnelEstablished(Channel ch) {
Boolean established = ch.attr(TUNNEL_ESTABLISHED_KEY).get();
return Boolean.TRUE.equals(established);
}
@SdkTestInternalApi
@FunctionalInterface
interface InitHandlerSupplier {
ChannelHandler newInitHandler(ChannelPool sourcePool, String proxyUsername, String proxyPassword, URI remoteAddress,
Promise<Channel> tunnelInitFuture);
}
}
| 1,151 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelOptions.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelOption;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class SdkChannelOptions {
private Map<ChannelOption, Object> options;
public SdkChannelOptions() {
options = new HashMap<>();
options.put(ChannelOption.TCP_NODELAY, Boolean.TRUE);
}
public <T> SdkChannelOptions putOption(ChannelOption<T> channelOption, T channelOptionValue) {
channelOption.validate(channelOptionValue);
options.put(channelOption, channelOptionValue);
return this;
}
public Map<ChannelOption, Object> channelOptions() {
return Collections.unmodifiableMap(options);
}
}
| 1,152 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/StaticTrustManagerFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.handler.ssl.util.SimpleTrustManagerFactory;
import java.security.KeyStore;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class StaticTrustManagerFactory extends SimpleTrustManagerFactory {
private final TrustManager[] trustManagers;
private StaticTrustManagerFactory(TrustManager[] trustManagers) {
this.trustManagers = trustManagers;
}
@Override
protected void engineInit(KeyStore keyStore) {
}
@Override
protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
}
@Override
protected TrustManager[] engineGetTrustManagers() {
return trustManagers;
}
public static TrustManagerFactory create(TrustManager[] trustManagers) {
return new StaticTrustManagerFactory(trustManagers);
}
}
| 1,153 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/DnsResolverLoader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.ChannelFactory;
import io.netty.channel.socket.DatagramChannel;
import io.netty.resolver.AddressResolverGroup;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.ClassLoaderHelper;
/**
* Utility class for instantiating netty dns resolvers only if they're available on the class path.
*/
@SdkProtectedApi
public class DnsResolverLoader {
private DnsResolverLoader() {
}
public static AddressResolverGroup<InetSocketAddress> init(ChannelFactory<? extends DatagramChannel> datagramChannelFactory) {
try {
Class<?> addressResolver = ClassLoaderHelper.loadClass(getAddressResolverGroup(), false, (Class) null);
Class<?> dnsNameResolverBuilder = ClassLoaderHelper.loadClass(getDnsNameResolverBuilder(), false, (Class) null);
Object dnsResolverObj = dnsNameResolverBuilder.newInstance();
Method method = dnsResolverObj.getClass().getMethod("channelFactory", ChannelFactory.class);
method.invoke(dnsResolverObj, datagramChannelFactory);
Object e = addressResolver.getConstructor(dnsNameResolverBuilder).newInstance(dnsResolverObj);
return (AddressResolverGroup<InetSocketAddress>) e;
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find module io.netty.resolver.dns "
+ " To use netty non blocking dns," +
" the 'netty-resolver-dns' module from io.netty must be on the class path. ", e);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create AddressResolverGroup", e);
}
}
private static String getAddressResolverGroup() {
return "io.netty.resolver.dns.DnsAddressResolverGroup";
}
private static String getDnsNameResolverBuilder() {
return "io.netty.resolver.dns.DnsNameResolverBuilder";
}
}
| 1,154 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyRequestMetrics.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import io.netty.channel.Channel;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.util.concurrent.Future;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Http2Metric;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
/**
* Utilities for collecting and publishing request-level metrics.
*/
@SdkInternalApi
public class NettyRequestMetrics {
private NettyRequestMetrics() {
}
/**
* Determine whether metrics are enabled, based on the provided metric collector.
*/
public static boolean metricsAreEnabled(MetricCollector metricCollector) {
return metricCollector != null && !(metricCollector instanceof NoOpMetricCollector);
}
public static void ifMetricsAreEnabled(MetricCollector metrics, Consumer<MetricCollector> metricsConsumer) {
if (metricsAreEnabled(metrics)) {
metricsConsumer.accept(metrics);
}
}
/**
* Publish stream metrics for the provided stream channel to the provided collector. This should only be invoked after
* the stream has been initialized. If the stream is not initialized when this is invoked, an exception will be thrown.
*/
public static void publishHttp2StreamMetrics(MetricCollector metricCollector, Channel channel) {
if (!metricsAreEnabled(metricCollector)) {
return;
}
getHttp2Connection(channel).ifPresent(http2Connection -> {
writeHttp2RequestMetrics(metricCollector, channel, http2Connection);
});
}
private static Optional<Http2Connection> getHttp2Connection(Channel channel) {
Channel parentChannel = channel.parent();
if (parentChannel == null) {
return Optional.empty();
}
return Optional.ofNullable(parentChannel.attr(ChannelAttributeKey.HTTP2_CONNECTION).get());
}
private static void writeHttp2RequestMetrics(MetricCollector metricCollector,
Channel channel,
Http2Connection http2Connection) {
int streamId = channel.attr(ChannelAttributeKey.HTTP2_FRAME_STREAM).get().id();
Http2Stream stream = http2Connection.stream(streamId);
metricCollector.reportMetric(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES,
http2Connection.local().flowController().windowSize(stream));
metricCollector.reportMetric(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES,
http2Connection.remote().flowController().windowSize(stream));
}
/**
* Measure the time taken for a {@link Future} to complete. Does NOT differentiate between success/failure.
*/
public static void measureTimeTaken(Future<?> future, Consumer<Duration> onDone) {
Instant start = Instant.now();
future.addListener(f -> {
Duration elapsed = Duration.between(start, Instant.now());
onDone.accept(elapsed);
});
}
}
| 1,155 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/IdleConnectionCountingChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* A channel pool implementation that tracks the number of "idle" channels in an underlying channel pool.
*
* <p>Specifically, this pool counts the number of channels acquired and then released from/to the underlying channel pool. It
* will monitor for the underlying channels to be closed, and will remove them from the "idle" count.
*/
@SdkInternalApi
public class IdleConnectionCountingChannelPool implements SdkChannelPool {
private static final NettyClientLogger log = NettyClientLogger.getLogger(IdleConnectionCountingChannelPool.class);
/**
* The idle channel state for a specific channel. This should only be accessed from the {@link #executor}.
*/
private static final AttributeKey<ChannelIdleState> CHANNEL_STATE =
NettyUtils.getOrCreateAttributeKey("IdleConnectionCountingChannelPool.CHANNEL_STATE");
/**
* The executor in which all updates to {@link #idleConnections} is performed.
*/
private final EventExecutor executor;
/**
* The delegate pool to which all acquire and release calls are delegated.
*/
private final ChannelPool delegatePool;
/**
* The number of idle connections in the underlying channel pool. This value is only valid if accessed from the
* {@link #executor}.
*/
private int idleConnections = 0;
public IdleConnectionCountingChannelPool(EventExecutor executor, ChannelPool delegatePool) {
this.executor = executor;
this.delegatePool = delegatePool;
}
@Override
public Future<Channel> acquire() {
return acquire(executor.newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
Future<Channel> acquirePromise = delegatePool.acquire(executor.newPromise());
acquirePromise.addListener(f -> {
Throwable failure = acquirePromise.cause();
if (failure != null) {
promise.setFailure(failure);
} else {
Channel channel = acquirePromise.getNow();
channelAcquired(channel);
promise.setSuccess(channel);
}
});
return promise;
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, new DefaultPromise<>(executor));
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
channelReleased(channel).addListener(f -> delegatePool.release(channel, promise));
return promise;
}
@Override
public void close() {
delegatePool.close();
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
CompletableFuture<Void> result = new CompletableFuture<>();
doInEventLoop(executor, () -> {
metrics.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, idleConnections);
result.complete(null);
}).addListener(f -> {
if (!f.isSuccess()) {
result.completeExceptionally(f.cause());
}
});
return result;
}
/**
* Add a listener to the provided channel that will update the idle channel count when the channel is closed.
*/
private void addUpdateIdleCountOnCloseListener(Channel channel) {
channel.closeFuture().addListener(f -> channelClosed(channel));
}
/**
* Invoked when a channel is acquired, marking it non-idle until it's closed or released.
*/
private void channelAcquired(Channel channel) {
doInEventLoop(executor, () -> {
ChannelIdleState channelIdleState = getChannelIdleState(channel);
if (channelIdleState == null) {
addUpdateIdleCountOnCloseListener(channel);
setChannelIdleState(channel, ChannelIdleState.NOT_IDLE);
} else {
switch (channelIdleState) {
case IDLE:
decrementIdleConnections();
setChannelIdleState(channel, ChannelIdleState.NOT_IDLE);
break;
case CLOSED:
break;
case NOT_IDLE:
default:
log.warn(channel, () -> "Failed to update idle connection count metric on acquire, because the channel "
+ "(" + channel + ") was in an unexpected state: " + channelIdleState);
}
}
});
}
/**
* Invoked when a channel is released, marking it idle until it's acquired.
*/
private Future<?> channelReleased(Channel channel) {
return doInEventLoop(executor, () -> {
ChannelIdleState channelIdleState = getChannelIdleState(channel);
if (channelIdleState == null) {
log.warn(channel,
() -> "Failed to update idle connection count metric on release, because the channel (" + channel +
") was in an unexpected state: null");
} else {
switch (channelIdleState) {
case NOT_IDLE:
incrementIdleConnections();
setChannelIdleState(channel, ChannelIdleState.IDLE);
break;
case CLOSED:
break;
case IDLE:
default:
log.warn(channel, () -> "Failed to update idle connection count metric on release, because the channel "
+ "(" + channel + ") was in an unexpected state: " + channelIdleState);
}
}
});
}
/**
* Invoked when a channel is closed, ensure it is marked as non-idle.
*/
private void channelClosed(Channel channel) {
doInEventLoop(executor, () -> {
ChannelIdleState channelIdleState = getChannelIdleState(channel);
setChannelIdleState(channel, ChannelIdleState.CLOSED);
if (channelIdleState != null) {
switch (channelIdleState) {
case IDLE:
decrementIdleConnections();
break;
case NOT_IDLE:
break;
default:
log.warn(channel,
() -> "Failed to update idle connection count metric on close, because the channel (" + channel +
") was in an unexpected state: " + channelIdleState);
}
}
});
}
private ChannelIdleState getChannelIdleState(Channel channel) {
return channel.attr(CHANNEL_STATE).get();
}
private void setChannelIdleState(Channel channel, ChannelIdleState newState) {
channel.attr(CHANNEL_STATE).set(newState);
}
/**
* Decrement the idle connection count. This must be invoked from the {@link #executor}.
*/
private void decrementIdleConnections() {
--idleConnections;
log.trace(null, () -> "Idle connection count decremented, now " + idleConnections);
}
/**
* Increment the idle connection count. This must be invoked from the {@link #executor}.
*/
private void incrementIdleConnections() {
++idleConnections;
log.trace(null, () -> "Idle connection count incremented, now " + idleConnections);
}
/**
* The idle state of a channel.
*/
private enum ChannelIdleState {
IDLE,
NOT_IDLE,
CLOSED
}
}
| 1,156 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_TIMEOUT;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_CONNECTIONS;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TCP_KEEPALIVE;
import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES;
import static software.amazon.awssdk.utils.NumericUtils.saturatedCast;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.TlsKeyManagersProvider;
import software.amazon.awssdk.http.TlsTrustManagersProvider;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Internal object for configuring netty.
*/
@SdkInternalApi
public final class NettyConfiguration {
public static final int CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS = 5;
public static final int EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS = 2;
public static final int EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS = 15;
public static final int EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS = 16;
public static final int HTTP2_CONNECTION_PING_TIMEOUT_SECONDS = 5;
private final AttributeMap configuration;
public NettyConfiguration(AttributeMap configuration) {
this.configuration = configuration;
}
public <T> T attribute(AttributeMap.Key<T> key) {
return configuration.get(key);
}
public int connectTimeoutMillis() {
return saturatedCast(configuration.get(CONNECTION_TIMEOUT).toMillis());
}
public int connectionAcquireTimeoutMillis() {
return saturatedCast(configuration.get(CONNECTION_ACQUIRE_TIMEOUT).toMillis());
}
public int maxConnections() {
return configuration.get(MAX_CONNECTIONS);
}
public int maxPendingConnectionAcquires() {
return configuration.get(MAX_PENDING_CONNECTION_ACQUIRES);
}
public int readTimeoutMillis() {
return saturatedCast(configuration.get(SdkHttpConfigurationOption.READ_TIMEOUT).toMillis());
}
public int writeTimeoutMillis() {
return saturatedCast(configuration.get(SdkHttpConfigurationOption.WRITE_TIMEOUT).toMillis());
}
public int idleTimeoutMillis() {
return saturatedCast(configuration.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis());
}
public int connectionTtlMillis() {
return saturatedCast(configuration.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE).toMillis());
}
public boolean reapIdleConnections() {
return configuration.get(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS);
}
public TlsKeyManagersProvider tlsKeyManagersProvider() {
return configuration.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
}
public TlsTrustManagersProvider tlsTrustManagersProvider() {
return configuration.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER);
}
public boolean trustAllCertificates() {
return configuration.get(TRUST_ALL_CERTIFICATES);
}
public boolean tcpKeepAlive() {
return configuration.get(TCP_KEEPALIVE);
}
public Duration tlsHandshakeTimeout() {
return configuration.get(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT);
}
}
| 1,157 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/OrderedWriteChannelHandlerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An implementation of {@link ChannelHandlerContext} that ensures all writes are performed in the order they are invoked.
*
* This works around https://github.com/netty/netty/issues/7783 where writes by an event loop 'skip ahead' of writes off of the
* event loop.
*/
@SdkInternalApi
public class OrderedWriteChannelHandlerContext extends DelegatingChannelHandlerContext {
private OrderedWriteChannelHandlerContext(ChannelHandlerContext delegate) {
super(delegate);
}
public static ChannelHandlerContext wrap(ChannelHandlerContext ctx) {
return new OrderedWriteChannelHandlerContext(ctx);
}
@Override
public ChannelFuture write(Object msg) {
return doInOrder(promise -> super.write(msg, promise));
}
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
doInOrder(() -> super.write(msg, promise));
return promise;
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return doInOrder(promise -> {
super.writeAndFlush(msg, promise);
});
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
doInOrder(() -> {
super.writeAndFlush(msg, promise);
});
return promise;
}
private ChannelFuture doInOrder(Consumer<ChannelPromise> task) {
ChannelPromise promise = newPromise();
if (!channel().eventLoop().inEventLoop()) {
task.accept(promise);
} else {
// If we're in the event loop, queue a task to perform the write, so that it occurs after writes that were scheduled
// off of the event loop.
channel().eventLoop().execute(() -> task.accept(promise));
}
return promise;
}
private void doInOrder(Runnable task) {
if (!channel().eventLoop().inEventLoop()) {
task.run();
} else {
// If we're in the event loop, queue a task to perform the write, so that it occurs after writes that were scheduled
// off of the event loop.
channel().eventLoop().execute(task);
}
}
}
| 1,158 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ExceptionHandlingUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class ExceptionHandlingUtils {
private ExceptionHandlingUtils() {
}
/**
* Runs a task within try-catch block. All exceptions thrown from the execution
* will be sent to errorNotifier.
*
* <p>
* This is useful for single-line executable code to avoid try-catch code clutter.
*
* @param executable the task to run
* @param errorNotifier error notifier
*/
public static void tryCatch(Runnable executable, Consumer<Throwable> errorNotifier) {
try {
executable.run();
} catch (Throwable throwable) {
errorNotifier.accept(throwable);
}
}
/**
* Runs a task within try-catch-finally block. All exceptions thrown from the execution
* will be sent to errorNotifier.
*
* <p>
* This is useful for single-line executable code to avoid try-catch code clutter.
*
* @param executable the task to run
* @param errorNotifier the error notifier
* @param cleanupExecutable the cleanup executable
* @param <T> the type of the object to be returned
* @return the object if succeeds
*/
public static <T> T tryCatchFinally(Callable<T> executable,
Consumer<Throwable> errorNotifier,
Runnable cleanupExecutable) {
try {
return executable.call();
} catch (Throwable throwable) {
errorNotifier.accept(throwable);
} finally {
cleanupExecutable.run();
}
return null;
}
}
| 1,159 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/DelegatingChannelHandlerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelProgressivePromise;
import io.netty.channel.ChannelPromise;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import java.net.SocketAddress;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An abstract implementation of {@link ChannelHandlerContext} that delegates to another
* context for non-overridden methods.
*/
@SdkInternalApi
public abstract class DelegatingChannelHandlerContext implements ChannelHandlerContext {
private final ChannelHandlerContext delegate;
public DelegatingChannelHandlerContext(ChannelHandlerContext delegate) {
this.delegate = delegate;
}
@Override
public Channel channel() {
return delegate.channel();
}
@Override
public EventExecutor executor() {
return delegate.executor();
}
@Override
public String name() {
return delegate.name();
}
@Override
public ChannelHandler handler() {
return delegate.handler();
}
@Override
public boolean isRemoved() {
return delegate.isRemoved();
}
@Override
public ChannelHandlerContext fireChannelRegistered() {
return delegate.fireChannelRegistered();
}
@Override
public ChannelHandlerContext fireChannelUnregistered() {
return delegate.fireChannelUnregistered();
}
@Override
public ChannelHandlerContext fireChannelActive() {
return delegate.fireChannelActive();
}
@Override
public ChannelHandlerContext fireChannelInactive() {
return delegate.fireChannelInactive();
}
@Override
public ChannelHandlerContext fireExceptionCaught(Throwable cause) {
return delegate.fireExceptionCaught(cause);
}
@Override
public ChannelHandlerContext fireUserEventTriggered(Object evt) {
return delegate.fireUserEventTriggered(evt);
}
@Override
public ChannelHandlerContext fireChannelRead(Object msg) {
return delegate.fireChannelRead(msg);
}
@Override
public ChannelHandlerContext fireChannelReadComplete() {
return delegate.fireChannelReadComplete();
}
@Override
public ChannelHandlerContext fireChannelWritabilityChanged() {
return delegate.fireChannelWritabilityChanged();
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return delegate.bind(localAddress);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return delegate.connect(remoteAddress);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return delegate.connect(remoteAddress, localAddress);
}
@Override
public ChannelFuture disconnect() {
return delegate.disconnect();
}
@Override
public ChannelFuture close() {
return delegate.close();
}
@Override
public ChannelFuture deregister() {
return delegate.deregister();
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return delegate.bind(localAddress, promise);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return delegate.connect(remoteAddress, promise);
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return delegate.connect(remoteAddress, localAddress, promise);
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return delegate.disconnect(promise);
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return delegate.close(promise);
}
@Override
public ChannelFuture deregister(ChannelPromise promise) {
return delegate.deregister(promise);
}
@Override
public ChannelHandlerContext read() {
return delegate.read();
}
@Override
public ChannelFuture write(Object msg) {
return delegate.write(msg);
}
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
return delegate.write(msg, promise);
}
@Override
public ChannelHandlerContext flush() {
return delegate.flush();
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return delegate.writeAndFlush(msg, promise);
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return delegate.writeAndFlush(msg);
}
@Override
public ChannelPromise newPromise() {
return delegate.newPromise();
}
@Override
public ChannelProgressivePromise newProgressivePromise() {
return delegate.newProgressivePromise();
}
@Override
public ChannelFuture newSucceededFuture() {
return delegate.newSucceededFuture();
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return delegate.newFailedFuture(cause);
}
@Override
public ChannelPromise voidPromise() {
return delegate.voidPromise();
}
@Override
public ChannelPipeline pipeline() {
return delegate.pipeline();
}
@Override
public ByteBufAllocator alloc() {
return delegate.alloc();
}
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return delegate.attr(key);
}
@Override
public <T> boolean hasAttr(AttributeKey<T> key) {
return delegate.hasAttr(key);
}
}
| 1,160 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/BetterFixedChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.ThrowableUtil;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* {@link ChannelPool} implementation that takes another {@link ChannelPool} implementation and enforce a maximum
* number of concurrent connections.
*/
//TODO: Contribute me back to Netty
public class BetterFixedChannelPool implements SdkChannelPool {
private static final IllegalStateException FULL_EXCEPTION = ThrowableUtil.unknownStackTrace(
new IllegalStateException("Too many outstanding acquire operations"),
BetterFixedChannelPool.class, "acquire0(...)");
private static final TimeoutException TIMEOUT_EXCEPTION = ThrowableUtil.unknownStackTrace(
new TimeoutException("Acquire operation took longer than configured maximum time"),
BetterFixedChannelPool.class, "<init>(...)");
static final IllegalStateException POOL_CLOSED_ON_RELEASE_EXCEPTION = ThrowableUtil.unknownStackTrace(
new IllegalStateException("BetterFixedChannelPooled was closed"),
BetterFixedChannelPool.class, "release(...)");
static final IllegalStateException POOL_CLOSED_ON_ACQUIRE_EXCEPTION = ThrowableUtil.unknownStackTrace(
new IllegalStateException("BetterFixedChannelPooled was closed"),
BetterFixedChannelPool.class, "acquire0(...)");
public enum AcquireTimeoutAction {
/**
* Create a new connection when the timeout is detected.
*/
NEW,
/**
* Fail the {@link Future} of the acquire call with a {@link TimeoutException}.
*/
FAIL
}
private final EventExecutor executor;
private final long acquireTimeoutNanos;
private final Runnable timeoutTask;
private final SdkChannelPool delegateChannelPool;
// There is no need to worry about synchronization as everything that modified the queue or counts is done
// by the above EventExecutor.
private final Queue<AcquireTask> pendingAcquireQueue = new ArrayDeque<>();
private final int maxConnections;
private final int maxPendingAcquires;
private int acquiredChannelCount;
private int pendingAcquireCount;
private boolean closed;
private BetterFixedChannelPool(Builder builder) {
if (builder.maxConnections < 1) {
throw new IllegalArgumentException("maxConnections: " + builder.maxConnections + " (expected: >= 1)");
}
if (builder.maxPendingAcquires < 1) {
throw new IllegalArgumentException("maxPendingAcquires: " + builder.maxPendingAcquires + " (expected: >= 1)");
}
this.delegateChannelPool = builder.channelPool;
this.executor = builder.executor;
if (builder.action == null && builder.acquireTimeoutMillis == -1) {
timeoutTask = null;
acquireTimeoutNanos = -1;
} else if (builder.action == null && builder.acquireTimeoutMillis != -1) {
throw new NullPointerException("action");
} else if (builder.action != null && builder.acquireTimeoutMillis < 0) {
throw new IllegalArgumentException("acquireTimeoutMillis: " + builder.acquireTimeoutMillis + " (expected: >= 0)");
} else {
acquireTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(builder.acquireTimeoutMillis);
switch (builder.action) {
case FAIL:
timeoutTask = new TimeoutTask() {
@Override
public void onTimeout(AcquireTask task) {
// Fail the promise as we timed out.
task.promise.setFailure(TIMEOUT_EXCEPTION);
}
};
break;
case NEW:
timeoutTask = new TimeoutTask() {
@Override
public void onTimeout(AcquireTask task) {
// Increment the acquire count and delegate to super to actually acquire a Channel which will
// create a new connection.
task.acquired();
delegateChannelPool.acquire(task.promise);
}
};
break;
default:
throw new Error();
}
}
this.maxConnections = builder.maxConnections;
this.maxPendingAcquires = builder.maxPendingAcquires;
}
@Override
public Future<Channel> acquire() {
return acquire(new DefaultPromise<>(executor));
}
@Override
public Future<Channel> acquire(final Promise<Channel> promise) {
try {
if (executor.inEventLoop()) {
acquire0(promise);
} else {
executor.execute(() -> acquire0(promise));
}
} catch (Throwable cause) {
promise.setFailure(cause);
}
return promise;
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
CompletableFuture<Void> delegateMetricResult = delegateChannelPool.collectChannelPoolMetrics(metrics);
CompletableFuture<Void> result = new CompletableFuture<>();
doInEventLoop(executor, () -> {
try {
metrics.reportMetric(HttpMetric.MAX_CONCURRENCY, this.maxConnections);
metrics.reportMetric(HttpMetric.PENDING_CONCURRENCY_ACQUIRES, this.pendingAcquireCount);
metrics.reportMetric(HttpMetric.LEASED_CONCURRENCY, this.acquiredChannelCount);
result.complete(null);
} catch (Throwable t) {
result.completeExceptionally(t);
}
});
return CompletableFuture.allOf(result, delegateMetricResult);
}
private void acquire0(final Promise<Channel> promise) {
assert executor.inEventLoop();
if (closed) {
promise.setFailure(POOL_CLOSED_ON_ACQUIRE_EXCEPTION);
return;
}
if (acquiredChannelCount < maxConnections) {
assert acquiredChannelCount >= 0;
// We need to create a new promise as we need to ensure the AcquireListener runs in the correct
// EventLoop
Promise<Channel> p = executor.newPromise();
AcquireListener l = new AcquireListener(promise);
l.acquired();
p.addListener(l);
delegateChannelPool.acquire(p);
} else {
if (pendingAcquireCount >= maxPendingAcquires) {
promise.setFailure(FULL_EXCEPTION);
} else {
AcquireTask task = new AcquireTask(promise);
if (pendingAcquireQueue.offer(task)) {
++pendingAcquireCount;
if (timeoutTask != null) {
task.timeoutFuture = executor.schedule(timeoutTask, acquireTimeoutNanos, TimeUnit.NANOSECONDS);
}
} else {
promise.setFailure(FULL_EXCEPTION);
}
}
assert pendingAcquireCount > 0;
}
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, new DefaultPromise<>(executor));
}
@Override
public Future<Void> release(final Channel channel, final Promise<Void> promise) {
ObjectUtil.checkNotNull(promise, "promise");
Promise<Void> p = executor.newPromise();
delegateChannelPool.release(channel, p.addListener(new FutureListener<Void>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
assert executor.inEventLoop();
if (closed) {
// Since the pool is closed, we have no choice but to close the channel
channel.close();
promise.setFailure(POOL_CLOSED_ON_RELEASE_EXCEPTION);
return;
}
if (future.isSuccess()) {
decrementAndRunTaskQueue();
promise.setSuccess(null);
} else {
Throwable cause = future.cause();
// Check if the exception was not because of we passed the Channel to the wrong pool.
if (!(cause instanceof IllegalArgumentException)) {
decrementAndRunTaskQueue();
}
promise.setFailure(future.cause());
}
}
}));
return promise;
}
private void decrementAndRunTaskQueue() {
--acquiredChannelCount;
// We should never have a negative value.
assert acquiredChannelCount >= 0;
// Run the pending acquire tasks before notify the original promise so if the user would
// try to acquire again from the ChannelFutureListener and the pendingAcquireCount is >=
// maxPendingAcquires we may be able to run some pending tasks first and so allow to add
// more.
runTaskQueue();
}
private void runTaskQueue() {
while (acquiredChannelCount < maxConnections) {
AcquireTask task = pendingAcquireQueue.poll();
if (task == null) {
break;
}
// Cancel the timeout if one was scheduled
ScheduledFuture<?> timeoutFuture = task.timeoutFuture;
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
--pendingAcquireCount;
task.acquired();
delegateChannelPool.acquire(task.promise);
}
// We should never have a negative value.
assert pendingAcquireCount >= 0;
assert acquiredChannelCount >= 0;
}
// AcquireTask extends AcquireListener to reduce object creations and so GC pressure
private final class AcquireTask extends AcquireListener {
final Promise<Channel> promise;
final long expireNanoTime = System.nanoTime() + acquireTimeoutNanos;
ScheduledFuture<?> timeoutFuture;
public AcquireTask(Promise<Channel> promise) {
super(promise);
// We need to create a new promise as we need to ensure the AcquireListener runs in the correct
// EventLoop.
this.promise = executor.<Channel>newPromise().addListener(this);
}
}
private abstract class TimeoutTask implements Runnable {
@Override
public final void run() {
assert executor.inEventLoop();
long nanoTime = System.nanoTime();
for (; ; ) {
AcquireTask task = pendingAcquireQueue.peek();
// Compare nanoTime as descripted in the javadocs of System.nanoTime()
//
// See https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()
// See https://github.com/netty/netty/issues/3705
if (task == null || nanoTime - task.expireNanoTime < 0) {
break;
}
pendingAcquireQueue.remove();
--pendingAcquireCount;
onTimeout(task);
}
}
public abstract void onTimeout(AcquireTask task);
}
private class AcquireListener implements FutureListener<Channel> {
private final Promise<Channel> originalPromise;
protected boolean acquired;
AcquireListener(Promise<Channel> originalPromise) {
this.originalPromise = originalPromise;
}
@Override
public void operationComplete(Future<Channel> future) throws Exception {
assert executor.inEventLoop();
if (closed) {
if (future.isSuccess()) {
// Since the pool is closed, we have no choice but to close the channel
future.getNow().close();
}
originalPromise.setFailure(POOL_CLOSED_ON_ACQUIRE_EXCEPTION);
return;
}
if (future.isSuccess()) {
originalPromise.setSuccess(future.getNow());
} else {
if (acquired) {
decrementAndRunTaskQueue();
} else {
runTaskQueue();
}
originalPromise.setFailure(future.cause());
}
}
public void acquired() {
if (acquired) {
return;
}
acquiredChannelCount++;
acquired = true;
}
}
@Override
public void close() {
if (executor.inEventLoop()) {
close0();
} else {
executor.submit(() -> close0()).awaitUninterruptibly();
}
}
private void close0() {
if (!closed) {
closed = true;
for (;;) {
AcquireTask task = pendingAcquireQueue.poll();
if (task == null) {
break;
}
ScheduledFuture<?> f = task.timeoutFuture;
if (f != null) {
f.cancel(false);
}
task.promise.setFailure(new ClosedChannelException());
}
acquiredChannelCount = 0;
pendingAcquireCount = 0;
// Ensure we dispatch this on another Thread as close0 will be called from the EventExecutor and we need
// to ensure we will not block in a EventExecutor.
GlobalEventExecutor.INSTANCE.execute(() -> delegateChannelPool.close());
}
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private SdkChannelPool channelPool;
private EventExecutor executor;
private AcquireTimeoutAction action;
private long acquireTimeoutMillis;
private int maxConnections;
private int maxPendingAcquires;
private Builder() {
}
public Builder channelPool(SdkChannelPool channelPool) {
this.channelPool = channelPool;
return this;
}
public Builder executor(EventExecutor executor) {
this.executor = executor;
return this;
}
public Builder acquireTimeoutAction(AcquireTimeoutAction action) {
this.action = action;
return this;
}
public Builder acquireTimeoutMillis(long acquireTimeoutMillis) {
this.acquireTimeoutMillis = acquireTimeoutMillis;
return this;
}
public Builder maxConnections(int maxConnections) {
this.maxConnections = maxConnections;
return this;
}
public Builder maxPendingAcquires(int maxPendingAcquires) {
this.maxPendingAcquires = maxPendingAcquires;
return this;
}
public BetterFixedChannelPool build() {
return new BetterFixedChannelPool(this);
}
}
}
| 1,161 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyClientLogger.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import io.netty.channel.Channel;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
/**
* Logger facade similar to {@link software.amazon.awssdk.utils.Logger}, that also includes channel information in the message
* when provided. When the logger has at least DEBUG level enabled, the logger uses {@link Channel#toString()} to provide the
* complete information about the channel. If only less verbose levels are available, then only the channel's ID is logged.
* <p>
* Having the channel information associated with the log message whenever available makes correlating messages that are all
* logged within the context of that channel possible; this is impossible to do otherwise because there is a 1:M mapping from
* event loops to channels.
* <p>
* <b>NOTE:</b> The absence of overrides that don't take a {@code Channel} parameter is deliberate. This is done to lessen the
* chances that a {code Channel} is omitted from the log by accident.
*/
@SdkInternalApi
public final class NettyClientLogger {
private final Logger delegateLogger;
@SdkTestInternalApi
NettyClientLogger(Logger delegateLogger) {
this.delegateLogger = delegateLogger;
}
public static NettyClientLogger getLogger(Class<?> clzz) {
Logger delegate = LoggerFactory.getLogger(clzz);
return new NettyClientLogger(delegate);
}
/**
* Log a DEBUG level message including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
*/
public void debug(Channel channel, Supplier<String> msgSupplier) {
debug(channel, msgSupplier, null);
}
/**
* Log a DEBUG level message with the given exception and including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
* @param t The throwable to log
*/
public void debug(Channel channel, Supplier<String> msgSupplier, Throwable t) {
if (!delegateLogger.isDebugEnabled()) {
return;
}
String finalMessage = prependChannelInfo(msgSupplier, channel);
delegateLogger.debug(finalMessage, t);
}
/**
* Log a WARN level message and including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
*/
public void warn(Channel channel, Supplier<String> msgSupplier) {
warn(channel, msgSupplier, null);
}
/**
* Log a ERROR level message with the given exception and including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
* @param t The throwable to log
*/
public void error(Channel channel, Supplier<String> msgSupplier, Throwable t) {
if (!delegateLogger.isErrorEnabled()) {
return;
}
String finalMessage = prependChannelInfo(msgSupplier, channel);
delegateLogger.error(finalMessage, t);
}
/**
* Log a ERROR level message and including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
*/
public void error(Channel channel, Supplier<String> msgSupplier) {
warn(channel, msgSupplier, null);
}
/**
* Log a WARN level message with the given exception and including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
* @param t The throwable to log
*/
public void warn(Channel channel, Supplier<String> msgSupplier, Throwable t) {
if (!delegateLogger.isWarnEnabled()) {
return;
}
String finalMessage = prependChannelInfo(msgSupplier, channel);
delegateLogger.warn(finalMessage, t);
}
/**
* Log a TRACE level message including the channel information.
*
* @param channel The channel for this message is being logged
* @param msgSupplier Supplier for the log message
*/
public void trace(Channel channel, Supplier<String> msgSupplier) {
if (!delegateLogger.isTraceEnabled()) {
return;
}
String finalMessage = prependChannelInfo(msgSupplier, channel);
delegateLogger.trace(finalMessage);
}
private String prependChannelInfo(Supplier<String> msgSupplier, Channel channel) {
if (channel == null) {
return msgSupplier.get();
}
String id;
if (!delegateLogger.isDebugEnabled()) {
id = channel.id().asShortText();
} else {
id = channel.toString();
}
return String.format("[Channel: %s] %s", id, msgSupplier.get());
}
}
| 1,162 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ReflectiveChannelFactory;
import io.netty.channel.epoll.EpollDatagramChannel;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.DelegatingEventLoopGroup;
@SdkInternalApi
public final class ChannelResolver {
private static final Map<String, String> KNOWN_EL_GROUPS_SOCKET_CHANNELS = new HashMap<>();
private static final Map<String, String> KNOWN_EL_GROUPS_DATAGRAM_CHANNELS = new HashMap<>();
static {
KNOWN_EL_GROUPS_SOCKET_CHANNELS.put("io.netty.channel.kqueue.KQueueEventLoopGroup",
"io.netty.channel.kqueue.KQueueSocketChannel");
KNOWN_EL_GROUPS_SOCKET_CHANNELS.put("io.netty.channel.oio.OioEventLoopGroup",
"io.netty.channel.socket.oio.OioSocketChannel");
KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.put("io.netty.channel.kqueue.KQueueEventLoopGroup",
"io.netty.channel.kqueue.KQueueDatagramChannel");
KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.put("io.netty.channel.oio.OioEventLoopGroup",
"io.netty.channel.socket.oio.OioDatagramChannel");
}
private ChannelResolver() {
}
/**
* Attempts to determine the {@link ChannelFactory} class that corresponds to the given
* event loop group.
*
* @param eventLoopGroup the event loop group to determine the {@link ChannelFactory} for
* @return A {@link ChannelFactory} instance for the given event loop group.
*/
@SuppressWarnings("unchecked")
public static ChannelFactory<? extends Channel> resolveSocketChannelFactory(EventLoopGroup eventLoopGroup) {
if (eventLoopGroup instanceof DelegatingEventLoopGroup) {
return resolveSocketChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate());
}
if (eventLoopGroup instanceof NioEventLoopGroup) {
return NioSocketChannel::new;
}
if (eventLoopGroup instanceof EpollEventLoopGroup) {
return EpollSocketChannel::new;
}
String socketFqcn = KNOWN_EL_GROUPS_SOCKET_CHANNELS.get(eventLoopGroup.getClass().getName());
if (socketFqcn == null) {
throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass());
}
return invokeSafely(() -> new ReflectiveChannelFactory(Class.forName(socketFqcn)));
}
/**
* Attempts to determine the {@link ChannelFactory} class for datagram channels that corresponds to the given
* event loop group.
*
* @param eventLoopGroup the event loop group to determine the {@link ChannelFactory} for
* @return A {@link ChannelFactory} instance for the given event loop group.
*/
@SuppressWarnings("unchecked")
public static ChannelFactory<? extends DatagramChannel> resolveDatagramChannelFactory(EventLoopGroup eventLoopGroup) {
if (eventLoopGroup instanceof DelegatingEventLoopGroup) {
return resolveDatagramChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate());
}
if (eventLoopGroup instanceof NioEventLoopGroup) {
return NioDatagramChannel::new;
}
if (eventLoopGroup instanceof EpollEventLoopGroup) {
return EpollDatagramChannel::new;
}
String datagramFqcn = KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.get(eventLoopGroup.getClass().getName());
if (datagramFqcn == null) {
throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass());
}
return invokeSafely(() -> new ReflectiveChannelFactory(Class.forName(datagramFqcn)));
}
}
| 1,163 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.WriteTimeoutException;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.SucceededFuture;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.ChannelDiagnostics;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public final class NettyUtils {
/**
* Completed succeed future.
*/
public static final SucceededFuture<?> SUCCEEDED_FUTURE = new SucceededFuture<>(null, null);
public static final String CLOSED_CHANNEL_ERROR_MESSAGE = "The connection was closed during the request. The request will "
+ "usually succeed on a retry, but if it does not: consider "
+ "disabling any proxies you have configured, enabling debug "
+ "logging, or performing a TCP dump to identify the root cause. "
+ "If this is a streaming operation, validate that data is being "
+ "read or written in a timely manner.";
private static final Logger log = Logger.loggerFor(NettyUtils.class);
private NettyUtils() {
}
public static Throwable decorateException(Channel channel, Throwable originalCause) {
if (isAcquireTimeoutException(originalCause)) {
return new Throwable(getMessageForAcquireTimeoutException(), originalCause);
} else if (isTooManyPendingAcquiresException(originalCause)) {
return new Throwable(getMessageForTooManyAcquireOperationsError(), originalCause);
} else if (originalCause instanceof ReadTimeoutException) {
return new IOException("Read timed out", originalCause);
} else if (originalCause instanceof WriteTimeoutException) {
return new IOException("Write timed out", originalCause);
} else if (originalCause instanceof ClosedChannelException || isConnectionResetException(originalCause)) {
return new IOException(NettyUtils.closedChannelMessage(channel), originalCause);
}
return originalCause;
}
private static boolean isConnectionResetException(Throwable originalCause) {
String message = originalCause.getMessage();
return originalCause instanceof IOException &&
message != null &&
message.contains("Connection reset by peer");
}
private static boolean isAcquireTimeoutException(Throwable originalCause) {
String message = originalCause.getMessage();
return originalCause instanceof TimeoutException &&
message != null &&
message.contains("Acquire operation took longer");
}
private static boolean isTooManyPendingAcquiresException(Throwable originalCause) {
String message = originalCause.getMessage();
return originalCause instanceof IllegalStateException &&
message != null &&
message.contains("Too many outstanding acquire operations");
}
private static String getMessageForAcquireTimeoutException() {
return "Acquire operation took longer than the configured maximum time. This indicates that a request cannot get a "
+ "connection from the pool within the specified maximum time. This can be due to high request rate.\n"
+ "Consider taking any of the following actions to mitigate the issue: increase max connections, "
+ "increase acquire timeout, or slowing the request rate.\n"
+ "Increasing the max connections can increase client throughput (unless the network interface is already "
+ "fully utilized), but can eventually start to hit operation system limitations on the number of file "
+ "descriptors used by the process. If you already are fully utilizing your network interface or cannot "
+ "further increase your connection count, increasing the acquire timeout gives extra time for requests to "
+ "acquire a connection before timing out. If the connections doesn't free up, the subsequent requests "
+ "will still timeout.\n"
+ "If the above mechanisms are not able to fix the issue, try smoothing out your requests so that large "
+ "traffic bursts cannot overload the client, being more efficient with the number of times you need to "
+ "call AWS, or by increasing the number of hosts sending requests.";
}
private static String getMessageForTooManyAcquireOperationsError() {
return "Maximum pending connection acquisitions exceeded. The request rate is too high for the client to keep up.\n"
+ "Consider taking any of the following actions to mitigate the issue: increase max connections, "
+ "increase max pending acquire count, decrease connection acquisition timeout, or "
+ "slow the request rate.\n"
+ "Increasing the max connections can increase client throughput (unless the network interface is already "
+ "fully utilized), but can eventually start to hit operation system limitations on the number of file "
+ "descriptors used by the process. If you already are fully utilizing your network interface or cannot "
+ "further increase your connection count, increasing the pending acquire count allows extra requests to be "
+ "buffered by the client, but can cause additional request latency and higher memory usage. If your request"
+ " latency or memory usage is already too high, decreasing the lease timeout will allow requests to fail "
+ "more quickly, reducing the number of pending connection acquisitions, but likely won't decrease the total "
+ "number of failed requests.\n"
+ "If the above mechanisms are not able to fix the issue, try smoothing out your requests so that large "
+ "traffic bursts cannot overload the client, being more efficient with the number of times you need to call "
+ "AWS, or by increasing the number of hosts sending requests.";
}
public static String closedChannelMessage(Channel channel) {
ChannelDiagnostics channelDiagnostics = channel != null && channel.attr(CHANNEL_DIAGNOSTICS) != null ?
channel.attr(CHANNEL_DIAGNOSTICS).get() : null;
ChannelDiagnostics parentChannelDiagnostics = channel != null && channel.parent() != null &&
channel.parent().attr(CHANNEL_DIAGNOSTICS) != null ?
channel.parent().attr(CHANNEL_DIAGNOSTICS).get() : null;
StringBuilder error = new StringBuilder();
error.append(CLOSED_CHANNEL_ERROR_MESSAGE);
if (channelDiagnostics != null) {
error.append(" Channel Information: ").append(channelDiagnostics);
if (parentChannelDiagnostics != null) {
error.append(" Parent Channel Information: ").append(parentChannelDiagnostics);
}
}
return error.toString();
}
/**
* Creates a {@link BiConsumer} that notifies the promise of any failures either via the {@link Throwable} passed into the
* BiConsumer of as a result of running the successFunction.
*
* @param successFunction Function called to process the successful result and map it into the result to notify the promise
* with.
* @param promise Promise to notify of success or failure.
* @param <SuccessT> Success type.
* @param <PromiseT> Type being fulfilled by the promise.
* @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method.
*/
public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> promiseNotifyingBiConsumer(
Function<SuccessT, PromiseT> successFunction, Promise<PromiseT> promise) {
return (success, fail) -> {
if (fail != null) {
promise.setFailure(fail);
} else {
try {
promise.setSuccess(successFunction.apply(success));
} catch (Throwable e) {
promise.setFailure(e);
}
}
};
}
/**
* Creates a {@link BiConsumer} that notifies the promise of any failures either via the throwable passed into the BiConsumer
* or as a result of running the successConsumer. This assumes that the successConsumer will notify the promise when it
* completes successfully.
*
* @param successConsumer BiConsumer to call if the result is successful. Promise is also passed and must be notified on
* success.
* @param promise Promise to notify.
* @param <SuccessT> Success type.
* @param <PromiseT> Type being fulfilled by the Promise.
* @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method.
*/
public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> asyncPromiseNotifyingBiConsumer(
BiConsumer<SuccessT, Promise<PromiseT>> successConsumer, Promise<PromiseT> promise) {
return (success, fail) -> {
if (fail != null) {
promise.setFailure(fail);
} else {
try {
successConsumer.accept(success, promise);
} catch (Throwable e) {
// If the successConsumer fails synchronously then we can notify the promise. If it fails asynchronously
// it's up to the successConsumer to notify.
promise.setFailure(e);
}
}
};
}
/**
* Create a {@link GenericFutureListener} that will notify the provided {@link Promise} on success and failure.
*
* @param channelPromise Promise to notify.
* @return GenericFutureListener
*/
public static <T> GenericFutureListener<Future<T>> promiseNotifyingListener(Promise<T> channelPromise) {
return future -> {
if (future.isSuccess()) {
channelPromise.setSuccess(future.getNow());
} else {
channelPromise.setFailure(future.cause());
}
};
}
/**
* Runs a task in the given {@link EventExecutor}. Runs immediately if the current thread is in the
* eventExecutor.
*
* @param eventExecutor Executor to run task in.
* @param runnable Task to run.
*
* @return The {@code Future} from from the executor.
*/
public static Future<?> doInEventLoop(EventExecutor eventExecutor, Runnable runnable) {
if (eventExecutor.inEventLoop()) {
try {
runnable.run();
return eventExecutor.newSucceededFuture(null);
} catch (Throwable t) {
return eventExecutor.newFailedFuture(t);
}
}
return eventExecutor.submit(runnable);
}
/**
* Runs a task in the given {@link EventExecutor}. Runs immediately if the current thread is in the
* eventExecutor. Notifies the given {@link Promise} if a failure occurs.
*
* @param eventExecutor Executor to run task in.
* @param runnable Task to run.
* @param promise Promise to notify if failure occurs.
*/
public static void doInEventLoop(EventExecutor eventExecutor, Runnable runnable, Promise<?> promise) {
try {
if (eventExecutor.inEventLoop()) {
runnable.run();
} else {
eventExecutor.submit(() -> {
try {
runnable.run();
} catch (Throwable e) {
promise.setFailure(e);
}
});
}
} catch (Throwable e) {
promise.setFailure(e);
}
}
public static void warnIfNotInEventLoop(EventLoop loop) {
assert loop.inEventLoop();
if (!loop.inEventLoop()) {
Exception exception =
new IllegalStateException("Execution is not in the expected event loop. Please report this issue to the "
+ "AWS SDK for Java team on GitHub, because it could result in race conditions.");
log.warn(() -> "Execution is happening outside of the expected event loop.", exception);
}
}
/**
* @return an {@code AttributeKey} for {@code attr}. This returns an existing instance if it was previously created.
*/
public static <T> AttributeKey<T> getOrCreateAttributeKey(String attr) {
if (AttributeKey.exists(attr)) {
return AttributeKey.valueOf(attr);
}
//CHECKSTYLE:OFF - This is the only place allowed to call AttributeKey.newInstance()
return AttributeKey.newInstance(attr);
//CHECKSTYLE:ON
}
/**
* @return a new {@link SslHandler} with ssl engine configured
*/
public static SslHandler newSslHandler(SslContext sslContext, ByteBufAllocator alloc, String peerHost, int peerPort,
Duration handshakeTimeout) {
// Need to provide host and port to enable SNI
// https://github.com/netty/netty/issues/3801#issuecomment-104274440
SslHandler sslHandler = sslContext.newHandler(alloc, peerHost, peerPort);
sslHandler.setHandshakeTimeout(handshakeTimeout.toMillis(), TimeUnit.MILLISECONDS);
configureSslEngine(sslHandler.engine());
return sslHandler;
}
/**
* Enable Hostname verification.
*
* See https://netty.io/4.0/api/io/netty/handler/ssl/SslContext.html#newHandler-io.netty.buffer.ByteBufAllocator-java.lang
* .String-int-
*
* @param sslEngine the sslEngine to configure
*/
private static void configureSslEngine(SSLEngine sslEngine) {
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
/**
* Create a {@link GenericFutureListener} that will propagate any failures or cancellations to the provided {@link Promise},
* or invoke the provided {@link Consumer} with the result of a successful operation completion. This is useful for chaining
* together multiple futures that may depend upon each other but that may not have the same return type.
* <p>
* Note that if you do not need the value returned by a successful completion (or if it returns {@link Void}) you may use
* {@link #runOrPropagate(Promise, Runnable)} instead.
*
* @param destination the Promise to notify upon failure or cancellation
* @param onSuccess the Consumer to invoke upon success
*/
public static <T> GenericFutureListener<Future<T>> consumeOrPropagate(Promise<?> destination, Consumer<T> onSuccess) {
return f -> {
if (f.isSuccess()) {
try {
T result = f.getNow();
onSuccess.accept(result);
} catch (Throwable t) {
destination.tryFailure(t);
}
} else if (f.isCancelled()) {
destination.cancel(false);
} else {
destination.tryFailure(f.cause());
}
};
}
/**
* Create a {@link GenericFutureListener} that will propagate any failures or cancellations to the provided {@link Promise},
* or invoke the provided {@link Runnable} upon successful operation completion. This is useful for chaining together multiple
* futures that may depend upon each other but that may not have the same return type.
*
* @param destination the Promise to notify upon failure or cancellation
* @param onSuccess the Runnable to invoke upon success
*/
public static <T> GenericFutureListener<Future<T>> runOrPropagate(Promise<?> destination, Runnable onSuccess) {
return f -> {
if (f.isSuccess()) {
try {
onSuccess.run();
} catch (Throwable t) {
destination.tryFailure(t);
}
} else if (f.isCancelled()) {
destination.cancel(false);
} else {
destination.tryFailure(f.cause());
}
};
}
public static void runAndLogError(NettyClientLogger log, String errorMsg, FunctionalUtils.UnsafeRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
log.error(null, () -> errorMsg, e);
}
}
}
| 1,164 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.utils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import java.util.NoSuchElementException;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class ChannelUtils {
private ChannelUtils() {
}
/**
* Removes handlers of the given class types from the pipeline.
*
* @param pipeline the pipeline to remove handlers from
* @param handlers handlers to remove, identified by class
*/
@SafeVarargs
public static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers) {
for (Class<? extends ChannelHandler> handler : handlers) {
if (pipeline.get(handler) != null) {
try {
pipeline.remove(handler);
} catch (NoSuchElementException exception) {
// There could still be race condition when channel gets
// closed right after removeIfExists is invoked. Ignoring
// NoSuchElementException for that edge case.
}
}
}
}
/**
* Retrieve optional attribute of the channel
*
* @param channel the channel
* @param key the key of the attribute
* @param <T> the type of the attribute value
* @return optional attribute
*/
public static <T> Optional<T> getAttribute(Channel channel, AttributeKey<T> key) {
return Optional.ofNullable(channel.attr(key))
.map(Attribute::get);
}
}
| 1,165 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2MultiplexedChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import static java.util.stream.Collectors.toList;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2LocalFlowController;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.PromiseCombiner;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.Validate;
/**
* {@link ChannelPool} implementation that handles multiplexed streams. Child channels are created
* for each HTTP/2 stream using {@link Http2StreamChannelBootstrap} with the parent channel being
* the actual socket channel. This implementation assumes that all connections have the same setting
* for MAX_CONCURRENT_STREAMS. Concurrent requests are load balanced across all available connections,
* when the max concurrency for a connection is reached then a new connection will be opened.
*
* <p>
* <b>Note:</b> This enforces no max concurrency. Relies on being wrapped with a {@link BetterFixedChannelPool}
* to enforce max concurrency which gives a bunch of other good features like timeouts, max pending acquires, etc.
* </p>
*/
@SdkInternalApi
public class Http2MultiplexedChannelPool implements SdkChannelPool {
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2MultiplexedChannelPool.class);
/**
* Reference to the {@link MultiplexedChannelRecord} on a channel.
*/
private static final AttributeKey<MultiplexedChannelRecord> MULTIPLEXED_CHANNEL = NettyUtils.getOrCreateAttributeKey(
"software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool.MULTIPLEXED_CHANNEL");
/**
* Whether a parent channel has been released yet. This guards against double-releasing to the delegate connection pool.
*/
private static final AttributeKey<Boolean> RELEASED = NettyUtils.getOrCreateAttributeKey(
"software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool.RELEASED");
private final ChannelPool connectionPool;
private final EventLoopGroup eventLoopGroup;
private final Set<MultiplexedChannelRecord> connections;
private final Duration idleConnectionTimeout;
private AtomicBoolean closed = new AtomicBoolean(false);
/**
* @param connectionPool Connection pool for parent channels (i.e. the socket channel).
*/
Http2MultiplexedChannelPool(ChannelPool connectionPool,
EventLoopGroup eventLoopGroup,
Duration idleConnectionTimeout) {
this.connectionPool = connectionPool;
this.eventLoopGroup = eventLoopGroup;
this.connections = ConcurrentHashMap.newKeySet();
this.idleConnectionTimeout = idleConnectionTimeout;
}
@SdkTestInternalApi
Http2MultiplexedChannelPool(ChannelPool connectionPool,
EventLoopGroup eventLoopGroup,
Set<MultiplexedChannelRecord> connections,
Duration idleConnectionTimeout) {
this(connectionPool, eventLoopGroup, idleConnectionTimeout);
this.connections.addAll(connections);
}
@Override
public Future<Channel> acquire() {
return acquire(eventLoopGroup.next().newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
if (closed.get()) {
return promise.setFailure(new IOException("Channel pool is closed!"));
}
for (MultiplexedChannelRecord multiplexedChannel : connections) {
if (acquireStreamOnInitializedConnection(multiplexedChannel, promise)) {
return promise;
}
}
// No available streams on existing connections, establish new connection and add it to list
acquireStreamOnNewConnection(promise);
return promise;
}
private void acquireStreamOnNewConnection(Promise<Channel> promise) {
Future<Channel> newConnectionAcquire = connectionPool.acquire();
newConnectionAcquire.addListener(f -> {
if (!newConnectionAcquire.isSuccess()) {
promise.setFailure(newConnectionAcquire.cause());
return;
}
Channel parentChannel = newConnectionAcquire.getNow();
try {
parentChannel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(this);
// When the protocol future is completed on the new connection, we're ready for new streams to be added to it.
parentChannel.attr(PROTOCOL_FUTURE).get()
.thenAccept(protocol -> acquireStreamOnFreshConnection(promise, parentChannel, protocol))
.exceptionally(throwable -> failAndCloseParent(promise, parentChannel, throwable));
} catch (Throwable e) {
failAndCloseParent(promise, parentChannel, e);
}
});
}
private void acquireStreamOnFreshConnection(Promise<Channel> promise, Channel parentChannel, Protocol protocol) {
try {
Long maxStreams = parentChannel.attr(MAX_CONCURRENT_STREAMS).get();
Validate.isTrue(protocol == Protocol.HTTP2,
"Protocol negotiated on connection (%s) was expected to be HTTP/2, but it "
+ "was %s.", parentChannel, Protocol.HTTP1_1);
Validate.isTrue(maxStreams != null,
"HTTP/2 was negotiated on the connection (%s), but the maximum number of "
+ "streams was not initialized.", parentChannel);
Validate.isTrue(maxStreams > 0, "Maximum streams were not positive on channel (%s).", parentChannel);
MultiplexedChannelRecord multiplexedChannel = new MultiplexedChannelRecord(parentChannel, maxStreams,
idleConnectionTimeout);
parentChannel.attr(MULTIPLEXED_CHANNEL).set(multiplexedChannel);
Promise<Channel> streamPromise = parentChannel.eventLoop().newPromise();
if (!acquireStreamOnInitializedConnection(multiplexedChannel, streamPromise)) {
failAndCloseParent(promise, parentChannel,
new IOException("Connection was closed while creating a new stream."));
return;
}
streamPromise.addListener(f -> {
if (!streamPromise.isSuccess()) {
promise.setFailure(streamPromise.cause());
return;
}
Channel stream = streamPromise.getNow();
cacheConnectionForFutureStreams(stream, multiplexedChannel, promise);
});
} catch (Throwable e) {
failAndCloseParent(promise, parentChannel, e);
}
}
private void cacheConnectionForFutureStreams(Channel stream,
MultiplexedChannelRecord multiplexedChannel,
Promise<Channel> promise) {
Channel parentChannel = stream.parent();
// Before we cache the connection, make sure that exceptions on the connection will remove it from the cache.
parentChannel.pipeline().addLast(ReleaseOnExceptionHandler.INSTANCE);
connections.add(multiplexedChannel);
if (closed.get()) {
// Whoops, we were closed while we were setting up. Make sure everything here is cleaned up properly.
failAndCloseParent(promise, parentChannel,
new IOException("Connection pool was closed while creating a new stream."));
return;
}
promise.setSuccess(stream);
}
/**
* By default, connection window size is a constant value:
* connectionWindowSize = 65535 + (configureInitialWindowSize - 65535) * 2.
* See https://github.com/netty/netty/blob/5c458c9a98d4d3d0345e58495e017175156d624f/codec-http2/src/main/java/io/netty
* /handler/codec/http2/Http2FrameCodec.java#L255
* We should expand connection window so that the window size proportional to the number of concurrent streams within the
* connection.
* Note that when {@code WINDOW_UPDATE} will be sent depends on the processedWindow in DefaultHttp2LocalFlowController.
*/
private void tryExpandConnectionWindow(Channel parentChannel) {
doInEventLoop(parentChannel.eventLoop(), () -> {
Http2Connection http2Connection = parentChannel.attr(HTTP2_CONNECTION).get();
Integer initialWindowSize = parentChannel.attr(HTTP2_INITIAL_WINDOW_SIZE).get();
Validate.notNull(http2Connection, "http2Connection should not be null on channel " + parentChannel);
Validate.notNull(http2Connection, "initialWindowSize should not be null on channel " + parentChannel);
Http2Stream connectionStream = http2Connection.connectionStream();
log.debug(parentChannel, () -> "Expanding connection window size for " + parentChannel + " by " + initialWindowSize);
try {
Http2LocalFlowController localFlowController = http2Connection.local().flowController();
localFlowController.incrementWindowSize(connectionStream, initialWindowSize);
} catch (Http2Exception e) {
log.warn(parentChannel, () -> "Failed to increment windowSize of connection " + parentChannel, e);
}
});
}
private Void failAndCloseParent(Promise<Channel> promise, Channel parentChannel, Throwable exception) {
log.debug(parentChannel, () -> "Channel acquiring failed, closing connection " + parentChannel, exception);
promise.setFailure(exception);
closeAndReleaseParent(parentChannel);
return null;
}
/**
* Acquire a stream on a connection that has already been initialized. This will return false if the connection cannot have
* any more streams allocated, and true if the stream can be allocated.
*
* This will NEVER complete the provided future when the return value is false. This will ALWAYS complete the provided
* future when the return value is true.
*/
private boolean acquireStreamOnInitializedConnection(MultiplexedChannelRecord channelRecord, Promise<Channel> promise) {
Promise<Channel> acquirePromise = channelRecord.getConnection().eventLoop().newPromise();
if (!channelRecord.acquireStream(acquirePromise)) {
return false;
}
acquirePromise.addListener(f -> {
try {
if (!acquirePromise.isSuccess()) {
promise.setFailure(acquirePromise.cause());
return;
}
Channel channel = acquirePromise.getNow();
channel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(this);
channel.attr(MULTIPLEXED_CHANNEL).set(channelRecord);
promise.setSuccess(channel);
tryExpandConnectionWindow(channel.parent());
} catch (Exception e) {
promise.setFailure(e);
}
});
return true;
}
@Override
public Future<Void> release(Channel childChannel) {
return release(childChannel, childChannel.eventLoop().newPromise());
}
@Override
public Future<Void> release(Channel childChannel, Promise<Void> promise) {
if (childChannel.parent() == null) {
// This isn't a child channel. Oddly enough, this is "expected" and is handled properly by the
// BetterFixedChannelPool AS LONG AS we return an IllegalArgumentException via the promise.
closeAndReleaseParent(childChannel);
return promise.setFailure(new IllegalArgumentException("Channel (" + childChannel + ") is not a child channel."));
}
Channel parentChannel = childChannel.parent();
MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get();
if (multiplexedChannel == null) {
// This is a child channel, but there is no attached multiplexed channel, which there should be if it was from
// this pool. Close it and log an error.
Exception exception = new IOException("Channel (" + childChannel + ") is not associated with any channel records. "
+ "It will be closed, but cannot be released within this pool.");
log.error(childChannel, exception::getMessage);
childChannel.close();
return promise.setFailure(exception);
}
multiplexedChannel.closeAndReleaseChild(childChannel);
if (multiplexedChannel.canBeClosedAndReleased()) {
// We just closed the last stream in a connection that has reached the end of its life.
return closeAndReleaseParent(parentChannel, null, promise);
}
return promise.setSuccess(null);
}
private Future<Void> closeAndReleaseParent(Channel parentChannel) {
return closeAndReleaseParent(parentChannel, null, parentChannel.eventLoop().newPromise());
}
private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause) {
return closeAndReleaseParent(parentChannel, cause, parentChannel.eventLoop().newPromise());
}
private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause, Promise<Void> resultPromise) {
if (parentChannel.parent() != null) {
// This isn't a parent channel. Notify it that something is wrong.
Exception exception = new IOException("Channel (" + parentChannel + ") is not a parent channel. It will be closed, "
+ "but cannot be released within this pool.");
log.error(parentChannel, exception::getMessage);
parentChannel.close();
return resultPromise.setFailure(exception);
}
MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get();
// We may not have a multiplexed channel if the parent channel hasn't been fully initialized.
if (multiplexedChannel != null) {
if (cause == null) {
multiplexedChannel.closeChildChannels();
} else {
multiplexedChannel.closeChildChannels(cause);
}
connections.remove(multiplexedChannel);
}
parentChannel.close();
if (parentChannel.attr(RELEASED).getAndSet(Boolean.TRUE) == null) {
return connectionPool.release(parentChannel, resultPromise);
}
return resultPromise.setSuccess(null);
}
void handleGoAway(Channel parentChannel, int lastStreamId, GoAwayException exception) {
log.debug(parentChannel, () -> "Received GOAWAY on " + parentChannel + " with lastStreamId of " + lastStreamId);
try {
MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get();
if (multiplexedChannel != null) {
multiplexedChannel.handleGoAway(lastStreamId, exception);
} else {
// If we don't have a multiplexed channel, the parent channel hasn't been fully initialized. Close it now.
closeAndReleaseParent(parentChannel, exception);
}
} catch (Exception e) {
log.error(parentChannel, () -> "Failed to handle GOAWAY frame on channel " + parentChannel, e);
}
}
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
Future<?> closeCompleteFuture = doClose();
try {
if (!closeCompleteFuture.await(10, TimeUnit.SECONDS)) {
throw new RuntimeException("Event loop didn't close after 10 seconds.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
Throwable exception = closeCompleteFuture.cause();
if (exception != null) {
throw new RuntimeException("Failed to close channel pool.", exception);
}
}
}
private Future<?> doClose() {
EventLoop closeEventLoop = eventLoopGroup.next();
Promise<?> closeFinishedPromise = closeEventLoop.newPromise();
doInEventLoop(closeEventLoop, () -> {
Promise<Void> releaseAllChannelsPromise = closeEventLoop.newPromise();
PromiseCombiner promiseCombiner = new PromiseCombiner(closeEventLoop);
// Create a copy of the connections to remove while we close them, in case closing updates the original list.
List<MultiplexedChannelRecord> channelsToRemove = new ArrayList<>(connections);
for (MultiplexedChannelRecord channel : channelsToRemove) {
promiseCombiner.add(closeAndReleaseParent(channel.getConnection()));
}
promiseCombiner.finish(releaseAllChannelsPromise);
releaseAllChannelsPromise.addListener(f -> {
connectionPool.close();
closeFinishedPromise.setSuccess(null);
});
});
return closeFinishedPromise;
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
CompletableFuture<Void> result = new CompletableFuture<>();
CompletableFuture<MultiplexedChannelRecord.Metrics> summedMetrics = new CompletableFuture<>();
List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics =
connections.stream()
.map(MultiplexedChannelRecord::getMetrics)
.collect(toList());
accumulateMetrics(summedMetrics, channelMetrics);
summedMetrics.whenComplete((m, t) -> {
if (t != null) {
result.completeExceptionally(t);
} else {
try {
metrics.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, Math.toIntExact(m.getAvailableStreams()));
result.complete(null);
} catch (Exception e) {
result.completeExceptionally(e);
}
}
});
return result;
}
private void accumulateMetrics(CompletableFuture<MultiplexedChannelRecord.Metrics> result,
List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics) {
accumulateMetrics(result, channelMetrics, new MultiplexedChannelRecord.Metrics(), 0);
}
private void accumulateMetrics(CompletableFuture<MultiplexedChannelRecord.Metrics> result,
List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics,
MultiplexedChannelRecord.Metrics resultAccumulator,
int index) {
if (index >= channelMetrics.size()) {
result.complete(resultAccumulator);
return;
}
channelMetrics.get(index).whenComplete((m, t) -> {
if (t != null) {
result.completeExceptionally(t);
} else {
resultAccumulator.add(m);
accumulateMetrics(result, channelMetrics, resultAccumulator, index + 1);
}
});
}
@Sharable
private static final class ReleaseOnExceptionHandler extends ChannelDuplexHandler {
private static final ReleaseOnExceptionHandler INSTANCE = new ReleaseOnExceptionHandler();
@Override
public void channelInactive(ChannelHandlerContext ctx) {
closeAndReleaseParent(ctx, new ClosedChannelException());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (cause instanceof Http2ConnectionTerminatingException) {
closeConnectionToNewRequests(ctx, cause);
} else {
closeAndReleaseParent(ctx, cause);
}
}
void closeConnectionToNewRequests(ChannelHandlerContext ctx, Throwable cause) {
MultiplexedChannelRecord multiplexedChannel = ctx.channel().attr(MULTIPLEXED_CHANNEL).get();
if (multiplexedChannel != null) {
multiplexedChannel.closeToNewStreams();
} else {
closeAndReleaseParent(ctx, cause);
}
}
private void closeAndReleaseParent(ChannelHandlerContext ctx, Throwable cause) {
Http2MultiplexedChannelPool pool = ctx.channel().attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).get();
pool.closeAndReleaseParent(ctx.channel(), cause);
}
}
}
| 1,166 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/PingFailedException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class PingFailedException extends IOException {
PingFailedException(String msg) {
super(msg);
}
PingFailedException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,167 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/GoAwayException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Exception thrown when a GOAWAY frame is sent by the service.
*/
@SdkInternalApi
public class GoAwayException extends IOException {
private final String message;
GoAwayException(long errorCode, String debugData) {
this.message = String.format("GOAWAY received from service, requesting this stream be closed. "
+ "Error Code = %d, Debug Data = %s",
errorCode, debugData);
}
@Override
public String getMessage() {
return message;
}
}
| 1,168 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ResetSendingSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
import io.netty.handler.codec.http2.Http2Error;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.async.DelegatingSubscription;
/**
* Wrapper around a {@link Subscription} to send a RST_STREAM frame on cancel.
*/
@SdkInternalApi
public class Http2ResetSendingSubscription extends DelegatingSubscription {
private final ChannelHandlerContext ctx;
public Http2ResetSendingSubscription(ChannelHandlerContext ctx, Subscription delegate) {
super(delegate);
this.ctx = ctx;
}
@Override
public void cancel() {
ctx.write(new DefaultHttp2ResetFrame(Http2Error.CANCEL));
super.cancel();
}
}
| 1,169 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/PingTracker.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.util.concurrent.ScheduledFuture;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Tracking the status after sending out the PING frame
*/
@SdkInternalApi
public final class PingTracker {
private final Supplier<ScheduledFuture<?>> timerFutureSupplier;
private ScheduledFuture<?> pingTimerFuture;
PingTracker(Supplier<ScheduledFuture<?>> timerFutureSupplier) {
this.timerFutureSupplier = timerFutureSupplier;
}
public void start() {
pingTimerFuture = timerFutureSupplier.get();
}
public void cancel() {
if (pingTimerFuture != null) {
pingTimerFuture.cancel(false);
}
}
}
| 1,170 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2PingHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2PingFrame;
import io.netty.util.concurrent.ScheduledFuture;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
import software.amazon.awssdk.utils.Validate;
/**
* Attached to a {@link Channel} to periodically check the health of HTTP2 connections via PING frames.
*
* If a channel is found to be unhealthy, this will invoke {@link ChannelPipeline#fireExceptionCaught(Throwable)}.
*/
@SdkInternalApi
public class Http2PingHandler extends SimpleChannelInboundHandler<Http2PingFrame> {
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2PingHandler.class);
private static final Http2PingFrame DEFAULT_PING_FRAME = new DefaultHttp2PingFrame(0);
private final long pingTimeoutMillis;
private ScheduledFuture<?> periodicPing;
private long lastPingSendTime = 0;
private long lastPingAckTime = 0;
public Http2PingHandler(int pingTimeoutMillis) {
this.pingTimeoutMillis = pingTimeoutMillis;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
CompletableFuture<Protocol> protocolFuture = ctx.channel().attr(ChannelAttributeKey.PROTOCOL_FUTURE).get();
Validate.validState(protocolFuture != null, "Protocol future must be initialized before handler is added.");
protocolFuture.thenAccept(p -> start(p, ctx));
}
private void start(Protocol protocol, ChannelHandlerContext ctx) {
if (protocol == Protocol.HTTP2 && periodicPing == null) {
periodicPing = ctx.channel()
.eventLoop()
.scheduleAtFixedRate(() -> doPeriodicPing(ctx.channel()), 0, pingTimeoutMillis, MILLISECONDS);
}
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
stop();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
stop();
ctx.fireChannelInactive();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2PingFrame frame) {
if (frame.ack()) {
log.debug(ctx.channel(), () -> "Received PING ACK from channel " + ctx.channel());
lastPingAckTime = System.currentTimeMillis();
} else {
ctx.fireChannelRead(frame);
}
}
private void doPeriodicPing(Channel channel) {
if (lastPingAckTime <= lastPingSendTime - pingTimeoutMillis) {
long timeSinceLastPingSend = System.currentTimeMillis() - lastPingSendTime;
channelIsUnhealthy(channel, new PingFailedException("Server did not respond to PING after " +
timeSinceLastPingSend + "ms (limit: " +
pingTimeoutMillis + "ms)"));
} else {
sendPing(channel);
}
}
private void sendPing(Channel channel) {
channel.writeAndFlush(DEFAULT_PING_FRAME).addListener(res -> {
if (!res.isSuccess()) {
log.debug(channel, () -> "Failed to write and flush PING frame to connection", res.cause());
channelIsUnhealthy(channel, new PingFailedException("Failed to send PING to the service", res.cause()));
} else {
lastPingSendTime = System.currentTimeMillis();
}
});
}
private void channelIsUnhealthy(Channel channel, PingFailedException exception) {
stop();
channel.pipeline().fireExceptionCaught(exception);
}
private void stop() {
if (periodicPing != null) {
periodicPing.cancel(false);
periodicPing = null;
}
}
}
| 1,171 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2StreamExceptionHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.TimeoutException;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Exception Handler for errors on the Http2 streams.
*/
@ChannelHandler.Sharable
@SdkInternalApi
public final class Http2StreamExceptionHandler extends ChannelInboundHandlerAdapter {
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2StreamExceptionHandler.class);
private static final Http2StreamExceptionHandler INSTANCE = new Http2StreamExceptionHandler();
private Http2StreamExceptionHandler() {
}
public static Http2StreamExceptionHandler create() {
return INSTANCE;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (isIoError(cause) && ctx.channel().parent() != null) {
Channel parent = ctx.channel().parent();
log.debug(parent, () -> "An I/O error occurred on an Http2 stream, notifying the connection channel " + parent);
parent.pipeline().fireExceptionCaught(new Http2ConnectionTerminatingException("An I/O error occurred on an "
+ "associated Http2 "
+ "stream " + ctx.channel()));
}
ctx.fireExceptionCaught(cause);
}
private boolean isIoError(Throwable cause) {
return cause instanceof TimeoutException || cause instanceof IOException;
}
}
| 1,172 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/MultiplexedChannelRecord.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.warnIfNotInEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOutboundInvoker;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
import software.amazon.awssdk.http.nio.netty.internal.ChannelDiagnostics;
import software.amazon.awssdk.http.nio.netty.internal.UnusedChannelExceptionHandler;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Contains a {@link Future} for the actual socket channel and tracks available
* streams based on the MAX_CONCURRENT_STREAMS setting for the connection.
*/
@SdkInternalApi
public class MultiplexedChannelRecord {
private static final NettyClientLogger log = NettyClientLogger.getLogger(MultiplexedChannelRecord.class);
private final Channel connection;
private final long maxConcurrencyPerConnection;
private final Long allowedIdleConnectionTimeMillis;
private final AtomicLong availableChildChannels;
private volatile long lastReserveAttemptTimeMillis;
// Only read or write in the connection.eventLoop()
private final Map<ChannelId, Http2StreamChannel> childChannels = new HashMap<>();
private ScheduledFuture<?> closeIfIdleTask;
// Only write in the connection.eventLoop()
private volatile RecordState state = RecordState.OPEN;
private volatile int lastStreamId;
MultiplexedChannelRecord(Channel connection, long maxConcurrencyPerConnection, Duration allowedIdleConnectionTime) {
this.connection = connection;
this.maxConcurrencyPerConnection = maxConcurrencyPerConnection;
this.availableChildChannels = new AtomicLong(maxConcurrencyPerConnection);
this.allowedIdleConnectionTimeMillis = allowedIdleConnectionTime == null ? null : allowedIdleConnectionTime.toMillis();
}
boolean acquireStream(Promise<Channel> promise) {
if (claimStream()) {
releaseClaimOnFailure(promise);
acquireClaimedStream(promise);
return true;
}
return false;
}
void acquireClaimedStream(Promise<Channel> promise) {
doInEventLoop(connection.eventLoop(), () -> {
if (state != RecordState.OPEN) {
String message;
// GOAWAY
if (state == RecordState.CLOSED_TO_NEW) {
message = String.format("Connection %s received GOAWAY with Last Stream ID %d. Unable to open new "
+ "streams on this connection.", connection, lastStreamId);
} else {
message = String.format("Connection %s was closed while acquiring new stream.", connection);
}
log.warn(connection, () -> message);
promise.setFailure(new IOException(message));
return;
}
Future<Http2StreamChannel> streamFuture = new Http2StreamChannelBootstrap(connection).open();
streamFuture.addListener((GenericFutureListener<Future<Http2StreamChannel>>) future -> {
warnIfNotInEventLoop(connection.eventLoop());
if (!future.isSuccess()) {
promise.setFailure(future.cause());
return;
}
Http2StreamChannel channel = future.getNow();
channel.pipeline().addLast(UnusedChannelExceptionHandler.getInstance());
channel.attr(ChannelAttributeKey.HTTP2_FRAME_STREAM).set(channel.stream());
channel.attr(ChannelAttributeKey.CHANNEL_DIAGNOSTICS).set(new ChannelDiagnostics(channel));
childChannels.put(channel.id(), channel);
promise.setSuccess(channel);
if (closeIfIdleTask == null && allowedIdleConnectionTimeMillis != null) {
enableCloseIfIdleTask();
}
});
}, promise);
}
private void enableCloseIfIdleTask() {
warnIfNotInEventLoop(connection.eventLoop());
// Don't poll more frequently than 1 second. Being overly-conservative is okay. Blowing up our CPU is not.
long taskFrequencyMillis = Math.max(allowedIdleConnectionTimeMillis, 1_000);
closeIfIdleTask = connection.eventLoop().scheduleAtFixedRate(this::closeIfIdle, taskFrequencyMillis, taskFrequencyMillis,
TimeUnit.MILLISECONDS);
connection.closeFuture().addListener(f -> closeIfIdleTask.cancel(false));
}
private void releaseClaimOnFailure(Promise<Channel> promise) {
try {
promise.addListener(f -> {
if (!promise.isSuccess()) {
releaseClaim();
}
});
} catch (Throwable e) {
releaseClaim();
throw e;
}
}
private void releaseClaim() {
if (availableChildChannels.incrementAndGet() > maxConcurrencyPerConnection) {
assert false;
log.warn(connection, () -> "Child channel count was caught attempting to be increased over max concurrency. "
+ "Please report this issue to the AWS SDK for Java team.");
availableChildChannels.decrementAndGet();
}
}
/**
* Handle a {@link Http2GoAwayFrame} on this connection, preventing new streams from being created on it, and closing any
* streams newer than the last-stream-id on the go-away frame.
*/
void handleGoAway(int lastStreamId, GoAwayException exception) {
doInEventLoop(connection.eventLoop(), () -> {
this.lastStreamId = lastStreamId;
if (state == RecordState.CLOSED) {
return;
}
if (state == RecordState.OPEN) {
state = RecordState.CLOSED_TO_NEW;
}
// Create a copy of the children to close, because fireExceptionCaught may remove from the childChannels.
List<Http2StreamChannel> childrenToClose = new ArrayList<>(childChannels.values());
childrenToClose.stream()
.filter(cc -> cc.stream().id() > lastStreamId)
.forEach(cc -> cc.pipeline().fireExceptionCaught(exception));
});
}
/**
* Prevent new streams from being acquired from the existing connection.
*/
void closeToNewStreams() {
doInEventLoop(connection.eventLoop(), () -> {
if (state == RecordState.OPEN) {
state = RecordState.CLOSED_TO_NEW;
}
});
}
/**
* Close all registered child channels, and prohibit new streams from being created on this connection.
*/
void closeChildChannels() {
closeAndExecuteOnChildChannels(ChannelOutboundInvoker::close);
}
/**
* Delivers the exception to all registered child channels, and prohibits new streams being created on this connection.
*/
void closeChildChannels(Throwable t) {
closeAndExecuteOnChildChannels(ch -> ch.pipeline().fireExceptionCaught(decorateConnectionException(t)));
}
private Throwable decorateConnectionException(Throwable t) {
String message =
String.format("An error occurred on the connection: %s, [channel: %s]. All streams will be closed", t,
connection.id());
if (t instanceof IOException) {
return new IOException(message, t);
}
return new Throwable(message, t);
}
private void closeAndExecuteOnChildChannels(Consumer<Channel> childChannelConsumer) {
doInEventLoop(connection.eventLoop(), () -> {
if (state == RecordState.CLOSED) {
return;
}
state = RecordState.CLOSED;
// Create a copy of the children, because they may be modified by the consumer.
List<Http2StreamChannel> childrenToClose = new ArrayList<>(childChannels.values());
for (Channel childChannel : childrenToClose) {
childChannelConsumer.accept(childChannel);
}
});
}
void closeAndReleaseChild(Channel childChannel) {
childChannel.close();
doInEventLoop(connection.eventLoop(), () -> {
childChannels.remove(childChannel.id());
releaseClaim();
});
}
private void closeIfIdle() {
warnIfNotInEventLoop(connection.eventLoop());
// Don't close if we have child channels.
if (!childChannels.isEmpty()) {
return;
}
// Don't close if there have been any reserves attempted since the idle connection time.
long nonVolatileLastReserveAttemptTimeMillis = lastReserveAttemptTimeMillis;
if (nonVolatileLastReserveAttemptTimeMillis > System.currentTimeMillis() - allowedIdleConnectionTimeMillis) {
return;
}
// Cut off new streams from being acquired from this connection by setting the number of available channels to 0.
// This write may fail if a reservation has happened since we checked the lastReserveAttemptTime.
if (!availableChildChannels.compareAndSet(maxConcurrencyPerConnection, 0)) {
return;
}
// If we've been closed, no need to shut down.
if (state != RecordState.OPEN) {
return;
}
log.debug(connection, () -> "Connection " + connection + " has been idle for " +
(System.currentTimeMillis() - nonVolatileLastReserveAttemptTimeMillis) +
"ms and will be shut down.");
// Mark ourselves as closed
state = RecordState.CLOSED;
// Start the shutdown process by closing the connection (which should be noticed by the connection pool)
connection.close();
}
public Channel getConnection() {
return connection;
}
private boolean claimStream() {
lastReserveAttemptTimeMillis = System.currentTimeMillis();
for (int attempt = 0; attempt < 5; ++attempt) {
if (state != RecordState.OPEN) {
return false;
}
long currentlyAvailable = availableChildChannels.get();
if (currentlyAvailable <= 0) {
return false;
}
if (availableChildChannels.compareAndSet(currentlyAvailable, currentlyAvailable - 1)) {
return true;
}
}
return false;
}
boolean canBeClosedAndReleased() {
return state != RecordState.OPEN && availableChildChannels.get() == maxConcurrencyPerConnection;
}
CompletableFuture<Metrics> getMetrics() {
CompletableFuture<Metrics> result = new CompletableFuture<>();
doInEventLoop(connection.eventLoop(), () -> {
int streamCount = childChannels.size();
result.complete(new Metrics().setAvailableStreams(maxConcurrencyPerConnection - streamCount));
});
return result;
}
private enum RecordState {
/**
* The connection is open and new streams may be acquired from it, if they are available.
*/
OPEN,
/**
* The connection is open, but new streams may not be acquired from it. This occurs when a connection is being
* shut down (e.g. after it has received a GOAWAY frame), but all streams haven't been closed yet.
*/
CLOSED_TO_NEW,
/**
* The connection is closed and new streams may not be acquired from it.
*/
CLOSED
}
public static class Metrics {
private long availableStreams = 0;
public long getAvailableStreams() {
return availableStreams;
}
public Metrics setAvailableStreams(long availableStreams) {
this.availableStreams = availableStreams;
return this;
}
public void add(Metrics rhs) {
this.availableStreams += rhs.availableStreams;
}
}
}
| 1,173 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpOrHttp2ChannelPool.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop;
import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.runOrPropagate;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.pool.ChannelPool;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.nio.netty.internal.IdleConnectionCountingChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration;
import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool;
import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* Channel pool that establishes an initial connection to determine protocol. Delegates
* to appropriate channel pool implementation depending on the protocol. This assumes that
* all connections will be negotiated with the same protocol.
*/
@SdkInternalApi
public class HttpOrHttp2ChannelPool implements SdkChannelPool {
private final ChannelPool delegatePool;
private final int maxConcurrency;
private final EventLoopGroup eventLoopGroup;
private final EventLoop eventLoop;
private final NettyConfiguration configuration;
private boolean protocolImplPromiseInitializationStarted = false;
private Promise<ChannelPool> protocolImplPromise;
private BetterFixedChannelPool protocolImpl;
private boolean closed;
public HttpOrHttp2ChannelPool(ChannelPool delegatePool,
EventLoopGroup group,
int maxConcurrency,
NettyConfiguration configuration) {
this.delegatePool = delegatePool;
this.maxConcurrency = maxConcurrency;
this.eventLoopGroup = group;
this.eventLoop = group.next();
this.configuration = configuration;
this.protocolImplPromise = eventLoop.newPromise();
}
@Override
public Future<Channel> acquire() {
return acquire(eventLoop.newPromise());
}
@Override
public Future<Channel> acquire(Promise<Channel> promise) {
doInEventLoop(eventLoop, () -> acquire0(promise), promise);
return promise;
}
private void acquire0(Promise<Channel> promise) {
if (closed) {
promise.setFailure(new IllegalStateException("Channel pool is closed!"));
return;
}
if (protocolImpl != null) {
protocolImpl.acquire(promise);
return;
}
if (!protocolImplPromiseInitializationStarted) {
initializeProtocol();
}
protocolImplPromise.addListener((GenericFutureListener<Future<ChannelPool>>) future -> {
if (future.isSuccess()) {
future.getNow().acquire(promise);
} else {
// Couldn't negotiate protocol, fail this acquire.
promise.setFailure(future.cause());
}
});
}
/**
* Establishes a single connection to initialize the protocol and choose the appropriate {@link ChannelPool} implementation
* for {@link #protocolImpl}.
*/
private void initializeProtocol() {
protocolImplPromiseInitializationStarted = true;
delegatePool.acquire().addListener((GenericFutureListener<Future<Channel>>) future -> {
if (future.isSuccess()) {
Channel newChannel = future.getNow();
newChannel.attr(PROTOCOL_FUTURE).get().whenComplete((protocol, e) -> {
if (e != null) {
failProtocolImplPromise(e);
} else {
completeProtocolConfiguration(newChannel, protocol);
}
});
} else {
failProtocolImplPromise(future.cause());
}
});
}
/**
* Fail the current protocolImplPromise and null it out so the next acquire will attempt to re-initialize it.
*
* @param e Cause of failure.
*/
private void failProtocolImplPromise(Throwable e) {
doInEventLoop(eventLoop, () -> {
protocolImplPromise.setFailure(e);
protocolImplPromise = eventLoop.newPromise();
protocolImplPromiseInitializationStarted = false;
});
}
private void completeProtocolConfiguration(Channel newChannel, Protocol protocol) {
doInEventLoop(eventLoop, () -> {
if (closed) {
closeAndRelease(newChannel, new IllegalStateException("Pool closed"));
} else {
try {
configureProtocol(newChannel, protocol);
} catch (Throwable e) {
closeAndRelease(newChannel, e);
}
}
});
}
private void closeAndRelease(Channel newChannel, Throwable e) {
newChannel.close();
delegatePool.release(newChannel);
protocolImplPromise.setFailure(e);
}
private void configureProtocol(Channel newChannel, Protocol protocol) {
if (Protocol.HTTP1_1 == protocol) {
// For HTTP/1.1 we use a traditional channel pool without multiplexing
SdkChannelPool idleConnectionMetricChannelPool = new IdleConnectionCountingChannelPool(eventLoop, delegatePool);
protocolImpl = BetterFixedChannelPool.builder()
.channelPool(idleConnectionMetricChannelPool)
.executor(eventLoop)
.acquireTimeoutAction(BetterFixedChannelPool.AcquireTimeoutAction.FAIL)
.acquireTimeoutMillis(configuration.connectionAcquireTimeoutMillis())
.maxConnections(maxConcurrency)
.maxPendingAcquires(configuration.maxPendingConnectionAcquires())
.build();
} else {
Duration idleConnectionTimeout = configuration.reapIdleConnections()
? Duration.ofMillis(configuration.idleTimeoutMillis()) : null;
SdkChannelPool h2Pool = new Http2MultiplexedChannelPool(delegatePool, eventLoopGroup, idleConnectionTimeout);
protocolImpl = BetterFixedChannelPool.builder()
.channelPool(h2Pool)
.executor(eventLoop)
.acquireTimeoutAction(BetterFixedChannelPool.AcquireTimeoutAction.FAIL)
.acquireTimeoutMillis(configuration.connectionAcquireTimeoutMillis())
.maxConnections(maxConcurrency)
.maxPendingAcquires(configuration.maxPendingConnectionAcquires())
.build();
}
// Give the channel back so it can be acquired again by protocolImpl
// Await the release completion to ensure we do not unnecessarily acquire a second channel
delegatePool.release(newChannel).addListener(runOrPropagate(protocolImplPromise, () -> {
protocolImplPromise.trySuccess(protocolImpl);
}));
}
@Override
public Future<Void> release(Channel channel) {
return release(channel, eventLoop.newPromise());
}
@Override
public Future<Void> release(Channel channel, Promise<Void> promise) {
doInEventLoop(eventLoop,
() -> release0(channel, promise),
promise);
return promise;
}
private void release0(Channel channel, Promise<Void> promise) {
if (protocolImpl == null) {
// If protocolImpl is null that means the first connection failed to establish. Release it back to the
// underlying connection pool.
delegatePool.release(channel, promise);
} else {
protocolImpl.release(channel, promise);
}
}
@Override
public void close() {
doInEventLoop(eventLoop, this::close0);
}
private void close0() {
if (closed) {
return;
}
closed = true;
if (protocolImpl != null) {
protocolImpl.close();
} else if (protocolImplPromiseInitializationStarted) {
protocolImplPromise.addListener((Future<ChannelPool> f) -> {
if (f.isSuccess()) {
f.getNow().close();
} else {
delegatePool.close();
}
});
} else {
delegatePool.close();
}
}
@Override
public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) {
CompletableFuture<Void> result = new CompletableFuture<>();
protocolImplPromise.addListener(f -> {
if (!f.isSuccess()) {
result.completeExceptionally(f.cause());
} else {
protocolImpl.collectChannelPoolMetrics(metrics).whenComplete((m, t) -> {
if (t != null) {
result.completeExceptionally(t);
} else {
result.complete(m);
}
});
}
});
return result;
}
}
| 1,174 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ConnectionTerminatingException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Exception indicating a connection is terminating
*/
@SdkInternalApi
final class Http2ConnectionTerminatingException extends RuntimeException {
Http2ConnectionTerminatingException(String message) {
super(message);
}
}
| 1,175 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/FlushOnReadHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This is an HTTP/2 related workaround for an issue where a WINDOW_UPDATE is
* queued but not written to the socket, causing a read() on the channel to
* hang if the remote endpoint thinks our inbound window is 0.
*/
@SdkInternalApi
@ChannelHandler.Sharable
public final class FlushOnReadHandler extends ChannelOutboundHandlerAdapter {
private static final FlushOnReadHandler INSTANCE = new FlushOnReadHandler();
private FlushOnReadHandler() {
}
@Override
public void read(ChannelHandlerContext ctx) {
//Note: order is important, we need to fire the read() event first
// since it's what triggers the WINDOW_UPDATE frame write
ctx.read();
ctx.channel().parent().flush();
}
public static FlushOnReadHandler getInstance() {
return INSTANCE;
}
}
| 1,176 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ToHttpInboundAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.DefaultLastHttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2ResetFrame;
import io.netty.handler.codec.http2.HttpConversionUtil;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Converts {@link Http2Frame}s to {@link HttpObject}s. Ignores the majority of {@link Http2Frame}s like PING
* or SETTINGS.
*/
@SdkInternalApi
public class Http2ToHttpInboundAdapter extends SimpleChannelInboundHandler<Http2Frame> {
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2ToHttpInboundAdapter.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) throws Exception {
if (frame instanceof Http2DataFrame) {
onDataRead((Http2DataFrame) frame, ctx);
} else if (frame instanceof Http2HeadersFrame) {
onHeadersRead((Http2HeadersFrame) frame, ctx);
ctx.channel().read();
} else if (frame instanceof Http2ResetFrame) {
onRstStreamRead((Http2ResetFrame) frame, ctx);
} else {
// TODO this is related to the inbound window update bug. Revisit
ctx.channel().parent().read();
}
}
private void onHeadersRead(Http2HeadersFrame headersFrame, ChannelHandlerContext ctx) throws Http2Exception {
HttpResponse httpResponse = HttpConversionUtil.toHttpResponse(headersFrame.stream().id(), headersFrame.headers(), true);
ctx.fireChannelRead(httpResponse);
if (HttpStatusFamily.of(httpResponse.status().code()) == HttpStatusFamily.SERVER_ERROR) {
fireConnectionExceptionForServerError(ctx);
}
}
private void fireConnectionExceptionForServerError(ChannelHandlerContext ctx) {
if (ctx.channel().parent() != null) {
Channel parent = ctx.channel().parent();
log.debug(ctx.channel(),
() -> "A 5xx server error occurred on an Http2 stream, notifying the connection channel " + ctx.channel());
parent.pipeline().fireExceptionCaught(new Http2ConnectionTerminatingException("A 5xx server error occurred on an "
+ "Http2 stream " + ctx.channel()));
}
}
private void onDataRead(Http2DataFrame dataFrame, ChannelHandlerContext ctx) throws Http2Exception {
ByteBuf data = dataFrame.content();
data.retain();
if (!dataFrame.isEndStream()) {
ctx.fireChannelRead(new DefaultHttpContent(data));
} else {
ctx.fireChannelRead(new DefaultLastHttpContent(data));
}
}
private void onRstStreamRead(Http2ResetFrame resetFrame, ChannelHandlerContext ctx) throws Http2Exception {
ctx.fireExceptionCaught(new Http2ResetException(resetFrame.errorCode()));
}
public static final class Http2ResetException extends IOException {
Http2ResetException(long errorCode) {
super(String.format("Connection reset. Error - %s(%d)", Http2Error.valueOf(errorCode).name(), errorCode));
}
}
}
| 1,177 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2GoAwayEventListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.handler.codec.http2.Http2ConnectionAdapter;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import java.nio.charset.StandardCharsets;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* Handles {@link Http2GoAwayFrame}s sent on a connection. This will pass the frame along to the connection's
* {@link Http2MultiplexedChannelPool#handleGoAway(Channel, int, GoAwayException)}.
*/
@SdkInternalApi
public final class Http2GoAwayEventListener extends Http2ConnectionAdapter {
private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2GoAwayEventListener.class);
private final Channel parentChannel;
public Http2GoAwayEventListener(Channel parentChannel) {
this.parentChannel = parentChannel;
}
@Override
public void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData) {
Http2MultiplexedChannelPool channelPool = parentChannel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL).get();
GoAwayException exception = new GoAwayException(errorCode, debugData.toString(StandardCharsets.UTF_8));
if (channelPool != null) {
channelPool.handleGoAway(parentChannel, lastStreamId, exception);
} else {
log.warn(parentChannel, () -> "GOAWAY received on a connection (" + parentChannel + ") not associated with any "
+ "multiplexed "
+ "channel pool.");
parentChannel.pipeline().fireExceptionCaught(exception);
}
}
}
| 1,178 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpToHttp2OutboundAdapter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http2.DefaultHttp2DataFrame;
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.EmptyHttp2Headers;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2MultiplexCodec;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.EventExecutor;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Translates HTTP/1.1 Netty objects to the corresponding HTTP/2 frame objects. Much of this was lifted from
* {@link HttpToHttp2ConnectionHandler} but since that actually encodes to the raw bytes it doesn't play nice with
* {@link Http2MultiplexCodec} which expects the frame objects.
*/
@SdkInternalApi
public class HttpToHttp2OutboundAdapter extends ChannelOutboundHandlerAdapter {
public HttpToHttp2OutboundAdapter() {
}
/**
* Handles conversion of {@link HttpMessage} and {@link HttpContent} to HTTP/2 frames.
*/
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) {
ctx.write(msg, promise);
return;
}
boolean release = true;
SimpleChannelPromiseAggregator promiseAggregator =
new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor());
try {
boolean endStream = false;
if (msg instanceof HttpMessage) {
HttpMessage httpMsg = (HttpMessage) msg;
// Convert and write the headers.
Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(httpMsg, false);
endStream = msg instanceof FullHttpMessage && !((FullHttpMessage) msg).content().isReadable();
ctx.write(new DefaultHttp2HeadersFrame(http2Headers), promiseAggregator.newPromise());
}
if (!endStream && msg instanceof HttpContent) {
boolean isLastContent = false;
HttpHeaders trailers = EmptyHttpHeaders.INSTANCE;
Http2Headers http2Trailers = EmptyHttp2Headers.INSTANCE;
if (msg instanceof LastHttpContent) {
isLastContent = true;
// Convert any trailing headers.
LastHttpContent lastContent = (LastHttpContent) msg;
trailers = lastContent.trailingHeaders();
http2Trailers = HttpConversionUtil.toHttp2Headers(trailers, false);
}
// Write the data
ByteBuf content = ((HttpContent) msg).content();
endStream = isLastContent && trailers.isEmpty();
release = false;
ctx.write(new DefaultHttp2DataFrame(content, endStream), promiseAggregator.newPromise());
if (!trailers.isEmpty()) {
// Write trailing headers.
ctx.write(new DefaultHttp2HeadersFrame(http2Trailers, true), promiseAggregator.newPromise());
}
ctx.flush();
}
} catch (Throwable t) {
promiseAggregator.setFailure(t);
} finally {
if (release) {
ReferenceCountUtil.release(msg);
}
promiseAggregator.doneAllocatingPromises();
}
}
/**
* Provides the ability to associate the outcome of multiple {@link ChannelPromise}
* objects into a single {@link ChannelPromise} object.
*/
static final class SimpleChannelPromiseAggregator extends DefaultChannelPromise {
private final ChannelPromise promise;
private int expectedCount;
private int doneCount;
private Throwable lastFailure;
private boolean doneAllocating;
SimpleChannelPromiseAggregator(ChannelPromise promise, Channel c, EventExecutor e) {
super(c, e);
assert promise != null && !promise.isDone();
this.promise = promise;
}
/**
* Allocate a new promise which will be used to aggregate the overall success of this promise aggregator.
*
* @return A new promise which will be aggregated.
* {@code null} if {@link #doneAllocatingPromises()} was previously called.
*/
public ChannelPromise newPromise() {
assert !doneAllocating : "Done allocating. No more promises can be allocated.";
++expectedCount;
return this;
}
/**
* Signify that no more {@link #newPromise()} allocations will be made.
* The aggregation can not be successful until this method is called.
*
* @return The promise that is the aggregation of all promises allocated with {@link #newPromise()}.
*/
public ChannelPromise doneAllocatingPromises() {
if (!doneAllocating) {
doneAllocating = true;
if (doneCount == expectedCount || expectedCount == 0) {
return setPromise();
}
}
return this;
}
@Override
public boolean tryFailure(Throwable cause) {
if (allowFailure()) {
++doneCount;
lastFailure = cause;
if (allPromisesDone()) {
return tryPromise();
}
// TODO: We break the interface a bit here.
// Multiple failure events can be processed without issue because this is an aggregation.
return true;
}
return false;
}
/**
* Fail this object if it has not already been failed.
* <p>
* This method will NOT throw an {@link IllegalStateException} if called multiple times
* because that may be expected.
*/
@Override
public ChannelPromise setFailure(Throwable cause) {
if (allowFailure()) {
++doneCount;
lastFailure = cause;
if (allPromisesDone()) {
return setPromise();
}
}
return this;
}
@Override
public ChannelPromise setSuccess(Void result) {
if (awaitingPromises()) {
++doneCount;
if (allPromisesDone()) {
setPromise();
}
}
return this;
}
@Override
public boolean trySuccess(Void result) {
if (awaitingPromises()) {
++doneCount;
if (allPromisesDone()) {
return tryPromise();
}
// TODO: We break the interface a bit here.
// Multiple success events can be processed without issue because this is an aggregation.
return true;
}
return false;
}
private boolean allowFailure() {
return awaitingPromises() || expectedCount == 0;
}
private boolean awaitingPromises() {
return doneCount < expectedCount;
}
private boolean allPromisesDone() {
return doneCount == expectedCount && doneAllocating;
}
private ChannelPromise setPromise() {
if (lastFailure == null) {
promise.setSuccess();
return super.setSuccess(null);
} else {
promise.setFailure(lastFailure);
return super.setFailure(lastFailure);
}
}
private boolean tryPromise() {
if (lastFailure == null) {
promise.trySuccess();
return super.trySuccess(null);
} else {
promise.tryFailure(lastFailure);
return super.tryFailure(lastFailure);
}
}
}
}
| 1,179 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2SettingsFrameHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.http2;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.pool.ChannelPool;
import io.netty.handler.codec.http2.Http2SettingsFrame;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.Protocol;
/**
* Configure channel based on the {@link Http2SettingsFrame} received from server
*/
@SdkInternalApi
public final class Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> {
private Channel channel;
private final long clientMaxStreams;
private AtomicReference<ChannelPool> channelPoolRef;
public Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef) {
this.channel = channel;
this.clientMaxStreams = clientMaxStreams;
this.channelPoolRef = channelPoolRef;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2SettingsFrame msg) {
Long serverMaxStreams = Optional.ofNullable(msg.settings().maxConcurrentStreams()).orElse(Long.MAX_VALUE);
channel.attr(MAX_CONCURRENT_STREAMS).set(Math.min(clientMaxStreams, serverMaxStreams));
channel.attr(PROTOCOL_FUTURE).get().complete(Protocol.HTTP2);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
if (!channel.attr(PROTOCOL_FUTURE).get().isDone()) {
channelError(new IOException("The channel was closed before the protocol could be determined."), channel, ctx);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
channelError(cause, channel, ctx);
}
private void channelError(Throwable cause, Channel ch, ChannelHandlerContext ctx) {
ch.attr(PROTOCOL_FUTURE).get().completeExceptionally(cause);
ctx.fireExceptionCaught(cause);
// Channel status may still be active at this point even if it's not so queue up the close so that status is
// accurately updated
ch.eventLoop().submit(() -> {
try {
if (ch.isActive()) {
ch.close();
}
} finally {
channelPoolRef.get().release(ch);
}
});
}
}
| 1,180 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/EmptyHttpResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
class EmptyHttpResponse extends DelegateHttpResponse implements FullHttpResponse {
EmptyHttpResponse(HttpResponse response) {
super(response);
}
@Override
public FullHttpResponse setStatus(HttpResponseStatus status) {
super.setStatus(status);
return this;
}
@Override
public FullHttpResponse setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public FullHttpResponse copy() {
if (response instanceof FullHttpResponse) {
return new EmptyHttpResponse(((FullHttpResponse) response).copy());
} else {
DefaultHttpResponse copy = new DefaultHttpResponse(protocolVersion(), status());
copy.headers().set(headers());
return new EmptyHttpResponse(copy);
}
}
@Override
public FullHttpResponse retain(int increment) {
ReferenceCountUtil.retain(message, increment);
return this;
}
@Override
public FullHttpResponse retain() {
ReferenceCountUtil.retain(message);
return this;
}
@Override
public FullHttpResponse touch() {
if (response instanceof FullHttpResponse) {
return ((FullHttpResponse) response).touch();
} else {
return this;
}
}
@Override
public FullHttpResponse touch(Object o) {
if (response instanceof FullHttpResponse) {
return ((FullHttpResponse) response).touch(o);
} else {
return this;
}
}
@Override
public HttpHeaders trailingHeaders() {
return new DefaultHttpHeaders();
}
@Override
public FullHttpResponse duplicate() {
if (response instanceof FullHttpResponse) {
return ((FullHttpResponse) response).duplicate();
} else {
return this;
}
}
@Override
public FullHttpResponse retainedDuplicate() {
if (response instanceof FullHttpResponse) {
return ((FullHttpResponse) response).retainedDuplicate();
} else {
return this;
}
}
@Override
public FullHttpResponse replace(ByteBuf byteBuf) {
if (response instanceof FullHttpResponse) {
return ((FullHttpResponse) response).replace(byteBuf);
} else {
return this;
}
}
@Override
public ByteBuf content() {
return Unpooled.EMPTY_BUFFER;
}
@Override
public int refCnt() {
if (message instanceof ReferenceCounted) {
return ((ReferenceCounted) message).refCnt();
} else {
return 1;
}
}
@Override
public boolean release() {
return ReferenceCountUtil.release(message);
}
@Override
public boolean release(int decrement) {
return ReferenceCountUtil.release(message, decrement);
}
}
| 1,181 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
class DelegateHttpRequest extends DelegateHttpMessage implements HttpRequest {
protected final HttpRequest request;
DelegateHttpRequest(HttpRequest request) {
super(request);
this.request = request;
}
@Override
public HttpRequest setMethod(HttpMethod method) {
request.setMethod(method);
return this;
}
@Override
public HttpRequest setUri(String uri) {
request.setUri(uri);
return this;
}
@Override
@Deprecated
public HttpMethod getMethod() {
return request.method();
}
@Override
public HttpMethod method() {
return request.method();
}
@Override
@Deprecated
public String getUri() {
return request.uri();
}
@Override
public String uri() {
return request.uri();
}
@Override
public HttpRequest setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
}
| 1,182 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HttpStreamsClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Handler that converts written {@link StreamedHttpRequest} messages into {@link HttpRequest} messages
* followed by {@link HttpContent} messages and reads {@link HttpResponse} messages followed by
* {@link HttpContent} messages and produces {@link StreamedHttpResponse} messages.
*
* This allows request and response bodies to be handled using reactive streams.
*
* There are two types of messages that this handler accepts for writing, {@link StreamedHttpRequest} and
* {@link FullHttpRequest}. Writing any other messages may potentially lead to HTTP message mangling.
*
* There are two types of messages that this handler will send down the chain, {@link StreamedHttpResponse},
* and {@link FullHttpResponse}. If {@link io.netty.channel.ChannelOption#AUTO_READ} is false for the channel,
* then any {@link StreamedHttpResponse} messages <em>must</em> be subscribed to consume the body, otherwise
* it's possible that no read will be done of the messages.
*
* As long as messages are returned in the order that they arrive, this handler implicitly supports HTTP
* pipelining.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public class HttpStreamsClientHandler extends HttpStreamsHandler<HttpResponse, HttpRequest> {
private int inFlight = 0;
private int withServer = 0;
private ChannelPromise closeOnZeroInFlight = null;
private Subscriber<HttpContent> awaiting100Continue;
private StreamedHttpMessage awaiting100ContinueMessage;
private boolean ignoreResponseBody = false;
public HttpStreamsClientHandler() {
super(HttpResponse.class, HttpRequest.class);
}
@Override
protected boolean hasBody(HttpResponse response) {
if (response.status().code() >= 100 && response.status().code() < 200) {
return false;
}
if (response.status().equals(HttpResponseStatus.NO_CONTENT) ||
response.status().equals(HttpResponseStatus.NOT_MODIFIED)) {
return false;
}
if (HttpUtil.isTransferEncodingChunked(response)) {
return true;
}
if (HttpUtil.isContentLengthSet(response)) {
return HttpUtil.getContentLength(response) > 0;
}
return true;
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
if (inFlight == 0) {
ctx.close(future);
} else {
closeOnZeroInFlight = future;
}
}
@Override
protected void consumedInMessage(ChannelHandlerContext ctx) {
inFlight--;
withServer--;
if (inFlight == 0 && closeOnZeroInFlight != null) {
ctx.close(closeOnZeroInFlight);
}
}
@Override
protected void receivedOutMessage(ChannelHandlerContext ctx) {
inFlight++;
}
@Override
protected void sentOutMessage(ChannelHandlerContext ctx) {
withServer++;
}
@Override
protected HttpResponse createEmptyMessage(HttpResponse response) {
return new EmptyHttpResponse(response);
}
@Override
protected HttpResponse createStreamedMessage(HttpResponse response, Publisher<HttpContent> stream) {
return new DelegateStreamedHttpResponse(response, stream);
}
@Override
protected void subscribeSubscriberToStream(StreamedHttpMessage msg, Subscriber<HttpContent> subscriber) {
if (HttpUtil.is100ContinueExpected(msg)) {
awaiting100Continue = subscriber;
awaiting100ContinueMessage = msg;
} else {
super.subscribeSubscriberToStream(msg, subscriber);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse && awaiting100Continue != null && withServer == 0) {
HttpResponse response = (HttpResponse) msg;
if (response.status().equals(HttpResponseStatus.CONTINUE)) {
super.subscribeSubscriberToStream(awaiting100ContinueMessage, awaiting100Continue);
awaiting100Continue = null;
awaiting100ContinueMessage = null;
if (msg instanceof FullHttpResponse) {
ReferenceCountUtil.release(msg);
} else {
ignoreResponseBody = true;
}
} else {
awaiting100ContinueMessage.subscribe(new CancelledSubscriber<HttpContent>());
awaiting100ContinueMessage = null;
awaiting100Continue.onSubscribe(new NoOpSubscription());
awaiting100Continue.onComplete();
awaiting100Continue = null;
super.channelRead(ctx, msg);
}
} else if (ignoreResponseBody && msg instanceof HttpContent) {
ReferenceCountUtil.release(msg);
if (msg instanceof LastHttpContent) {
ignoreResponseBody = false;
}
} else {
super.channelRead(ctx, msg);
}
}
private static class NoOpSubscription implements Subscription {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
}
}
| 1,183 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpRequest;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Combines {@link HttpRequest} and {@link StreamedHttpMessage} into one
* message. So it represents an http request with a stream of
* {@link io.netty.handler.codec.http.HttpContent} messages that can be subscribed to.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public interface StreamedHttpRequest extends HttpRequest, StreamedHttpMessage {
}
| 1,184 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpResponse;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Combines {@link HttpResponse} and {@link StreamedHttpMessage} into one
* message. So it represents an http response with a stream of
* {@link io.netty.handler.codec.http.HttpContent} messages that can be subscribed to.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public interface StreamedHttpResponse extends HttpResponse, StreamedHttpMessage {
}
| 1,185 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.EventExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.OrderedWriteChannelHandlerContext;
import software.amazon.awssdk.utils.Validate;
/**
* Subscriber that publishes received messages to the handler pipeline.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public class HandlerSubscriber<T> extends ChannelDuplexHandler implements Subscriber<T> {
static final long DEFAULT_LOW_WATERMARK = 4;
static final long DEFAULT_HIGH_WATERMARK = 16;
private final EventExecutor executor;
private final long demandLowWatermark;
private final long demandHighWatermark;
private final AtomicBoolean hasSubscription = new AtomicBoolean();
private volatile Subscription subscription;
private volatile ChannelHandlerContext ctx;
private State state = HandlerSubscriber.State.NO_SUBSCRIPTION_OR_CONTEXT;
private long outstandingDemand = 0;
private ChannelFuture lastWriteFuture;
/**
* Create a new handler subscriber.
*
* The supplied executor must be the same event loop as the event loop that this handler is eventually registered
* with, if not, an exception will be thrown when the handler is registered.
*
* @param executor The executor to execute asynchronous events from the publisher on.
* @param demandLowWatermark The low watermark for demand. When demand drops below this, more will be requested.
* @param demandHighWatermark The high watermark for demand. This is the maximum that will be requested.
*/
public HandlerSubscriber(EventExecutor executor, long demandLowWatermark, long demandHighWatermark) {
this.executor = executor;
this.demandLowWatermark = demandLowWatermark;
this.demandHighWatermark = demandHighWatermark;
}
/**
* Create a new handler subscriber with the default low and high watermarks.
*
* The supplied executor must be the same event loop as the event loop that this handler is eventually registered
* with, if not, an exception will be thrown when the handler is registered.
*
* @param executor The executor to execute asynchronous events from the publisher on.
* @see #HandlerSubscriber(EventExecutor, long, long)
*/
public HandlerSubscriber(EventExecutor executor) {
this(executor, DEFAULT_LOW_WATERMARK, DEFAULT_HIGH_WATERMARK);
}
/**
* Override for custom error handling. By default, it closes the channel.
*
* @param error The error to handle.
*/
protected void error(Throwable error) {
doClose();
}
/**
* Override for custom completion handling. By default, it closes the channel.
*/
protected void complete() {
doClose();
}
enum State {
NO_SUBSCRIPTION_OR_CONTEXT,
NO_SUBSCRIPTION,
NO_CONTEXT,
INACTIVE,
RUNNING,
CANCELLED,
COMPLETE
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
verifyRegisteredWithRightExecutor(ctx);
// Ensure that writes to the context happen consecutively, even if they're performed from within the event loop.
// See https://github.com/netty/netty/issues/7783
ctx = OrderedWriteChannelHandlerContext.wrap(ctx);
switch (state) {
case NO_SUBSCRIPTION_OR_CONTEXT:
this.ctx = ctx;
// We were in no subscription or context, now we just don't have a subscription.
state = HandlerSubscriber.State.NO_SUBSCRIPTION;
break;
case NO_CONTEXT:
this.ctx = ctx;
// We were in no context, we're now fully initialised
maybeStart();
break;
case COMPLETE:
// We are complete, close
state = HandlerSubscriber.State.COMPLETE;
ctx.close();
break;
default:
throw new IllegalStateException("This handler must only be added to a pipeline once " + state);
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
verifyRegisteredWithRightExecutor(ctx);
ctx.fireChannelRegistered();
}
private void verifyRegisteredWithRightExecutor(ChannelHandlerContext ctx) {
if (ctx.channel().isRegistered() && !executor.inEventLoop()) {
throw new IllegalArgumentException("Channel handler MUST be registered with the same EventExecutor that "
+ "it is created with.");
}
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
maybeRequestMore();
ctx.fireChannelWritabilityChanged();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (state == HandlerSubscriber.State.INACTIVE) {
state = HandlerSubscriber.State.RUNNING;
maybeRequestMore();
}
ctx.fireChannelActive();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
cancel();
ctx.fireChannelInactive();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
cancel();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cancel();
ctx.fireExceptionCaught(cause);
}
private void cancel() {
switch (state) {
case NO_SUBSCRIPTION:
state = HandlerSubscriber.State.CANCELLED;
break;
case RUNNING:
case INACTIVE:
subscription.cancel();
state = HandlerSubscriber.State.CANCELLED;
break;
default:
// ignore
}
}
@Override
public void onSubscribe(final Subscription subscription) {
if (subscription == null) {
throw new NullPointerException("Null subscription");
} else if (!hasSubscription.compareAndSet(false, true)) {
subscription.cancel();
} else {
this.subscription = subscription;
executor.execute(new Runnable() {
@Override
public void run() {
provideSubscription();
}
});
}
}
private void provideSubscription() {
switch (state) {
case NO_SUBSCRIPTION_OR_CONTEXT:
state = HandlerSubscriber.State.NO_CONTEXT;
break;
case NO_SUBSCRIPTION:
maybeStart();
break;
case CANCELLED:
subscription.cancel();
break;
default:
// ignore
}
}
private void maybeStart() {
if (ctx.channel().isActive()) {
state = HandlerSubscriber.State.RUNNING;
maybeRequestMore();
} else {
state = HandlerSubscriber.State.INACTIVE;
}
}
@Override
public void onNext(T t) {
// Publish straight to the context.
Validate.notNull(t, "Event must not be null.");
lastWriteFuture = ctx.writeAndFlush(t);
lastWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
outstandingDemand--;
maybeRequestMore();
}
});
}
@Override
public void onError(final Throwable error) {
if (error == null) {
throw new NullPointerException("Null error published");
}
error(error);
}
@Override
public void onComplete() {
if (lastWriteFuture == null) {
complete();
} else {
lastWriteFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
complete();
}
});
}
}
private void doClose() {
executor.execute(new Runnable() {
@Override
public void run() {
switch (state) {
case NO_SUBSCRIPTION:
case INACTIVE:
case RUNNING:
ctx.close();
state = HandlerSubscriber.State.COMPLETE;
break;
default:
// ignore
}
}
});
}
private void maybeRequestMore() {
if (outstandingDemand <= demandLowWatermark && ctx.channel().isWritable()) {
long toRequest = demandHighWatermark - outstandingDemand;
outstandingDemand = demandHighWatermark;
subscription.request(toRequest);
}
}
}
| 1,186 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DefaultStreamedHttpRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import java.util.Objects;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A default streamed HTTP request.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public class DefaultStreamedHttpRequest extends DefaultHttpRequest implements StreamedHttpRequest {
private final Publisher<HttpContent> stream;
public DefaultStreamedHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri, Publisher<HttpContent> stream) {
super(httpVersion, method, uri);
this.stream = stream;
}
public DefaultStreamedHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri, boolean validateHeaders,
Publisher<HttpContent> stream) {
super(httpVersion, method, uri, validateHeaders);
this.stream = stream;
}
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
stream.subscribe(subscriber);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
DefaultStreamedHttpRequest that = (DefaultStreamedHttpRequest) o;
return Objects.equals(stream, that.stream);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (stream != null ? stream.hashCode() : 0);
return result;
}
}
| 1,187 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HttpStreamsHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.STREAMING_COMPLETE_KEY;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import java.util.LinkedList;
import java.util.Queue;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
abstract class HttpStreamsHandler<InT extends HttpMessage, OutT extends HttpMessage> extends ChannelDuplexHandler {
private static final NettyClientLogger logger = NettyClientLogger.getLogger(HttpStreamsHandler.class);
private final Queue<Outgoing> outgoing = new LinkedList<>();
private final Class<InT> inClass;
private final Class<OutT> outClass;
/**
* The incoming message that is currently being streamed out to a subscriber.
*
* This is tracked so that if its subscriber cancels, we can go into a mode where we ignore the rest of the body.
* Since subscribers may cancel as many times as they like, including well after they've received all their content,
* we need to track what the current message that's being streamed out is so that we can ignore it if it's not
* currently being streamed out.
*/
private InT currentlyStreamedMessage;
/**
* Ignore the remaining reads for the incoming message.
*
* This is used in conjunction with currentlyStreamedMessage, as well as in situations where we have received the
* full body, but still might be expecting a last http content message.
*/
private boolean ignoreBodyRead;
/**
* Whether a LastHttpContent message needs to be written once the incoming publisher completes.
*
* Since the publisher may itself publish a LastHttpContent message, we need to track this fact, because if it
* doesn't, then we need to write one ourselves.
*/
private boolean sendLastHttpContent;
HttpStreamsHandler(Class<InT> inClass, Class<OutT> outClass) {
this.inClass = inClass;
this.outClass = outClass;
}
/**
* Whether the given incoming message has a body.
*/
protected abstract boolean hasBody(InT in);
/**
* Create an empty incoming message. This must be of type FullHttpMessage, and is invoked when we've determined
* that an incoming message can't have a body, so we send it on as a FullHttpMessage.
*/
protected abstract InT createEmptyMessage(InT in);
/**
* Create a streamed incoming message with the given stream.
*/
protected abstract InT createStreamedMessage(InT in, Publisher<HttpContent> stream);
/**
* Invoked when an incoming message is first received.
*
* Overridden by sub classes for state tracking.
*/
protected void receivedInMessage(ChannelHandlerContext ctx) {
}
/**
* Invoked when an incoming message is fully consumed.
*
* Overridden by sub classes for state tracking.
*/
protected void consumedInMessage(ChannelHandlerContext ctx) {
}
/**
* Invoked when an outgoing message is first received.
*
* Overridden by sub classes for state tracking.
*/
protected void receivedOutMessage(ChannelHandlerContext ctx) {
}
/**
* Invoked when an outgoing message is fully sent.
*
* Overridden by sub classes for state tracking.
*/
protected void sentOutMessage(ChannelHandlerContext ctx) {
}
/**
* Subscribe the given subscriber to the given streamed message.
*
* Provided so that the client subclass can intercept this to hold off sending the body of an expect 100 continue
* request.
*/
protected void subscribeSubscriberToStream(StreamedHttpMessage msg, Subscriber<HttpContent> subscriber) {
msg.subscribe(subscriber);
}
/**
* Invoked every time a read of the incoming body is requested by the subscriber.
*
* Provided so that the server subclass can intercept this to send a 100 continue response.
*/
protected void bodyRequested(ChannelHandlerContext ctx) {
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
if (inClass.isInstance(msg)) {
receivedInMessage(ctx);
InT inMsg = inClass.cast(msg);
if (inMsg instanceof FullHttpMessage) {
// Forward as is
ctx.fireChannelRead(inMsg);
consumedInMessage(ctx);
} else if (!hasBody(inMsg)) {
// Wrap in empty message
ctx.fireChannelRead(createEmptyMessage(inMsg));
consumedInMessage(ctx);
// There will be a LastHttpContent message coming after this, ignore it
ignoreBodyRead = true;
} else {
currentlyStreamedMessage = inMsg;
// It has a body, stream it
HandlerPublisher<HttpContent> publisher = new HandlerPublisher<HttpContent>(ctx.executor(), HttpContent.class) {
@Override
protected void cancelled() {
if (ctx.executor().inEventLoop()) {
handleCancelled(ctx, inMsg);
} else {
ctx.executor().execute(new Runnable() {
@Override
public void run() {
handleCancelled(ctx, inMsg);
}
});
}
}
@Override
protected void requestDemand() {
bodyRequested(ctx);
super.requestDemand();
}
};
ctx.channel().pipeline().addAfter(ctx.name(), ctx.name() + "-body-publisher", publisher);
ctx.fireChannelRead(createStreamedMessage(inMsg, publisher));
}
} else if (msg instanceof HttpContent) {
handleReadHttpContent(ctx, (HttpContent) msg);
}
}
private void handleCancelled(ChannelHandlerContext ctx, InT msg) {
if (currentlyStreamedMessage == msg) {
ignoreBodyRead = true;
// Need to do a read in case the subscriber ignored a read completed.
ctx.read();
}
}
private void handleReadHttpContent(ChannelHandlerContext ctx, HttpContent content) {
boolean lastHttpContent = content instanceof LastHttpContent;
if (lastHttpContent) {
logger.debug(ctx.channel(),
() -> "Received LastHttpContent " + ctx.channel() + " with ignoreBodyRead as " + ignoreBodyRead);
ctx.channel().attr(STREAMING_COMPLETE_KEY).set(true);
}
if (!ignoreBodyRead) {
if (lastHttpContent) {
if (content.content().readableBytes() > 0 ||
!((LastHttpContent) content).trailingHeaders().isEmpty()) {
// It has data or trailing headers, send them
ctx.fireChannelRead(content);
} else {
ReferenceCountUtil.release(content);
}
removeHandlerIfActive(ctx, ctx.name() + "-body-publisher");
currentlyStreamedMessage = null;
consumedInMessage(ctx);
} else {
ctx.fireChannelRead(content);
}
} else {
ReferenceCountUtil.release(content);
if (lastHttpContent) {
ignoreBodyRead = false;
if (currentlyStreamedMessage != null) {
removeHandlerIfActive(ctx, ctx.name() + "-body-publisher");
}
currentlyStreamedMessage = null;
}
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (ignoreBodyRead) {
ctx.read();
} else {
ctx.fireChannelReadComplete();
}
}
@Override
public void write(final ChannelHandlerContext ctx, Object msg, final ChannelPromise promise) throws Exception {
if (outClass.isInstance(msg)) {
Outgoing out = new Outgoing(outClass.cast(msg), promise);
receivedOutMessage(ctx);
if (outgoing.isEmpty()) {
outgoing.add(out);
flushNext(ctx);
} else {
outgoing.add(out);
}
} else if (msg instanceof LastHttpContent) {
sendLastHttpContent = false;
ctx.write(msg, promise);
} else {
ctx.write(msg, promise);
}
}
protected void unbufferedWrite(final ChannelHandlerContext ctx, final Outgoing out) {
if (out.message instanceof FullHttpMessage) {
// Forward as is
ctx.writeAndFlush(out.message, out.promise);
out.promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
executeInEventLoop(ctx, new Runnable() {
@Override
public void run() {
sentOutMessage(ctx);
outgoing.remove();
flushNext(ctx);
}
});
}
});
} else if (out.message instanceof StreamedHttpMessage) {
StreamedHttpMessage streamed = (StreamedHttpMessage) out.message;
HandlerSubscriber<HttpContent> subscriber = new HandlerSubscriber<HttpContent>(ctx.executor()) {
@Override
protected void error(Throwable error) {
out.promise.tryFailure(error);
ctx.close();
}
@Override
protected void complete() {
executeInEventLoop(ctx, new Runnable() {
@Override
public void run() {
completeBody(ctx);
}
});
}
};
sendLastHttpContent = true;
// DON'T pass the promise through, create a new promise instead.
ctx.writeAndFlush(out.message);
ctx.pipeline().addAfter(ctx.name(), ctx.name() + "-body-subscriber", subscriber);
subscribeSubscriberToStream(streamed, subscriber);
}
}
private void completeBody(final ChannelHandlerContext ctx) {
removeHandlerIfActive(ctx, ctx.name() + "-body-subscriber");
if (sendLastHttpContent) {
ChannelPromise promise = outgoing.peek().promise;
ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, promise).addListener(
new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
executeInEventLoop(ctx, new Runnable() {
@Override
public void run() {
outgoing.remove();
sentOutMessage(ctx);
flushNext(ctx);
}
});
}
}
);
} else {
outgoing.remove().promise.setSuccess();
sentOutMessage(ctx);
flushNext(ctx);
}
}
/**
* Most operations we want to do even if the channel is not active, because if it's not, then we want to encounter
* the error that occurs when that operation happens and so that it can be passed up to the user. However, removing
* handlers should only be done if the channel is active, because the error that is encountered when they aren't
* makes no sense to the user (NoSuchElementException).
*/
private void removeHandlerIfActive(ChannelHandlerContext ctx, String name) {
if (ctx.channel().isActive()) {
ctx.pipeline().remove(name);
}
}
private void flushNext(ChannelHandlerContext ctx) {
if (!outgoing.isEmpty()) {
unbufferedWrite(ctx, outgoing.element());
} else {
ctx.fireChannelWritabilityChanged();
}
}
private void executeInEventLoop(ChannelHandlerContext ctx, Runnable runnable) {
if (ctx.executor().inEventLoop()) {
runnable.run();
} else {
ctx.executor().execute(runnable);
}
}
class Outgoing {
final OutT message;
final ChannelPromise promise;
Outgoing(OutT message, ChannelPromise promise) {
this.message = message;
this.promise = promise;
}
}
}
| 1,188 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateStreamedHttpResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponse;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
final class DelegateStreamedHttpResponse extends DelegateHttpResponse implements StreamedHttpResponse {
private final Publisher<HttpContent> stream;
DelegateStreamedHttpResponse(HttpResponse response, Publisher<HttpContent> stream) {
super(response);
this.stream = stream;
}
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
stream.subscribe(subscriber);
}
}
| 1,189 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DefaultStreamedHttpResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import java.util.Objects;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A default streamed HTTP response.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public class DefaultStreamedHttpResponse extends DefaultHttpResponse implements StreamedHttpResponse {
private final Publisher<HttpContent> stream;
public DefaultStreamedHttpResponse(HttpVersion version, HttpResponseStatus status, Publisher<HttpContent> stream) {
super(version, status);
this.stream = stream;
}
public DefaultStreamedHttpResponse(HttpVersion version, HttpResponseStatus status, boolean validateHeaders,
Publisher<HttpContent> stream) {
super(version, status, validateHeaders);
this.stream = stream;
}
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
stream.subscribe(subscriber);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
DefaultStreamedHttpResponse that = (DefaultStreamedHttpResponse) o;
return Objects.equals(stream, that.stream);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (stream != null ? stream.hashCode() : 0);
return result;
}
}
| 1,190 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.internal.TypeParameterMatcher;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Publisher for a Netty Handler.
*
* This publisher supports only one subscriber.
*
* All interactions with the subscriber are done from the handlers executor, hence, they provide the same happens before
* semantics that Netty provides.
*
* The handler publishes all messages that match the type as specified by the passed in class. Any non matching messages
* are forwarded to the next handler.
*
* The publisher will signal complete if it receives a channel inactive event.
*
* The publisher will release any messages that it drops (for example, messages that are buffered when the subscriber
* cancels), but other than that, it does not release any messages. It is up to the subscriber to release messages.
*
* If the subscriber cancels, the publisher will send a close event up the channel pipeline.
*
* All errors will short circuit the buffer, and cause publisher to immediately call the subscribers onError method,
* dropping the buffer.
*
* The publisher can be subscribed to or placed in a handler chain in any order.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*/
@SdkInternalApi
public class HandlerPublisher<T> extends ChannelDuplexHandler implements Publisher<T> {
/**
* Used for buffering a completion signal.
*/
private static final Object COMPLETE = new Object() {
@Override
public String toString() {
return "COMPLETE";
}
};
private final EventExecutor executor;
private final TypeParameterMatcher matcher;
private final Queue<Object> buffer = new LinkedList<>();
/**
* Whether a subscriber has been provided. This is used to detect whether two subscribers are subscribing
* simultaneously.
*/
private final AtomicBoolean hasSubscriber = new AtomicBoolean();
private State state = HandlerPublisher.State.NO_SUBSCRIBER_OR_CONTEXT;
private volatile Subscriber<? super T> subscriber;
private ChannelHandlerContext ctx;
private long outstandingDemand = 0;
private Throwable noSubscriberError;
/**
* Create a handler publisher.
*
* The supplied executor must be the same event loop as the event loop that this handler is eventually registered
* with, if not, an exception will be thrown when the handler is registered.
*
* @param executor The executor to execute asynchronous events from the subscriber on.
* @param subscriberMessageType The type of message this publisher accepts.
*/
public HandlerPublisher(EventExecutor executor, Class<? extends T> subscriberMessageType) {
this.executor = executor;
this.matcher = TypeParameterMatcher.get(subscriberMessageType);
}
/**
* Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next
* {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
*
* @param msg The message to check.
* @return True if the message should be accepted.
*/
protected boolean acceptInboundMessage(Object msg) throws Exception {
return matcher.match(msg);
}
/**
* Override to handle when a subscriber cancels the subscription.
*
* By default, this method will simply close the channel.
*/
protected void cancelled() {
ctx.close();
}
/**
* Override to intercept when demand is requested.
*
* By default, a channel read is invoked.
*/
protected void requestDemand() {
ctx.read();
}
enum State {
/**
* Initial state. There's no subscriber, and no context.
*/
NO_SUBSCRIBER_OR_CONTEXT,
/**
* A subscriber has been provided, but no context has been provided.
*/
NO_CONTEXT,
/**
* A context has been provided, but no subscriber has been provided.
*/
NO_SUBSCRIBER,
/**
* An error has been received, but there's no subscriber to receive it.
*/
NO_SUBSCRIBER_ERROR,
/**
* There is no demand, and we have nothing buffered.
*/
IDLE,
/**
* There is no demand, and we're buffering elements.
*/
BUFFERING,
/**
* We have nothing buffered, but there is demand.
*/
DEMANDING,
/**
* The stream is complete, however there are still elements buffered for which no demand has come from the subscriber.
*/
DRAINING,
/**
* We're done, in the terminal state.
*/
DONE
}
@Override
public void subscribe(final Subscriber<? super T> subscriber) {
if (subscriber == null) {
throw new NullPointerException("Null subscriber");
}
if (!hasSubscriber.compareAndSet(false, true)) {
// Must call onSubscribe first.
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
});
subscriber.onError(new IllegalStateException("This publisher only supports one subscriber"));
} else {
executor.execute(new Runnable() {
@Override
public void run() {
provideSubscriber(subscriber);
}
});
}
}
private void provideSubscriber(Subscriber<? super T> subscriber) {
this.subscriber = subscriber;
switch (state) {
case NO_SUBSCRIBER_OR_CONTEXT:
state = HandlerPublisher.State.NO_CONTEXT;
break;
case NO_SUBSCRIBER:
if (buffer.isEmpty()) {
state = HandlerPublisher.State.IDLE;
} else {
state = HandlerPublisher.State.BUFFERING;
}
subscriber.onSubscribe(new ChannelSubscription());
break;
case DRAINING:
subscriber.onSubscribe(new ChannelSubscription());
break;
case NO_SUBSCRIBER_ERROR:
cleanup();
state = HandlerPublisher.State.DONE;
subscriber.onSubscribe(new ChannelSubscription());
subscriber.onError(noSubscriberError);
break;
default:
// Do nothing
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// If the channel is not yet registered, then it's not safe to invoke any methods on it, eg read() or close()
// So don't provide the context until it is registered.
if (ctx.channel().isRegistered()) {
provideChannelContext(ctx);
}
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
provideChannelContext(ctx);
ctx.fireChannelRegistered();
}
private void provideChannelContext(ChannelHandlerContext ctx) {
switch (state) {
case NO_SUBSCRIBER_OR_CONTEXT:
verifyRegisteredWithRightExecutor(ctx);
this.ctx = ctx;
// It's set, we don't have a subscriber
state = HandlerPublisher.State.NO_SUBSCRIBER;
break;
case NO_CONTEXT:
verifyRegisteredWithRightExecutor(ctx);
this.ctx = ctx;
state = HandlerPublisher.State.IDLE;
subscriber.onSubscribe(new ChannelSubscription());
break;
default:
// Ignore, this could be invoked twice by both handlerAdded and channelRegistered.
}
}
private void verifyRegisteredWithRightExecutor(ChannelHandlerContext ctx) {
if (!executor.inEventLoop()) {
throw new IllegalArgumentException("Channel handler MUST be registered with the same EventExecutor that it is "
+ "created with.");
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// If we subscribed before the channel was active, then our read would have been ignored.
if (state == HandlerPublisher.State.DEMANDING) {
requestDemand();
}
ctx.fireChannelActive();
}
private void receivedDemand(long demand) {
switch (state) {
case BUFFERING:
case DRAINING:
if (addDemand(demand)) {
flushBuffer();
}
break;
case DEMANDING:
addDemand(demand);
break;
case IDLE:
if (addDemand(demand)) {
// Important to change state to demanding before doing a read, in case we get a synchronous
// read back.
state = HandlerPublisher.State.DEMANDING;
requestDemand();
}
break;
default:
}
}
private boolean addDemand(long demand) {
if (demand <= 0) {
illegalDemand();
return false;
} else {
if (outstandingDemand < Long.MAX_VALUE) {
outstandingDemand += demand;
if (outstandingDemand < 0) {
outstandingDemand = Long.MAX_VALUE;
}
}
return true;
}
}
private void illegalDemand() {
cleanup();
subscriber.onError(new IllegalArgumentException("Request for 0 or negative elements in violation of Section 3.9 "
+ "of the Reactive Streams specification"));
ctx.close();
state = HandlerPublisher.State.DONE;
}
private void flushBuffer() {
while (!buffer.isEmpty() && (outstandingDemand > 0 || outstandingDemand == Long.MAX_VALUE)) {
publishMessage(buffer.remove());
}
if (buffer.isEmpty()) {
if (outstandingDemand > 0) {
if (state == HandlerPublisher.State.BUFFERING) {
state = HandlerPublisher.State.DEMANDING;
} // otherwise we're draining
requestDemand();
} else if (state == HandlerPublisher.State.BUFFERING) {
state = HandlerPublisher.State.IDLE;
}
}
}
private void receivedCancel() {
switch (state) {
case BUFFERING:
case DEMANDING:
case IDLE:
cancelled();
state = HandlerPublisher.State.DONE;
break;
case DRAINING:
state = HandlerPublisher.State.DONE;
break;
default:
// ignore
}
cleanup();
subscriber = null;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
if (acceptInboundMessage(message)) {
switch (state) {
case IDLE:
buffer.add(message);
state = HandlerPublisher.State.BUFFERING;
break;
case NO_SUBSCRIBER:
case BUFFERING:
buffer.add(message);
break;
case DEMANDING:
publishMessage(message);
break;
case DRAINING:
case DONE:
ReferenceCountUtil.release(message);
break;
case NO_CONTEXT:
case NO_SUBSCRIBER_OR_CONTEXT:
throw new IllegalStateException("Message received before added to the channel context");
default:
// Ignore
}
} else {
ctx.fireChannelRead(message);
}
}
private void publishMessage(Object message) {
if (COMPLETE.equals(message)) {
subscriber.onComplete();
state = HandlerPublisher.State.DONE;
} else {
@SuppressWarnings("unchecked")
T next = (T) message;
subscriber.onNext(next);
if (outstandingDemand < Long.MAX_VALUE) {
outstandingDemand--;
if (outstandingDemand == 0 && state != HandlerPublisher.State.DRAINING) {
if (buffer.isEmpty()) {
state = HandlerPublisher.State.IDLE;
} else {
state = HandlerPublisher.State.BUFFERING;
}
}
}
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (state == HandlerPublisher.State.DEMANDING) {
requestDemand();
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
complete();
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
complete();
}
private void complete() {
switch (state) {
case NO_SUBSCRIBER:
case BUFFERING:
buffer.add(COMPLETE);
state = HandlerPublisher.State.DRAINING;
break;
case DEMANDING:
case IDLE:
subscriber.onComplete();
state = HandlerPublisher.State.DONE;
break;
case NO_SUBSCRIBER_ERROR:
// Ignore, we're already going to complete the stream with an error
// when the subscriber subscribes.
break;
default:
// Ignore
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
switch (state) {
case NO_SUBSCRIBER:
noSubscriberError = cause;
state = HandlerPublisher.State.NO_SUBSCRIBER_ERROR;
cleanup();
break;
case BUFFERING:
case DEMANDING:
case IDLE:
case DRAINING:
state = HandlerPublisher.State.DONE;
cleanup();
subscriber.onError(cause);
break;
default:
// Ignore
}
}
/**
* Release all elements from the buffer.
*/
private void cleanup() {
while (!buffer.isEmpty()) {
ReferenceCountUtil.release(buffer.remove());
}
}
private class ChannelSubscription implements Subscription {
@Override
public void request(final long demand) {
executor.execute(new Runnable() {
@Override
public void run() {
receivedDemand(demand);
}
});
}
@Override
public void cancel() {
executor.execute(new Runnable() {
@Override
public void run() {
receivedCancel();
}
});
}
}
}
| 1,191 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
class DelegateHttpResponse extends DelegateHttpMessage implements HttpResponse {
protected final HttpResponse response;
DelegateHttpResponse(HttpResponse response) {
super(response);
this.response = response;
}
@Override
public HttpResponse setStatus(HttpResponseStatus status) {
response.setStatus(status);
return this;
}
@Override
@Deprecated
public HttpResponseStatus getStatus() {
return response.status();
}
@Override
public HttpResponseStatus status() {
return response.status();
}
@Override
public HttpResponse setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
}
| 1,192 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpMessage.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMessage;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Combines {@link HttpMessage} and {@link Publisher} into one
* message. So it represents an http message with a stream of {@link HttpContent}
* messages that can be subscribed to.
*
* Note that receivers of this message <em>must</em> consume the publisher,
* since the publisher will exert back pressure up the stream if not consumed.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public interface StreamedHttpMessage extends HttpMessage, Publisher<HttpContent> {
}
| 1,193 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpMessage.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpVersion;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
class DelegateHttpMessage implements HttpMessage {
protected final HttpMessage message;
DelegateHttpMessage(HttpMessage message) {
this.message = message;
}
@Override
@Deprecated
public HttpVersion getProtocolVersion() {
return message.protocolVersion();
}
@Override
public HttpVersion protocolVersion() {
return message.protocolVersion();
}
@Override
public HttpMessage setProtocolVersion(HttpVersion version) {
message.setProtocolVersion(version);
return this;
}
@Override
public HttpHeaders headers() {
return message.headers();
}
@Override
@Deprecated
public DecoderResult getDecoderResult() {
return message.decoderResult();
}
@Override
public DecoderResult decoderResult() {
return message.decoderResult();
}
@Override
public void setDecoderResult(DecoderResult result) {
message.setDecoderResult(result);
}
@Override
public String toString() {
return this.getClass().getName() + "(" + message.toString() + ")";
}
}
| 1,194 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateStreamedHttpRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
final class DelegateStreamedHttpRequest extends DelegateHttpRequest implements StreamedHttpRequest {
private final Publisher<HttpContent> stream;
DelegateStreamedHttpRequest(HttpRequest request, Publisher<HttpContent> stream) {
super(request);
this.stream = stream;
}
@Override
public void subscribe(Subscriber<? super HttpContent> subscriber) {
stream.subscribe(subscriber);
}
}
| 1,195 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/EmptyHttpRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
class EmptyHttpRequest extends DelegateHttpRequest implements FullHttpRequest {
EmptyHttpRequest(HttpRequest request) {
super(request);
}
@Override
public FullHttpRequest setUri(String uri) {
super.setUri(uri);
return this;
}
@Override
public FullHttpRequest setMethod(HttpMethod method) {
super.setMethod(method);
return this;
}
@Override
public FullHttpRequest setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public FullHttpRequest copy() {
if (request instanceof FullHttpRequest) {
return new EmptyHttpRequest(((FullHttpRequest) request).copy());
} else {
DefaultHttpRequest copy = new DefaultHttpRequest(protocolVersion(), method(), uri());
copy.headers().set(headers());
return new EmptyHttpRequest(copy);
}
}
@Override
public FullHttpRequest retain(int increment) {
ReferenceCountUtil.retain(message, increment);
return this;
}
@Override
public FullHttpRequest retain() {
ReferenceCountUtil.retain(message);
return this;
}
@Override
public FullHttpRequest touch() {
if (request instanceof FullHttpRequest) {
return ((FullHttpRequest) request).touch();
} else {
return this;
}
}
@Override
public FullHttpRequest touch(Object o) {
if (request instanceof FullHttpRequest) {
return ((FullHttpRequest) request).touch(o);
} else {
return this;
}
}
@Override
public HttpHeaders trailingHeaders() {
return new DefaultHttpHeaders();
}
@Override
public FullHttpRequest duplicate() {
if (request instanceof FullHttpRequest) {
return ((FullHttpRequest) request).duplicate();
} else {
return this;
}
}
@Override
public FullHttpRequest retainedDuplicate() {
if (request instanceof FullHttpRequest) {
return ((FullHttpRequest) request).retainedDuplicate();
} else {
return this;
}
}
@Override
public FullHttpRequest replace(ByteBuf byteBuf) {
if (message instanceof FullHttpRequest) {
return ((FullHttpRequest) request).replace(byteBuf);
} else {
return this;
}
}
@Override
public ByteBuf content() {
return Unpooled.EMPTY_BUFFER;
}
@Override
public int refCnt() {
if (message instanceof ReferenceCounted) {
return ((ReferenceCounted) message).refCnt();
} else {
return 1;
}
}
@Override
public boolean release() {
return ReferenceCountUtil.release(message);
}
@Override
public boolean release(int decrement) {
return ReferenceCountUtil.release(message, decrement);
}
}
| 1,196 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/CancelledSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.http.nio.netty.internal.nrs;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A cancelled subscriber.
*
* This class contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
@SdkInternalApi
public final class CancelledSubscriber<T> implements Subscriber<T> {
@Override
public void onSubscribe(Subscription subscription) {
if (subscription == null) {
throw new NullPointerException("Null subscription");
} else {
subscription.cancel();
}
}
@Override
public void onNext(T t) {
}
@Override
public void onError(Throwable error) {
if (error == null) {
throw new NullPointerException("Null error published");
}
}
@Override
public void onComplete() {
}
}
| 1,197 |
0 | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal | Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/package-info.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* This package contains source imported from https://github.com/playframework/netty-reactive-streams,
* licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here:
* https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt
*
* All original source licensed under the Apache License 2.0 by playframework. All modifications are
* licensed under the Apache License 2.0 by Amazon Web Services.
*/
package software.amazon.awssdk.http.nio.netty.internal.nrs;
| 1,198 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/AwsRequestOverrideConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.awscore;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
public class AwsRequestOverrideConfigurationTest {
@Test
public void testCredentialsProviderWorksWithBothOldAndNewInterfaceTypes() {
AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
AwsBasicCredentials.create("akid","skid"));
AwsRequestOverrideConfiguration configuration1 = AwsRequestOverrideConfiguration
.builder().credentialsProvider(credentialsProvider).build();
AwsRequestOverrideConfiguration configuration2 = AwsRequestOverrideConfiguration
.builder().credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider).build();
assertCredentialsEqual(configuration1.credentialsProvider().get(), configuration1.credentialsIdentityProvider().get());
assertCredentialsEqual(configuration2.credentialsProvider().get(), configuration2.credentialsIdentityProvider().get());
assertCredentialsEqual(configuration1.credentialsProvider().get(), configuration2.credentialsIdentityProvider().get());
assertCredentialsEqual(configuration2.credentialsProvider().get(), configuration1.credentialsIdentityProvider().get());
}
private void assertCredentialsEqual(AwsCredentialsProvider credentialsProvider,
IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) {
AwsCredentials creds1 = credentialsProvider.resolveCredentials();
AwsCredentialsIdentity creds2 = identityProvider.resolveIdentity().join();
assertThat(creds1.accessKeyId()).isEqualTo(creds2.accessKeyId());
assertThat(creds1.secretAccessKey()).isEqualTo(creds2.secretAccessKey());
}
}
| 1,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.