index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__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
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientNonBlockingDnsTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.util.Collections.singletonMap; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.StringUtils.reverse; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.assertCanReceiveBasicRequest; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createProvider; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createRequest; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.makeSimpleRequest; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.assertj.core.api.Condition; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.utils.AttributeMap; @RunWith(MockitoJUnitRunner.class) public class NettyNioAsyncHttpClientNonBlockingDnsTest { private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener(); private static final SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder() .useNonBlockingDnsResolver(true) .buildWithDefaults( AttributeMap.builder() .put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true) .build()); @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig() .dynamicPort() .dynamicHttpsPort() .networkTrafficListener(wiremockTrafficListener)); @Before public void methodSetup() { wiremockTrafficListener.reset(); } @AfterClass public static void tearDown() throws Exception { client.close(); } @Test public void canSendContentAndGetThatContentBackNonBlockingDns() throws Exception { String body = randomAlphabetic(50); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(body)) .willReturn(aResponse().withBody(reverse(body)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpRequest request = createRequest(uri, "/echo", body, SdkHttpMethod.POST, singletonMap("reversed", "true")); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(body)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); verify(1, postRequestedFor(urlEqualTo("/echo?reversed=true"))); assertThat(recorder.fullResponseAsString()).isEqualTo(reverse(body)); } @Test public void defaultThreadFactoryUsesHelpfulName() throws Exception { // Make a request to ensure a thread is primed makeSimpleRequest(client, mockServer); String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+"; assertThat(Thread.getAllStackTraces().keySet()) .areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern), "Matches default thread pattern: `%s`", expectedPattern)); } @Test public void canMakeBasicRequestOverHttp() throws Exception { String smallBody = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(client, uri, smallBody); } @Test public void canMakeBasicRequestOverHttps() throws Exception { String smallBody = randomAlphabetic(10); URI uri = URI.create("https://localhost:" + mockServer.httpsPort()); assertCanReceiveBasicRequest(client, uri, smallBody); } @Test public void canHandleLargerPayloadsOverHttp() throws Exception { String largishBody = randomAlphabetic(25000); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(client, uri, largishBody); } @Test public void canHandleLargerPayloadsOverHttps() throws Exception { String largishBody = randomAlphabetic(25000); URI uri = URI.create("https://localhost:" + mockServer.httpsPort()); assertCanReceiveBasicRequest(client, uri, largishBody); } @Test public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws InterruptedException, ExecutionException, TimeoutException, IOException { final String content = randomAlphabetic(32); final String streamContent = content + reverse(content); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(content)) .willReturn(aResponse().withBody(reverse(content)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true")); request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build(); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); // HTTP servers will stop processing the request as soon as it reads // bytes equal to 'Content-Length' so we need to inspect the raw // traffic to ensure that there wasn't anything after that. assertThat(wiremockTrafficListener.requests().toString()).endsWith(content); } }
1,300
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientSpiVerificationTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.Rule; import org.junit.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.EmptyPublisher; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; 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.utils.AttributeMap; /** * Verify the behavior of {@link NettyNioAsyncHttpClient} is consistent with the SPI. */ public class NettyNioAsyncHttpClientSpiVerificationTest { @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig() .dynamicPort() .dynamicHttpsPort()); private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder().buildWithDefaults(mapWithTrustAllCerts()); @AfterClass public static void tearDown() throws Exception { client.close(); } // CONNECTION_RESET_BY_PEER does not work on JDK 11. See https://github.com/tomakehurst/wiremock/issues/1009 @Test public void signalsErrorViaOnErrorAndFuture() throws Exception { stubFor(any(urlEqualTo("/")).willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE))); CompletableFuture<Boolean> errorSignaled = new CompletableFuture<>(); SdkAsyncHttpResponseHandler handler = new TestResponseHandler() { @Override public void onError(Throwable error) { errorSignaled.complete(true); } }; SdkHttpRequest request = createRequest(URI.create("http://localhost:" + mockServer.port())); CompletableFuture<Void> executeFuture = client.execute(AsyncExecuteRequest.builder() .request(request) .responseHandler(handler) .requestContentPublisher(new EmptyPublisher()) .build()); assertThat(errorSignaled.get(1, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(executeFuture::join).hasCauseInstanceOf(IOException.class); } @Test public void callsOnStreamForEmptyResponseContent() throws Exception { stubFor(any(urlEqualTo("/")).willReturn(aResponse().withStatus(204).withHeader("foo", "bar"))); CompletableFuture<Boolean> streamReceived = new CompletableFuture<>(); SdkAsyncHttpResponseHandler handler = new TestResponseHandler() { @Override public void onStream(Publisher<ByteBuffer> stream) { super.onStream(stream); streamReceived.complete(true); } }; SdkHttpRequest request = createRequest(URI.create("http://localhost:" + mockServer.port())); client.execute(AsyncExecuteRequest.builder() .request(request) .responseHandler(handler) .requestContentPublisher(new EmptyPublisher()) .build()); assertThat(streamReceived.get(1, TimeUnit.SECONDS)).isTrue(); } private static AttributeMap mapWithTrustAllCerts() { return AttributeMap.builder() .put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true) .build(); } private SdkHttpFullRequest createRequest(URI endpoint) { return createRequest(endpoint, "/", null, SdkHttpMethod.GET, emptyMap()); } private SdkHttpFullRequest createRequest(URI endpoint, String resourcePath, String body, SdkHttpMethod method, Map<String, String> params) { String contentLength = body == null ? null : String.valueOf(body.getBytes(UTF_8).length); return SdkHttpFullRequest.builder() .uri(endpoint) .method(method) .encodedPath(resourcePath) .applyMutation(b -> params.forEach(b::putRawQueryParameter)) .applyMutation(b -> { b.putHeader("Host", endpoint.getHost()); if (contentLength != null) { b.putHeader("Content-Length", contentLength); } }).build(); } private static class TestResponseHandler implements SdkAsyncHttpResponseHandler { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { stream.subscribe(new DrainingSubscriber<>()); } @Override public void onError(Throwable error) { } } private static class DrainingSubscriber<T> implements Subscriber<T> { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; this.subscription.request(Long.MAX_VALUE); } @Override public void onNext(T t) { this.subscription.request(1); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } } }
1,301
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientWireMockTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomAscii; import static org.apache.commons.lang3.StringUtils.reverse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.assertCanReceiveBasicRequest; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createProvider; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.createRequest; import static software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClientTestUtils.makeSimpleRequest; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit.WireMockRule; import io.netty.channel.Channel; import io.netty.channel.ChannelFactory; import io.netty.channel.ChannelFuture; 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 io.netty.handler.ssl.SslProvider; import io.netty.util.AttributeKey; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.net.ssl.TrustManagerFactory; import org.assertj.core.api.Condition; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.HttpTestUtils; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; 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.nio.netty.internal.NettyConfiguration; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPoolMap; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.utils.AttributeMap; @RunWith(MockitoJUnitRunner.class) public class NettyNioAsyncHttpClientWireMockTest { private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener(); @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig() .dynamicPort() .dynamicHttpsPort() .networkTrafficListener(wiremockTrafficListener)); private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder().buildWithDefaults(mapWithTrustAllCerts()); @Before public void methodSetup() { wiremockTrafficListener.reset(); } @AfterClass public static void tearDown() throws Exception { client.close(); } @Test public void defaultConnectionIdleTimeout() { try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder().build()) { assertThat(client.configuration().idleTimeoutMillis()).isEqualTo(5000); } } @Test public void defaultTlsHandshakeTimeout() { try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.create()) { assertThat(client.configuration().tlsHandshakeTimeout().toMillis()).isEqualTo(5000); } } @Test public void noTlsTimeout_hasConnectTimeout_shouldResolveToConnectTimeout() { Duration connectTimeout = Duration.ofSeconds(1); try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionTimeout(connectTimeout) .build()) { assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(connectTimeout); } Duration timeoutOverride = Duration.ofSeconds(2); try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionTimeout(timeoutOverride) .build()) { assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(timeoutOverride); } } @Test public void tlsTimeoutConfigured_shouldHonor() { Duration connectTimeout = Duration.ofSeconds(1); Duration tlsTimeout = Duration.ofSeconds(3); try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .tlsNegotiationTimeout(tlsTimeout) .connectionTimeout(connectTimeout) .build()) { assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(tlsTimeout); } try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionTimeout(connectTimeout) .tlsNegotiationTimeout(tlsTimeout) .build()) { assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(tlsTimeout); } } @Test public void overrideConnectionIdleTimeout_shouldHonor() { try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofMillis(1000)) .build()) { assertThat(client.configuration().idleTimeoutMillis()).isEqualTo(1000); } } @Test public void invalidMaxPendingConnectionAcquireConfig_shouldPropagateException() { try (SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(1) .maxPendingConnectionAcquires(0) .build()) { assertThatThrownBy(() -> makeSimpleRequest(customClient, mockServer)).hasMessageContaining("java.lang" + ".IllegalArgumentException: maxPendingAcquires: 0 (expected: >= 1)"); } } @Test public void customFactoryIsUsed() throws Exception { ThreadFactory threadFactory = spy(new CustomThreadFactory()); SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .eventLoopGroupBuilder(SdkEventLoopGroup.builder() .threadFactory(threadFactory)) .build(); makeSimpleRequest(customClient, mockServer); customClient.close(); Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any()); } @Test public void openSslBeingUsed() throws Exception { try (SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .sslProvider(SslProvider.OPENSSL) .build()) { makeSimpleRequest(customClient, mockServer); } } @Test public void defaultJdkSslProvider() throws Exception { try (SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .sslProvider(SslProvider.JDK) .build()) { makeSimpleRequest(customClient, mockServer); customClient.close(); } } @Test public void defaultThreadFactoryUsesHelpfulName() throws Exception { // Make a request to ensure a thread is primed makeSimpleRequest(client, mockServer); String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+"; assertThat(Thread.getAllStackTraces().keySet()) .areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern), "Matches default thread pattern: `%s`", expectedPattern)); } @Test public void customThreadCountIsRespected() throws Exception { final int threadCount = 10; ThreadFactory threadFactory = spy(new CustomThreadFactory()); SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .eventLoopGroupBuilder(SdkEventLoopGroup.builder() .threadFactory(threadFactory) .numberOfThreads(threadCount)) .build(); // Have to make enough requests to prime the threads for (int i = 0; i < threadCount + 1; i++) { makeSimpleRequest(customClient, mockServer); } customClient.close(); Mockito.verify(threadFactory, times(threadCount)).newThread(Mockito.any()); } @Test public void customEventLoopGroup_NotClosedWhenClientIsClosed() throws Exception { ThreadFactory threadFactory = spy(new CustomThreadFactory()); // Cannot use DefaultEventLoopGroupFactory because the concrete // implementation it creates is platform-dependent and could be a final // (i.e. non-spyable) class. EventLoopGroup eventLoopGroup = spy(new NioEventLoopGroup(0, threadFactory)); SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .eventLoopGroup(SdkEventLoopGroup.create(eventLoopGroup, NioSocketChannel::new)) .build(); makeSimpleRequest(customClient, mockServer); customClient.close(); Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any()); Mockito.verify(eventLoopGroup, never()).shutdownGracefully(); } @Test public void customChannelFactoryIsUsed() throws Exception { ChannelFactory channelFactory = mock(ChannelFactory.class); when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> new NioSocketChannel()); EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(); SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .eventLoopGroup(SdkEventLoopGroup.create(customEventLoopGroup, channelFactory)) .build(); makeSimpleRequest(customClient, mockServer); customClient.close(); Mockito.verify(channelFactory, atLeastOnce()).newChannel(); assertThat(customEventLoopGroup.isShuttingDown()).isFalse(); customEventLoopGroup.shutdownGracefully().awaitUninterruptibly(); } @Test public void closeClient_shouldCloseUnderlyingResources() { SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.builder().build(); SdkChannelPool channelPool = mock(SdkChannelPool.class); SdkChannelPoolMap<URI, SdkChannelPool> sdkChannelPoolMap = new SdkChannelPoolMap<URI, SdkChannelPool>() { @Override protected SdkChannelPool newPool(URI key) { return channelPool; } }; sdkChannelPoolMap.get(URI.create("http://blah")); NettyConfiguration nettyConfiguration = new NettyConfiguration(AttributeMap.empty()); SdkAsyncHttpClient customerClient = new NettyNioAsyncHttpClient(eventLoopGroup, sdkChannelPoolMap, nettyConfiguration); customerClient.close(); assertThat(eventLoopGroup.eventLoopGroup().isShuttingDown()).isTrue(); assertThat(eventLoopGroup.eventLoopGroup().isTerminated()).isTrue(); assertThat(sdkChannelPoolMap).isEmpty(); Mockito.verify(channelPool).close(); } @Test public void responseConnectionReused_shouldReleaseChannel() throws Exception { ChannelFactory channelFactory = mock(ChannelFactory.class); EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1); NioSocketChannel channel = new NioSocketChannel(); when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel); SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory); NettyNioAsyncHttpClient customClient = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .eventLoopGroup(eventLoopGroup) .maxConcurrency(1) .build(); makeSimpleRequest(customClient, mockServer); verifyChannelRelease(channel); assertThat(channel.isShutdown()).isFalse(); customClient.close(); eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly(); } @Test public void connectionInactive_shouldReleaseChannel() throws Exception { ChannelFactory channelFactory = mock(ChannelFactory.class); EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1); NioSocketChannel channel = new NioSocketChannel(); when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel); SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory); NettyNioAsyncHttpClient customClient = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .eventLoopGroup(eventLoopGroup) .maxConcurrency(1) .build(); String body = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body) .withStatus(500) .withFault(Fault.RANDOM_DATA_THEN_CLOSE))); customClient.execute(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider("")) .responseHandler(recorder).build()); verifyChannelRelease(channel); assertThat(channel.isShutdown()).isTrue(); customClient.close(); eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly(); } @Test public void responseConnectionClosed_shouldCloseAndReleaseChannel() throws Exception { ChannelFactory channelFactory = mock(ChannelFactory.class); EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1); NioSocketChannel channel = new NioSocketChannel(); when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory); NettyNioAsyncHttpClient customClient = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .eventLoopGroup(eventLoopGroup) .maxConcurrency(1) .build(); String body = randomAlphabetic(10); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body) .withStatus(500) .withHeader("Connection", "close") )); customClient.execute(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider("")) .responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); verifyChannelRelease(channel); assertThat(channel.isShutdown()).isTrue(); customClient.close(); eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly(); } @Test public void builderUsesProvidedTrustManagersProvider() throws Exception { WireMockServer selfSignedServer = HttpTestUtils.createSelfSignedServer(); TrustManagerFactory managerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); managerFactory.init(HttpTestUtils.getSelfSignedKeyStore()); try (SdkAsyncHttpClient netty = NettyNioAsyncHttpClient.builder() .tlsTrustManagersProvider(managerFactory::getTrustManagers) .build()) { selfSignedServer.start(); URI uri = URI.create("https://localhost:" + selfSignedServer.httpsPort()); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); netty.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); } finally { selfSignedServer.stop(); } } @Test public void canMakeBasicRequestOverHttp() throws Exception { String smallBody = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(client, uri, smallBody); } @Test public void canMakeBasicRequestOverHttps() throws Exception { String smallBody = randomAlphabetic(10); URI uri = URI.create("https://localhost:" + mockServer.httpsPort()); assertCanReceiveBasicRequest(client, uri, smallBody); } @Test public void canHandleLargerPayloadsOverHttp() throws Exception { String largishBody = randomAlphabetic(25000); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(client, uri, largishBody); } @Test public void canHandleLargerPayloadsOverHttps() throws Exception { String largishBody = randomAlphabetic(25000); URI uri = URI.create("https://localhost:" + mockServer.httpsPort()); assertCanReceiveBasicRequest(client, uri, largishBody); } @Test public void canSendContentAndGetThatContentBack() throws Exception { String body = randomAlphabetic(50); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(body)) .willReturn(aResponse().withBody(reverse(body)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpRequest request = createRequest(uri, "/echo", body, SdkHttpMethod.POST, singletonMap("reversed", "true")); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(body)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); verify(1, postRequestedFor(urlEqualTo("/echo?reversed=true"))); assertThat(recorder.fullResponseAsString()).isEqualTo(reverse(body)); } @Test public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws InterruptedException, ExecutionException, TimeoutException, IOException { final String content = randomAlphabetic(32); final String streamContent = content + reverse(content); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(content)) .willReturn(aResponse().withBody(reverse(content)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true")); request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build(); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); // HTTP servers will stop processing the request as soon as it reads // bytes equal to 'Content-Length' so we need to inspect the raw // traffic to ensure that there wasn't anything after that. assertThat(wiremockTrafficListener.requests().toString()).endsWith(content); } @Test public void closeMethodClosesOpenedChannels() throws InterruptedException, TimeoutException, ExecutionException { String body = randomAlphabetic(10); URI uri = URI.create("https://localhost:" + mockServer.httpsPort()); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body))); SdkHttpFullRequest request = createRequest(uri, "/", body, SdkHttpMethod.POST, Collections.emptyMap()); RecordingResponseHandler recorder = new RecordingResponseHandler(); CompletableFuture<Boolean> channelClosedFuture = new CompletableFuture<>(); ChannelFactory<NioSocketChannel> channelFactory = new ChannelFactory<NioSocketChannel>() { @Override public NioSocketChannel newChannel() { return new NioSocketChannel() { @Override public ChannelFuture close() { ChannelFuture cf = super.close(); channelClosedFuture.complete(true); return cf; } }; } }; SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .eventLoopGroup(new SdkEventLoopGroup(new NioEventLoopGroup(1), channelFactory)) .buildWithDefaults(mapWithTrustAllCerts()); try { customClient.execute(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider(body)) .responseHandler(recorder).build()) .join(); } finally { customClient.close(); } assertThat(channelClosedFuture.get(5, TimeUnit.SECONDS)).isTrue(); } @Test public void execute_requestByteBufferWithNonZeroPosition_shouldHonor() throws Exception { String body = randomAlphabetic(70); byte[] content = randomAscii(100).getBytes(); ByteBuffer requestContent = ByteBuffer.wrap(content); requestContent.position(95); String expected = new String(content, 95, 5); URI uri = URI.create("http://localhost:" + mockServer.port()); stubFor(post(urlPathEqualTo("/")) .withRequestBody(equalTo(expected)).willReturn(aResponse().withBody(body))); SdkHttpRequest request = createRequest(uri, "/", expected, SdkHttpMethod.POST, emptyMap()); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(new SimpleHttpContentPublisher(requestContent)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); verify(postRequestedFor(urlPathEqualTo("/")).withRequestBody(equalTo(expected))); } // Needs to be a non-anon class in order to spy public static class CustomThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(r); } } @Test public void testExceptionMessageChanged_WhenPendingAcquireQueueIsFull() throws Exception { String expectedErrorMsg = "Maximum pending connection acquisitions exceeded."; SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(1) .maxPendingConnectionAcquires(1) .build(); List<CompletableFuture<Void>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000).completeFuture); } assertThatThrownBy(() -> CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join()) .hasMessageContaining(expectedErrorMsg); customClient.close(); } @Test public void testExceptionMessageChanged_WhenConnectionTimeoutErrorEncountered() throws Exception { String expectedErrorMsg = "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."; SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(1) .connectionTimeout(Duration.ofMillis(1)) .connectionAcquisitionTimeout(Duration.ofMillis(1)) .build(); List<CompletableFuture<Void>> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000).completeFuture); } assertThatThrownBy(() -> CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join()) .hasMessageContaining(expectedErrorMsg); customClient.close(); } @Test public void createNettyClient_ReadWriteTimeoutCanBeZero() throws Exception { SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .readTimeout(Duration.ZERO) .writeTimeout(Duration.ZERO) .build(); makeSimpleRequest(customClient, mockServer); customClient.close(); } @Test public void createNettyClient_tlsNegotiationTimeoutNotPositive_shouldThrowException() throws Exception { assertThatThrownBy(() -> NettyNioAsyncHttpClient.builder() .tlsNegotiationTimeout(Duration.ZERO) .build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be positive"); assertThatThrownBy(() -> NettyNioAsyncHttpClient.builder() .tlsNegotiationTimeout(Duration.ofSeconds(-1)) .build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be positive"); } @Test public void metricsAreCollectedWhenMaxPendingConnectionAcquisitionsAreExceeded() throws Exception { SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(1) .maxPendingConnectionAcquires(1) .build(); List<RecordingResponseHandler> handlers = new ArrayList<>(); for (int i = 0; i < 10; i++) { handlers.add(makeSimpleRequestAndReturnResponseHandler(customClient, 1000)); } for (RecordingResponseHandler handler : handlers) { try { handler.executionFuture.join(); } catch (Exception e) { // Ignored. } MetricCollection metrics = handler.collector.collect(); assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio"); assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(1); assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).allSatisfy(a -> assertThat(a).isBetween(0, 9)); assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).allSatisfy(a -> assertThat(a).isBetween(0, 1)); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).allSatisfy(a -> assertThat(a).isBetween(0, 1)); } customClient.close(); } @Test public void metricsAreCollectedForSuccessfulCalls() throws Exception { SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(10) .build(); RecordingResponseHandler handler = makeSimpleRequestAndReturnResponseHandler(customClient); handler.executionFuture.get(10, TimeUnit.SECONDS); Thread.sleep(5_000); MetricCollection metrics = handler.collector.collect(); assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio"); assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10); assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isBetween(0, 1); assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1); customClient.close(); } @Test public void metricsAreCollectedForClosedClientCalls() throws Exception { SdkAsyncHttpClient customClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(10) .build(); customClient.close(); RecordingResponseHandler handler = makeSimpleRequestAndReturnResponseHandler(customClient); try { handler.executionFuture.get(10, TimeUnit.SECONDS); } catch (Exception e) { // Expected } MetricCollection metrics = handler.collector.collect(); assertThat(metrics.metricValues(HttpMetric.HTTP_CLIENT_NAME)).containsExactly("NettyNio"); assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(10); assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(0); assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(0); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1); } private void verifyChannelRelease(Channel channel) throws InterruptedException { Thread.sleep(1000); assertThat(channel.attr(AttributeKey.valueOf("channelPool")).get()).isNull(); } private RecordingResponseHandler makeSimpleRequestAndReturnResponseHandler(SdkAsyncHttpClient client) throws Exception { return makeSimpleRequestAndReturnResponseHandler(client, null); } private RecordingResponseHandler makeSimpleRequestAndReturnResponseHandler(SdkAsyncHttpClient client, Integer delayInMillis) throws Exception { String body = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body).withFixedDelay(delayInMillis))); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); recorder.executionFuture = client.execute(AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(createProvider("")) .responseHandler(recorder) .metricCollector(recorder.collector) .build()); return recorder; } private static AttributeMap mapWithTrustAllCerts() { return AttributeMap.builder() .put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true) .build(); } }
1,302
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/RecordingNetworkTrafficListener.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 com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; /** * Simple implementation of {@link WiremockNetworkTrafficListener} to record all requests received as a string for later * verification. */ public class RecordingNetworkTrafficListener implements WiremockNetworkTrafficListener { private final StringBuilder requests = new StringBuilder(); @Override public void opened(Socket socket) { } @Override public void incoming(Socket socket, ByteBuffer byteBuffer) { requests.append(StandardCharsets.UTF_8.decode(byteBuffer)); } @Override public void outgoing(Socket socket, ByteBuffer byteBuffer) { } @Override public void closed(Socket socket) { } public void reset() { requests.setLength(0); } public StringBuilder requests() { return requests; } }
1,303
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ProxyWireMockTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import java.io.IOException; import java.util.concurrent.CompletionException; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.http.EmptyPublisher; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; /** * Tests for HTTP proxy functionality in the Netty client. */ public class ProxyWireMockTest { private static SdkAsyncHttpClient client; private static ProxyConfiguration proxyCfg; private static WireMockServer mockServer = new WireMockServer(new WireMockConfiguration() .dynamicPort() .dynamicHttpsPort()); private static WireMockServer mockProxy = new WireMockServer(new WireMockConfiguration() .dynamicPort() .dynamicHttpsPort()); @BeforeClass public static void setup() { mockProxy.start(); mockServer.start(); mockServer.stubFor(get(urlPathEqualTo("/")).willReturn(aResponse().withStatus(200).withBody("hello"))); proxyCfg = ProxyConfiguration.builder() .host("localhost") .port(mockProxy.port()) .build(); } @AfterClass public static void teardown() { mockServer.stop(); mockProxy.stop(); } @After public void methodTeardown() { if (client != null) { client.close(); } client = null; } @Test(expected = IOException.class) public void proxyConfigured_attemptsToConnect() throws Throwable { AsyncExecuteRequest req = AsyncExecuteRequest.builder() .request(testSdkRequest()) .responseHandler(mock(SdkAsyncHttpResponseHandler.class)) .build(); client = NettyNioAsyncHttpClient.builder() .proxyConfiguration(proxyCfg) .build(); try { client.execute(req).join(); } catch (CompletionException e) { Throwable cause = e.getCause(); // WireMock doesn't allow for mocking the CONNECT method so it will just return a 404, causing the client // to throw an exception. assertThat(e.getCause().getMessage()).isEqualTo("Could not connect to proxy"); throw cause; } } @Test public void proxyConfigured_hostInNonProxySet_doesNotConnect() { RecordingResponseHandler responseHandler = new RecordingResponseHandler(); AsyncExecuteRequest req = AsyncExecuteRequest.builder() .request(testSdkRequest()) .responseHandler(responseHandler) .requestContentPublisher(new EmptyPublisher()) .build(); ProxyConfiguration cfg = proxyCfg.toBuilder() .nonProxyHosts(Stream.of("localhost").collect(Collectors.toSet())) .build(); client = NettyNioAsyncHttpClient.builder() .proxyConfiguration(cfg) .build(); client.execute(req).join(); responseHandler.completeFuture.join(); assertThat(responseHandler.fullResponseAsString()).isEqualTo("hello"); } @Test public void proxyConfigured_hostInNonProxySet_nonBlockingDns_doesNotConnect() { RecordingResponseHandler responseHandler = new RecordingResponseHandler(); AsyncExecuteRequest req = AsyncExecuteRequest.builder() .request(testSdkRequest()) .responseHandler(responseHandler) .requestContentPublisher(new EmptyPublisher()) .build(); ProxyConfiguration cfg = proxyCfg.toBuilder() .nonProxyHosts(Stream.of("localhost").collect(Collectors.toSet())) .build(); client = NettyNioAsyncHttpClient.builder() .proxyConfiguration(cfg) .useNonBlockingDnsResolver(true) .build(); client.execute(req).join(); responseHandler.completeFuture.join(); assertThat(responseHandler.fullResponseAsString()).isEqualTo("hello"); } private SdkHttpFullRequest testSdkRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("http") .host("localhost") .port(mockServer.port()) .putHeader("host", "localhost") .build(); } }
1,304
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/Http2ConfigurationTest.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 org.assertj.core.api.Assertions.assertThat; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class Http2ConfigurationTest { @Rule public ExpectedException expected = ExpectedException.none(); @Test public void builder_returnsInstance() { assertThat(Http2Configuration.builder()).isNotNull(); } @Test public void build_buildsCorrectConfig() { long maxStreams = 1; int initialWindowSize = 2; Http2Configuration config = Http2Configuration.builder() .maxStreams(maxStreams) .initialWindowSize(initialWindowSize) .build(); assertThat(config.maxStreams()).isEqualTo(maxStreams); assertThat(config.initialWindowSize()).isEqualTo(initialWindowSize); } @Test public void builder_toBuilder_roundTrip() { Http2Configuration config1 = Http2Configuration.builder() .maxStreams(7L) .initialWindowSize(42) .build(); Http2Configuration config2 = config1.toBuilder().build(); assertThat(config1).isEqualTo(config2); } @Test public void builder_maxStream_nullValue_doesNotThrow() { Http2Configuration.builder().maxStreams(null); } @Test public void builder_maxStream_negative_throws() { expected.expect(IllegalArgumentException.class); Http2Configuration.builder().maxStreams(-1L); } @Test public void builder_maxStream_0_throws() { expected.expect(IllegalArgumentException.class); Http2Configuration.builder().maxStreams(0L); } @Test public void builder_initialWindowSize_nullValue_doesNotThrow() { Http2Configuration.builder().initialWindowSize(null); } @Test public void builder_initialWindowSize_negative_throws() { expected.expect(IllegalArgumentException.class); Http2Configuration.builder().initialWindowSize(-1); } @Test public void builder_initialWindowSize_0_throws() { expected.expect(IllegalArgumentException.class); Http2Configuration.builder().initialWindowSize(0); } }
1,305
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/SdkTestHttpContentPublisher.java
package software.amazon.awssdk.http.nio.netty; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; public class SdkTestHttpContentPublisher implements SdkHttpContentPublisher { private final byte[] body; private final AtomicReference<Subscriber<? super ByteBuffer>> subscriber = new AtomicReference<>(null); private final AtomicBoolean complete = new AtomicBoolean(false); private final AtomicInteger cancelled = new AtomicInteger(0); public SdkTestHttpContentPublisher(byte[] body) { this.body = body; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { boolean wasFirstSubscriber = subscriber.compareAndSet(null, s); SdkTestHttpContentPublisher publisher = this; if (wasFirstSubscriber) { s.onSubscribe(new Subscription() { @Override public void request(long n) { publisher.request(n); } @Override public void cancel() { cancelled.incrementAndGet(); // Do nothing } }); } else { s.onError(new RuntimeException("Only allow one subscriber")); } } protected void request(long n) { // Send the whole body if they request >0 ByteBuffers if (n > 0 && !complete.get()) { complete.set(true); subscriber.get().onNext(ByteBuffer.wrap(body)); subscriber.get().onComplete(); } } @Override public Optional<Long> contentLength() { return Optional.of((long)body.length); } }
1,306
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientTestUtils.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.WireMockServer; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; public class NettyNioAsyncHttpClientTestUtils { /** * Make a simple async request and wait for it to fiish. * * @param client Client to make request with. */ public static void makeSimpleRequest(SdkAsyncHttpClient client, WireMockServer mockServer) throws Exception { String body = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body))); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); } public static SdkHttpContentPublisher createProvider(String body) { Stream<ByteBuffer> chunks = splitStringBySize(body).stream() .map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8))); return new SdkHttpContentPublisher() { @Override public Optional<Long> contentLength() { return Optional.of(Long.valueOf(body.length())); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { chunks.forEach(s::onNext); s.onComplete(); } @Override public void cancel() { } }); } }; } public static SdkHttpFullRequest createRequest(URI uri) { return createRequest(uri, "/", null, SdkHttpMethod.GET, emptyMap()); } public static SdkHttpFullRequest createRequest(URI uri, String resourcePath, String body, SdkHttpMethod method, Map<String, String> params) { String contentLength = body == null ? null : String.valueOf(body.getBytes(UTF_8).length); return SdkHttpFullRequest.builder() .uri(uri) .method(method) .encodedPath(resourcePath) .applyMutation(b -> params.forEach(b::putRawQueryParameter)) .applyMutation(b -> { b.putHeader("Host", uri.getHost()); if (contentLength != null) { b.putHeader("Content-Length", contentLength); } }).build(); } public static void assertCanReceiveBasicRequest(SdkAsyncHttpClient client, URI uri, String body) throws Exception { stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body))); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); assertThat(recorder.responses).hasOnlyOneElementSatisfying( headerResponse -> { assertThat(headerResponse.headers()).containsKey("Some-Header"); assertThat(headerResponse.statusCode()).isEqualTo(200); }); assertThat(recorder.fullResponseAsString()).isEqualTo(body); verify(1, getRequestedFor(urlMatching("/"))); } private static Collection<String> splitStringBySize(String str) { if (isBlank(str)) { return Collections.emptyList(); } ArrayList<String> split = new ArrayList<>(); for (int i = 0; i <= str.length() / 1000; i++) { split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length()))); } return split; } }
1,307
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ClientTlsAuthTestBase.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.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; abstract class ClientTlsAuthTestBase { protected static final String STORE_PASSWORD = "password"; protected static final String CLIENT_STORE_TYPE = "pkcs12"; protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/netty/server-keystore"; protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/netty/client1.p12"; protected static Path tempDir; protected static Path serverKeyStore; protected static Path clientKeyStore; @BeforeAll public static void setUp() throws IOException { tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName()); copyCertsToTmpDir(); } @AfterAll public static void teardown() throws IOException { Files.deleteIfExists(serverKeyStore); Files.deleteIfExists(clientKeyStore); Files.deleteIfExists(tempDir); } private static void copyCertsToTmpDir() throws IOException { InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE); Path sks = copyToTmpDir(sksStream, "server-keystore"); InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE); Path cks = copyToTmpDir(cksStream, "client1.p12"); serverKeyStore = sks; clientKeyStore = cks; } private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException { Path dst = tempDir.resolve(name); Files.copy(srcStream, dst); return dst; } }
1,308
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyClientTlsAuthTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import java.io.IOException; import java.util.concurrent.CompletionException; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.http.EmptyPublisher; import software.amazon.awssdk.http.FileStoreTlsKeyManagersProvider; import software.amazon.awssdk.http.HttpTestUtils; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.TlsKeyManagersProvider; 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.utils.AttributeMap; /** * Tests to ensure that Netty layer can perform TLS client authentication. */ public class NettyClientTlsAuthTest extends ClientTlsAuthTestBase { private static final AttributeMap DEFAULTS = AttributeMap.builder() .put(TRUST_ALL_CERTIFICATES, true) .build(); @Rule public ExpectedException thrown = ExpectedException.none(); private static WireMockServer mockProxy; private static ProxyConfiguration proxyCfg; private static TlsKeyManagersProvider keyManagersProvider; private SdkAsyncHttpClient netty; @BeforeClass public static void setUp() throws IOException { ClientTlsAuthTestBase.setUp(); // Will be used by both client and server to trust the self-signed // cert they present to each other System.setProperty("javax.net.ssl.trustStore", serverKeyStore.toAbsolutePath().toString()); System.setProperty("javax.net.ssl.trustStorePassword", STORE_PASSWORD); System.setProperty("javax.net.ssl.trustStoreType", "jks"); mockProxy = new WireMockServer(new WireMockConfiguration() .dynamicHttpsPort() .needClientAuth(true) .keystorePath(serverKeyStore.toAbsolutePath().toString()) .keystorePassword(STORE_PASSWORD)); mockProxy.start(); mockProxy.stubFor(get(urlPathMatching(".*")).willReturn(aResponse().withStatus(200).withBody("hello"))); proxyCfg = ProxyConfiguration.builder() .scheme("https") .host("localhost") .port(mockProxy.httpsPort()) .build(); keyManagersProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); } @AfterClass public static void teardown() throws IOException { ClientTlsAuthTestBase.teardown(); mockProxy.stop(); System.clearProperty("javax.net.ssl.trustStore"); System.clearProperty("javax.net.ssl.trustStorePassword"); System.clearProperty("javax.net.ssl.trustStoreType"); } @After public void methodTeardown() { if (netty != null) { netty.close(); } netty = null; } @Test public void builderUsesProvidedKeyManagersProvider() { TlsKeyManagersProvider mockKeyManagersProvider = mock(TlsKeyManagersProvider.class); netty = NettyNioAsyncHttpClient.builder() .proxyConfiguration(proxyCfg) .tlsKeyManagersProvider(mockKeyManagersProvider) .buildWithDefaults(DEFAULTS); try { sendRequest(netty, new RecordingResponseHandler()); } catch (Exception ignored) { } verify(mockKeyManagersProvider).keyManagers(); } @Test public void proxyRequest_ableToAuthenticate() { thrown.expectCause(instanceOf(IOException.class)); thrown.expectMessage("Could not connect to proxy"); netty = NettyNioAsyncHttpClient.builder() .proxyConfiguration(proxyCfg) .tlsKeyManagersProvider(keyManagersProvider) .buildWithDefaults(DEFAULTS); sendRequest(netty, new RecordingResponseHandler()); } @Test public void proxyRequest_noKeyManagerGiven_notAbleToSendConnect() throws Throwable { thrown.expectCause(instanceOf(IOException.class)); thrown.expectMessage("Unable to send CONNECT request to proxy"); netty = NettyNioAsyncHttpClient.builder() .proxyConfiguration(proxyCfg) .buildWithDefaults(DEFAULTS); sendRequest(netty, new RecordingResponseHandler()); } @Test public void proxyRequest_keyStoreSystemPropertiesConfigured_ableToAuthenticate() throws Throwable { thrown.expectCause(instanceOf(IOException.class)); thrown.expectMessage("Could not connect to proxy"); System.setProperty("javax.net.ssl.keyStore", clientKeyStore.toAbsolutePath().toString()); System.setProperty("javax.net.ssl.keyStoreType", CLIENT_STORE_TYPE); System.setProperty("javax.net.ssl.keyStorePassword", STORE_PASSWORD); netty = NettyNioAsyncHttpClient.builder() .proxyConfiguration(proxyCfg) .buildWithDefaults(DEFAULTS); try { sendRequest(netty, new RecordingResponseHandler()); } finally { System.clearProperty("javax.net.ssl.keyStore"); System.clearProperty("javax.net.ssl.keyStoreType"); System.clearProperty("javax.net.ssl.keyStorePassword"); } } @Test public void nonProxy_noKeyManagerGiven_shouldThrowException() { netty = NettyNioAsyncHttpClient.builder() .buildWithDefaults(DEFAULTS); assertThatThrownBy(() -> HttpTestUtils.sendGetRequest(mockProxy.httpsPort(), netty).join()) .isInstanceOf(CompletionException.class) .hasMessageContaining("SSL") .hasRootCauseInstanceOf(SSLException.class); } @Test public void builderUsesProvidedKeyManagersProviderNonBlockingDns() { TlsKeyManagersProvider mockKeyManagersProvider = mock(TlsKeyManagersProvider.class); netty = NettyNioAsyncHttpClient.builder() .useNonBlockingDnsResolver(true) .proxyConfiguration(proxyCfg) .tlsKeyManagersProvider(mockKeyManagersProvider) .buildWithDefaults(AttributeMap.builder() .put(TRUST_ALL_CERTIFICATES, true) .build()); try { sendRequest(netty, new RecordingResponseHandler()); } catch (Exception ignored) { } verify(mockKeyManagersProvider).keyManagers(); } private void sendRequest(SdkAsyncHttpClient client, SdkAsyncHttpResponseHandler responseHandler) { AsyncExecuteRequest req = AsyncExecuteRequest.builder() .request(testSdkRequest()) .requestContentPublisher(new EmptyPublisher()) .responseHandler(responseHandler) .build(); client.execute(req).join(); } private static SdkHttpFullRequest testSdkRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("https") .host("some-awesome-service.amazonaws.com") .port(443) .putHeader("host", "some-awesome-service.amazonaws.com") .build(); } }
1,309
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/ProxyConfigurationTest.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 org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.stream.Stream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for {@link ProxyConfiguration}. */ public class ProxyConfigurationTest { private static final Random RNG = new Random(); private static final String TEST_HOST = "foo.com"; private static final int TEST_PORT = 7777; private static final String TEST_NON_PROXY_HOST = "bar.com"; private static final String TEST_USER = "testuser"; private static final String TEST_PASSWORD = "123"; @BeforeEach public void setup() { clearProxyProperties(); } @AfterAll public static void cleanup() { clearProxyProperties(); } @Test void build_setsAllProperties() { verifyAllPropertiesSet(allPropertiesSetConfig()); } @Test void build_systemPropertyDefault_Http() { setHttpProxyProperties(); Set<String> nonProxyHost = new HashSet<>(); nonProxyHost.add("bar.com"); ProxyConfiguration config = ProxyConfiguration.builder().build(); assertThat(config.host()).isEqualTo(TEST_HOST); assertThat(config.port()).isEqualTo(TEST_PORT); assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost); assertThat(config.username()).isEqualTo(TEST_USER); assertThat(config.password()).isEqualTo(TEST_PASSWORD); assertThat(config.scheme()).isEqualTo("http"); } @Test void build_systemPropertyEnabled_Https() { setHttpsProxyProperties(); Set<String> nonProxyHost = new HashSet<>(); nonProxyHost.add("bar.com"); ProxyConfiguration config = ProxyConfiguration.builder() .scheme("https") .useSystemPropertyValues(Boolean.TRUE).build(); assertThat(config.host()).isEqualTo(TEST_HOST); assertThat(config.port()).isEqualTo(TEST_PORT); assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost); assertThat(config.username()).isEqualTo(TEST_USER); assertThat(config.password()).isEqualTo(TEST_PASSWORD); assertThat(config.scheme()).isEqualTo("https"); } @Test void build_systemPropertyDisabled() { setHttpProxyProperties(); Set<String> nonProxyHost = new HashSet<>(); nonProxyHost.add("test.com"); ProxyConfiguration config = ProxyConfiguration.builder() .host("localhost") .port(8888) .nonProxyHosts(nonProxyHost) .username("username") .password("password") .useSystemPropertyValues(Boolean.FALSE).build(); assertThat(config.host()).isEqualTo("localhost"); assertThat(config.port()).isEqualTo(8888); assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost); assertThat(config.username()).isEqualTo("username"); assertThat(config.password()).isEqualTo("password"); assertThat(config.scheme()).isEqualTo("http"); } @Test void build_systemPropertyOverride() { setHttpProxyProperties(); Set<String> nonProxyHost = new HashSet<>(); nonProxyHost.add("test.com"); ProxyConfiguration config = ProxyConfiguration.builder() .host("localhost") .port(8888) .nonProxyHosts(nonProxyHost) .username("username") .password("password") .build(); assertThat(config.host()).isEqualTo("localhost"); assertThat(config.port()).isEqualTo(8888); assertThat(config.nonProxyHosts()).isEqualTo(nonProxyHost); assertThat(config.username()).isEqualTo("username"); assertThat(config.password()).isEqualTo("password"); assertThat(config.scheme()).isEqualTo("http"); } @Test void toBuilder_roundTrip_producesExactCopy() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration copy = original.toBuilder().build(); assertThat(copy).isEqualTo(original); } @Test void setNonProxyHostsToNull_createsEmptySet() { ProxyConfiguration cfg = ProxyConfiguration.builder() .nonProxyHosts(null) .build(); assertThat(cfg.nonProxyHosts()).isEmpty(); } @Test void toBuilderModified_doesNotModifySource() { ProxyConfiguration original = allPropertiesSetConfig(); ProxyConfiguration modified = setAllPropertiesToRandomValues(original.toBuilder()).build(); assertThat(original).isNotEqualTo(modified); } private ProxyConfiguration allPropertiesSetConfig() { return setAllPropertiesToRandomValues(ProxyConfiguration.builder()).build(); } private ProxyConfiguration.Builder setAllPropertiesToRandomValues(ProxyConfiguration.Builder builder) { Stream.of(builder.getClass().getDeclaredMethods()) .filter(m -> m.getParameterCount() == 1 && m.getReturnType().equals(ProxyConfiguration.Builder.class)) .forEach(m -> { try { m.setAccessible(true); setRandomValue(builder, m); } catch (Exception e) { throw new RuntimeException("Could not create random proxy config", e); } }); return builder; } private void setRandomValue(Object o, Method setter) throws InvocationTargetException, IllegalAccessException { Class<?> paramClass = setter.getParameterTypes()[0]; if (String.class.equals(paramClass)) { setter.invoke(o, randomString()); } else if (int.class.equals(paramClass)) { setter.invoke(o, RNG.nextInt()); } else if (Set.class.isAssignableFrom(paramClass)) { setter.invoke(o, randomSet()); } else if (Boolean.class.equals(paramClass)) { setter.invoke(o, RNG.nextBoolean()); } else { throw new RuntimeException("Don't know how create random value for type " + paramClass); } } private void verifyAllPropertiesSet(ProxyConfiguration cfg) { boolean hasNullProperty = Stream.of(cfg.getClass().getDeclaredMethods()) .filter(m -> !m.getReturnType().equals(Void.class) && m.getParameterCount() == 0) .anyMatch(m -> { m.setAccessible(true); try { return m.invoke(cfg) == null; } catch (Exception e) { return true; } }); if (hasNullProperty) { throw new RuntimeException("Given configuration has unset property"); } } private String randomString() { String alpha = "abcdefghijklmnopqrstuwxyz"; StringBuilder sb = new StringBuilder(16); for (int i = 0; i < 16; ++i) { sb.append(alpha.charAt(RNG.nextInt(16))); } return sb.toString(); } private Set<String> randomSet() { Set<String> ss = new HashSet<>(16); for (int i = 0; i < 16; ++i) { ss.add(randomString()); } return ss; } private void setHttpProxyProperties() { System.setProperty("http.proxyHost", TEST_HOST); System.setProperty("http.proxyPort", Integer.toString(TEST_PORT)); System.setProperty("http.nonProxyHosts", TEST_NON_PROXY_HOST); System.setProperty("http.proxyUser", TEST_USER); System.setProperty("http.proxyPassword", TEST_PASSWORD); } private void setHttpsProxyProperties() { System.setProperty("https.proxyHost", TEST_HOST); System.setProperty("https.proxyPort", Integer.toString(TEST_PORT)); System.setProperty("http.nonProxyHosts", TEST_NON_PROXY_HOST); System.setProperty("https.proxyUser", TEST_USER); System.setProperty("https.proxyPassword", TEST_PASSWORD); } private static void clearProxyProperties() { System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("http.nonProxyHosts"); System.clearProperty("http.proxyUser"); System.clearProperty("http.proxyPassword"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); System.clearProperty("https.proxyUser"); System.clearProperty("https.proxyPassword"); } }
1,310
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/RecordingResponseHandler.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.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.async.SdkHttpResponseHandler; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.metrics.MetricCollector; public final class RecordingResponseHandler implements SdkAsyncHttpResponseHandler { List<SdkHttpResponse> responses = new ArrayList<>(); private StringBuilder bodyParts = new StringBuilder(); CompletableFuture<Void> completeFuture = new CompletableFuture<>(); CompletableFuture<Void> executionFuture = null; MetricCollector collector = MetricCollector.create("test"); @Override public void onHeaders(SdkHttpResponse response) { responses.add(response); } @Override public void onStream(Publisher<ByteBuffer> publisher) { publisher.subscribe(new SimpleSubscriber(byteBuffer -> { byte[] b = new byte[byteBuffer.remaining()]; byteBuffer.duplicate().get(b); bodyParts.append(new String(b, StandardCharsets.UTF_8)); }) { @Override public void onError(Throwable t) { completeFuture.completeExceptionally(t); } @Override public void onComplete() { completeFuture.complete(null); } }); } @Override public void onError(Throwable error) { completeFuture.completeExceptionally(error); } public String fullResponseAsString() { return bodyParts.toString(); } }
1,311
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClientDefaultWireMockTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.reverse; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.assertj.core.api.Condition; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; public class NettyNioAsyncHttpClientDefaultWireMockTest { private final RecordingNetworkTrafficListener wiremockTrafficListener = new RecordingNetworkTrafficListener(); @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig() .dynamicPort() .dynamicHttpsPort() .networkTrafficListener(wiremockTrafficListener)); private static SdkAsyncHttpClient client = NettyNioAsyncHttpClient.create(); @Before public void methodSetup() { wiremockTrafficListener.reset(); } @AfterClass public static void tearDown() throws Exception { client.close(); } @Test public void defaultThreadFactoryUsesHelpfulName() throws Exception { // Make a request to ensure a thread is primed makeSimpleRequest(client); String expectedPattern = "aws-java-sdk-NettyEventLoop-\\d+-\\d+"; assertThat(Thread.getAllStackTraces().keySet()) .areAtLeast(1, new Condition<>(t -> t.getName().matches(expectedPattern), "Matches default thread pattern: `%s`", expectedPattern)); } /** * Make a simple async request and wait for it to fiish. * * @param client Client to make request with. */ private void makeSimpleRequest(SdkAsyncHttpClient client) throws Exception { String body = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withBody(body))); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); } @Test public void canMakeBasicRequestOverHttp() throws Exception { String smallBody = randomAlphabetic(10); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(uri, smallBody); } @Test public void canHandleLargerPayloadsOverHttp() throws Exception { String largishBody = randomAlphabetic(25000); URI uri = URI.create("http://localhost:" + mockServer.port()); assertCanReceiveBasicRequest(uri, largishBody); } @Test public void canSendContentAndGetThatContentBack() throws Exception { String body = randomAlphabetic(50); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(body)) .willReturn(aResponse().withBody(reverse(body)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpRequest request = createRequest(uri, "/echo", body, SdkHttpMethod.POST, singletonMap("reversed", "true")); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(body)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); verify(1, postRequestedFor(urlEqualTo("/echo?reversed=true"))); assertThat(recorder.fullResponseAsString()).isEqualTo(reverse(body)); } @Test public void requestContentOnlyEqualToContentLengthHeaderFromProvider() throws Exception { final String content = randomAlphabetic(32); final String streamContent = content + reverse(content); stubFor(any(urlEqualTo("/echo?reversed=true")) .withRequestBody(equalTo(content)) .willReturn(aResponse().withBody(reverse(content)))); URI uri = URI.create("http://localhost:" + mockServer.port()); SdkHttpFullRequest request = createRequest(uri, "/echo", streamContent, SdkHttpMethod.POST, singletonMap("reversed", "true")); request = request.toBuilder().putHeader("Content-Length", Integer.toString(content.length())).build(); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider(streamContent)).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); // HTTP servers will stop processing the request as soon as it reads // bytes equal to 'Content-Length' so we need to inspect the raw // traffic to ensure that there wasn't anything after that. assertThat(wiremockTrafficListener.requests().toString()).endsWith(content); } private void assertCanReceiveBasicRequest(URI uri, String body) throws Exception { stubFor(any(urlPathEqualTo("/")).willReturn(aResponse().withHeader("Some-Header", "With Value").withBody(body))); SdkHttpRequest request = createRequest(uri); RecordingResponseHandler recorder = new RecordingResponseHandler(); client.execute(AsyncExecuteRequest.builder().request(request).requestContentPublisher(createProvider("")).responseHandler(recorder).build()); recorder.completeFuture.get(5, TimeUnit.SECONDS); assertThat(recorder.responses).hasOnlyOneElementSatisfying( headerResponse -> { assertThat(headerResponse.headers()).containsKey("Some-Header"); assertThat(headerResponse.statusCode()).isEqualTo(200); }); assertThat(recorder.fullResponseAsString()).isEqualTo(body); verify(1, getRequestedFor(urlMatching("/"))); } private SdkHttpContentPublisher createProvider(String body) { Stream<ByteBuffer> chunks = splitStringBySize(body).stream() .map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8))); return new SdkHttpContentPublisher() { @Override public Optional<Long> contentLength() { return Optional.of(Long.valueOf(body.length())); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { chunks.forEach(s::onNext); s.onComplete(); } @Override public void cancel() { } }); } }; } private SdkHttpFullRequest createRequest(URI uri) { return createRequest(uri, "/", null, SdkHttpMethod.GET, emptyMap()); } private SdkHttpFullRequest createRequest(URI uri, String resourcePath, String body, SdkHttpMethod method, Map<String, String> params) { String contentLength = body == null ? null : String.valueOf(body.getBytes(UTF_8).length); return SdkHttpFullRequest.builder() .uri(uri) .method(method) .encodedPath(resourcePath) .applyMutation(b -> params.forEach(b::putRawQueryParameter)) .applyMutation(b -> { b.putHeader("Host", uri.getHost()); if (contentLength != null) { b.putHeader("Content-Length", contentLength); } }).build(); } private static Collection<String> splitStringBySize(String str) { if (isBlank(str)) { return Collections.emptyList(); } ArrayList<String> split = new ArrayList<>(); for (int i = 0; i <= str.length() / 1000; i++) { split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length()))); } return split; } }
1,312
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/internal/ProxyTunnelInitHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; 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.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.ssl.SslCloseCompletionEvent; import io.netty.handler.ssl.SslHandler; 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 org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; /** * Unit tests for {@link ProxyTunnelInitHandler}. */ @RunWith(MockitoJUnitRunner.class) public class ProxyTunnelInitHandlerTest { private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1); private static final URI REMOTE_HOST = URI.create("https://s3.amazonaws.com:1234"); private static final String PROXY_USER = "myuser"; private static final String PROXY_PASSWORD = "mypassword"; @Mock private ChannelHandlerContext mockCtx; @Mock private Channel mockChannel; @Mock private ChannelPipeline mockPipeline; @Mock private ChannelPool mockChannelPool; @Before public void methodSetup() { when(mockCtx.channel()).thenReturn(mockChannel); when(mockCtx.pipeline()).thenReturn(mockPipeline); when(mockChannel.writeAndFlush(any())).thenReturn(new DefaultChannelPromise(mockChannel, GROUP.next())); } @AfterClass public static void teardown() { GROUP.shutdownGracefully().awaitUninterruptibly(); } @Test public void addedToPipeline_addsCodec() { HttpClientCodec codec = new HttpClientCodec(); Supplier<HttpClientCodec> codecSupplier = () -> codec; when(mockCtx.name()).thenReturn("foo"); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, null, null, REMOTE_HOST, null, codecSupplier); handler.handlerAdded(mockCtx); verify(mockPipeline).addBefore(eq("foo"), eq(null), eq(codec)); } @Test public void successfulProxyResponse_completesFuture() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); successResponse(handler); assertThat(promise.awaitUninterruptibly().getNow()).isEqualTo(mockChannel); } @Test public void successfulProxyResponse_removesSelfAndCodec() { when(mockPipeline.get(HttpClientCodec.class)).thenReturn(new HttpClientCodec()); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); successResponse(handler); handler.handlerRemoved(mockCtx); verify(mockPipeline).remove(eq(handler)); verify(mockPipeline).remove(eq(HttpClientCodec.class)); } @Test public void successfulProxyResponse_doesNotRemoveSslHandler() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); successResponse(handler); verify(mockPipeline, never()).get(eq(SslHandler.class)); verify(mockPipeline, never()).remove(eq(SslHandler.class)); } @Test public void unexpectedMessage_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.channelRead(mockCtx, new Object()); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } @Test public void unsuccessfulResponse_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); handler.channelRead(mockCtx, resp); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } @Test public void requestWriteFails_failsPromise() { DefaultChannelPromise writePromise = new DefaultChannelPromise(mockChannel, GROUP.next()); writePromise.setFailure(new IOException("boom")); when(mockChannel.writeAndFlush(any())).thenReturn(writePromise); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); } @Test public void channelInactive_shouldFailPromise() throws Exception { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); SslCloseCompletionEvent event = new SslCloseCompletionEvent(new RuntimeException("")); handler.channelInactive(mockCtx); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); verify(mockCtx).close(); } @Test public void unexpectedExceptionThrown_shouldFailPromise() throws Exception { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.exceptionCaught(mockCtx, new RuntimeException("exception")); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); verify(mockCtx).close(); } @Test public void handlerRemoved_removesCodec() { HttpClientCodec codec = new HttpClientCodec(); when(mockPipeline.get(eq(HttpClientCodec.class))).thenReturn(codec); Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerRemoved(mockCtx); verify(mockPipeline).remove(eq(HttpClientCodec.class)); } @Test public void handledAdded_writesRequest_withoutAuth() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); verify(mockChannel).writeAndFlush(requestCaptor.capture()); String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort(); HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri, Unpooled.EMPTY_BUFFER, false); expectedRequest.headers().add(HttpHeaderNames.HOST, uri); assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest); } @Test public void handledAdded_writesRequest_withAuth() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, PROXY_USER, PROXY_PASSWORD, REMOTE_HOST, promise); handler.handlerAdded(mockCtx); ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); verify(mockChannel).writeAndFlush(requestCaptor.capture()); String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort(); HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri, Unpooled.EMPTY_BUFFER, false); expectedRequest.headers().add(HttpHeaderNames.HOST, uri); String authB64 = Base64.getEncoder().encodeToString(String.format("%s:%s", PROXY_USER, PROXY_PASSWORD).getBytes(CharsetUtil.UTF_8)); expectedRequest.headers().add(HttpHeaderNames.PROXY_AUTHORIZATION, String.format("Basic %s", authB64)); assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest); } private void successResponse(ProxyTunnelInitHandler handler) { DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); handler.channelRead(mockCtx, resp); } }
1,313
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/internal/CancellableAcquireChannelPoolTest.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.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Promise; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link CancellableAcquireChannelPool}. */ @RunWith(MockitoJUnitRunner.class) public class CancellableAcquireChannelPoolTest { private static final EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); private EventExecutor eventExecutor; @Mock private SdkChannelPool mockDelegatePool; private Channel channel; private CancellableAcquireChannelPool cancellableAcquireChannelPool; @Before public void setup() { channel = new NioSocketChannel(); eventLoopGroup.register(channel); eventExecutor = eventLoopGroup.next(); cancellableAcquireChannelPool = new CancellableAcquireChannelPool(eventExecutor, mockDelegatePool); } @After public void methodTeardown() { channel.close().awaitUninterruptibly(); } @AfterClass public static void teardown() { eventLoopGroup.shutdownGracefully().awaitUninterruptibly(); } @Test public void promiseCancelledBeforeAcquireComplete_closesAndReleasesChannel() throws InterruptedException { Promise<Channel> acquireFuture = eventExecutor.newPromise(); acquireFuture.setFailure(new RuntimeException("Changed my mind!")); when(mockDelegatePool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> { Promise p = invocationOnMock.getArgument(0, Promise.class); p.setSuccess(channel); return p; }); cancellableAcquireChannelPool.acquire(acquireFuture); Thread.sleep(500); verify(mockDelegatePool).release(eq(channel)); assertThat(channel.closeFuture().isDone()).isTrue(); } }
1,314
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/internal/SharedSdkEventLoopGroupTest.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 org.assertj.core.api.Java6Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; public class SharedSdkEventLoopGroupTest { @Test public void referenceCountIsInitiallyZero() { assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); } @Test public void referenceCountIsIncrementedOnGet() { SdkEventLoopGroup group = SharedSdkEventLoopGroup.get(); assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(1); group.eventLoopGroup().shutdownGracefully(); } @Test public void referenceCountIsOnceDecrementedOnClose() { SdkEventLoopGroup group = SharedSdkEventLoopGroup.get(); group.eventLoopGroup().shutdownGracefully(); assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); group.eventLoopGroup().shutdownGracefully(); assertThat(SharedSdkEventLoopGroup.referenceCount()).isEqualTo(0); } @Test public void sharedEventLoopGroupIsDeallocatedWhenCountReachesZero() { DelegatingEventLoopGroup group1 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); DelegatingEventLoopGroup group2 = (DelegatingEventLoopGroup) SharedSdkEventLoopGroup.get().eventLoopGroup(); assertThat(group1.getDelegate()).isEqualTo(group2.getDelegate()); group1.shutdownGracefully(); group2.shutdownGracefully(); assertThat(group1.getDelegate().isShuttingDown()).isTrue(); } }
1,315
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/internal/FutureCancelHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; 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.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.DefaultChannelId; import io.netty.channel.EventLoopGroup; import io.netty.util.DefaultAttributeMap; import java.io.IOException; import java.util.concurrent.CancellationException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; /** * Unit tests for {@link FutureCancelHandler}. */ @RunWith(MockitoJUnitRunner.class) public class FutureCancelHandlerTest { private FutureCancelHandler handler = FutureCancelHandler.getInstance(); @Mock private ChannelHandlerContext ctx; @Mock private Channel channel; @Mock private SdkChannelPool channelPool; private RequestContext requestContext; @Mock private SdkAsyncHttpResponseHandler responseHandler; @Mock private EventLoopGroup eventLoopGroup; @Before public void methodSetup() { requestContext = new RequestContext(channelPool, eventLoopGroup, AsyncExecuteRequest.builder().responseHandler(responseHandler).build(), null); DefaultAttributeMap attrMap = new DefaultAttributeMap(); attrMap.attr(EXECUTION_ID_KEY).set(1L); attrMap.attr(REQUEST_CONTEXT_KEY).set(requestContext); when(ctx.channel()).thenReturn(channel); when(channel.attr(EXECUTION_ID_KEY)).thenReturn(attrMap.attr(EXECUTION_ID_KEY)); when(channel.attr(REQUEST_CONTEXT_KEY)).thenReturn(attrMap.attr(REQUEST_CONTEXT_KEY)); when(channel.id()).thenReturn(DefaultChannelId.newInstance()); } @Test public void surfacesCancelExceptionAsIOException() { FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); handler.exceptionCaught(ctx, cancelledException); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isInstanceOf(IOException.class); } @Test public void forwardsExceptionIfNotCancelledException() { ArgumentCaptor<Throwable> exceptionCaptor = ArgumentCaptor.forClass(Throwable.class); Throwable err = new RuntimeException("some other exception"); handler.exceptionCaught(ctx, err); verify(ctx).fireExceptionCaught(exceptionCaptor.capture()); assertThat(exceptionCaptor.getValue()).isEqualTo(err); } @Test public void cancelledException_executionIdNull_shouldIgnoreExceptionAndCloseChannel() { when(channel.attr(EXECUTION_ID_KEY)).thenReturn(null); FutureCancelledException cancelledException = new FutureCancelledException(1L, new CancellationException()); handler.exceptionCaught(ctx, cancelledException); verify(ctx, never()).fireExceptionCaught(any(Throwable.class)); verify(ctx).close(); } }
1,316
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/internal/HandlerRemovingChannelPoolListenerTest.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 org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE; 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 io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler; @RunWith(MockitoJUnitRunner.class) public class HandlerRemovingChannelPoolListenerTest { @Mock private SdkChannelPool channelPool; @Mock private SdkAsyncHttpResponseHandler responseHandler; private Channel mockChannel; private ChannelPipeline pipeline; private NioEventLoopGroup nioEventLoopGroup; private HandlerRemovingChannelPoolListener handler; @Before public void setup() throws Exception { mockChannel = new MockChannel(); pipeline = mockChannel.pipeline(); pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); nioEventLoopGroup = new NioEventLoopGroup(); nioEventLoopGroup.register(mockChannel); RequestContext requestContext = new RequestContext(channelPool, nioEventLoopGroup, AsyncExecuteRequest.builder().responseHandler(responseHandler).build(), null); mockChannel.attr(IN_USE).set(true); mockChannel.attr(REQUEST_CONTEXT_KEY).set(requestContext); mockChannel.attr(RESPONSE_COMPLETE_KEY).set(true); pipeline.addLast(new HttpStreamsClientHandler()); pipeline.addLast(ResponseHandler.getInstance()); pipeline.addLast(new ReadTimeoutHandler(10)); pipeline.addLast(new WriteTimeoutHandler(10)); handler = HandlerRemovingChannelPoolListener.create(); } @After public void tearDown() { nioEventLoopGroup.shutdownGracefully(); } @Test public void release_openChannel_handlerShouldBeRemovedFromChannelPool() { assertHandlersNotRemoved(); handler.channelReleased(mockChannel); assertHandlersRemoved(); } @Test public void release_closedChannel_handlerShouldBeRemovedFromPipeline() { mockChannel.close().awaitUninterruptibly(); // CLOSE -> INACTIVE -> UNREGISTERED: channel handlers should be removed at this point assertHandlersRemoved(); handler.channelReleased(mockChannel); assertHandlersRemoved(); } @Test public void release_deregisteredOpenChannel_handlerShouldBeRemovedFromChannelPool() { mockChannel.deregister().awaitUninterruptibly(); assertHandlersNotRemoved(); handler.channelReleased(mockChannel); assertHandlersRemoved(); } private void assertHandlersRemoved() { assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNull(); assertThat(pipeline.get(ResponseHandler.class)).isNull(); assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull(); assertThat(pipeline.get(WriteTimeoutHandler.class)).isNull(); } private void assertHandlersNotRemoved() { assertThat(pipeline.get(HttpStreamsClientHandler.class)).isNotNull(); assertThat(pipeline.get(ResponseHandler.class)).isNotNull(); assertThat(pipeline.get(ReadTimeoutHandler.class)).isNotNull(); assertThat(pipeline.get(WriteTimeoutHandler.class)).isNotNull(); } }
1,317
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/internal/HealthCheckedChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.util.Attribute; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GlobalEventExecutor; 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.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.mockito.stubbing.OngoingStubbing; import software.amazon.awssdk.utils.AttributeMap; public class HealthCheckedChannelPoolTest { private EventLoopGroup eventLoopGroup = Mockito.mock(EventLoopGroup.class); private EventLoop eventLoop = Mockito.mock(EventLoop.class); private SdkChannelPool downstreamChannelPool = Mockito.mock(SdkChannelPool.class); private List<Channel> channels = new ArrayList<>(); private ScheduledFuture<?> scheduledFuture = Mockito.mock(ScheduledFuture.class); private Attribute<Boolean> attribute = mock(Attribute.class); private static final NettyConfiguration NETTY_CONFIGURATION = new NettyConfiguration(AttributeMap.builder() .put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofMillis(10)) .build()); private HealthCheckedChannelPool channelPool = new HealthCheckedChannelPool(eventLoopGroup, NETTY_CONFIGURATION, downstreamChannelPool); @BeforeEach public void reset() { Mockito.reset(eventLoopGroup, eventLoop, downstreamChannelPool, scheduledFuture, attribute); channels.clear(); Mockito.when(eventLoopGroup.next()).thenReturn(eventLoop); Mockito.when(eventLoop.newPromise()) .thenAnswer((Answer<Promise<Object>>) i -> new DefaultPromise<>(GlobalEventExecutor.INSTANCE)); } @Test public void acquireCanMakeJustOneCall() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void acquireCanMakeManyCalls() throws Exception { stubForIgnoredTimeout(); stubAcquireHealthySequence(false, false, false, false, true); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(4)); Mockito.verify(downstreamChannelPool, Mockito.times(5)).acquire(any()); } @Test public void acquireActiveAndKeepAliveTrue_shouldAcquireOnce() throws Exception { stubForIgnoredTimeout(); stubAcquireActiveAndKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(0)); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void acquire_firstChannelKeepAliveFalse_shouldAcquireAnother() throws Exception { stubForIgnoredTimeout(); stubAcquireTwiceFirstTimeNotKeepAlive(); Future<Channel> acquire = channelPool.acquire(); acquire.get(5, TimeUnit.SECONDS); assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isTrue(); assertThat(acquire.getNow()).isEqualTo(channels.get(1)); Mockito.verify(downstreamChannelPool, Mockito.times(2)).acquire(any()); } @Test public void badDownstreamAcquiresCausesException() throws Exception { stubForIgnoredTimeout(); stubBadDownstreamAcquire(); Future<Channel> acquire = channelPool.acquire(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { // Expected } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(IOException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void slowAcquireTimesOut() throws Exception { stubIncompleteDownstreamAcquire(); Mockito.when(eventLoopGroup.schedule(Mockito.any(Runnable.class), Mockito.eq(10), Mockito.eq(TimeUnit.MILLISECONDS))) .thenAnswer(i -> scheduledFuture); Future<Channel> acquire = channelPool.acquire(); ArgumentCaptor<Runnable> timeoutTask = ArgumentCaptor.forClass(Runnable.class); Mockito.verify(eventLoopGroup).schedule(timeoutTask.capture(), anyLong(), any()); timeoutTask.getValue().run(); try { acquire.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { // Expected } assertThat(acquire.isDone()).isTrue(); assertThat(acquire.isSuccess()).isFalse(); assertThat(acquire.cause()).isInstanceOf(TimeoutException.class); Mockito.verify(downstreamChannelPool, Mockito.times(1)).acquire(any()); } @Test public void releaseHealthyDoesNotClose() { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(true); stubKeepAliveAttribute(channel, null); channelPool.release(channel); Mockito.verify(channel, never()).close(); Mockito.verify(downstreamChannelPool, times(1)).release(channel); } @Test public void releaseHealthyCloses() { Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(false); stubKeepAliveAttribute(channel, null); channelPool.release(channel); Mockito.verify(channel, times(1)).close(); Mockito.verify(downstreamChannelPool, times(1)).release(channel); } public void stubAcquireHealthySequence(Boolean... acquireHealthySequence) { OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any())); for (boolean shouldAcquireBeHealthy : acquireHealthySequence) { stubbing = stubbing.thenAnswer(invocation -> { Promise<Channel> promise = invocation.getArgument(0, Promise.class); Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(shouldAcquireBeHealthy); stubKeepAliveAttribute(channel, null); channels.add(channel); promise.setSuccess(channel); return promise; }); } } private void stubAcquireActiveAndKeepAlive() { OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any())); stubbing = stubbing.thenAnswer(invocation -> { Promise<Channel> promise = invocation.getArgument(0, Promise.class); Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(true); stubKeepAliveAttribute(channel, true); channels.add(channel); promise.setSuccess(channel); return promise; }); } private void stubKeepAliveAttribute(Channel channel, Boolean isKeepAlive) { Mockito.when(channel.attr(KEEP_ALIVE)).thenReturn(attribute); when(attribute.get()).thenReturn(isKeepAlive); } public void stubBadDownstreamAcquire() { Mockito.when(downstreamChannelPool.acquire(any())).thenAnswer(invocation -> { Promise<Channel> promise = invocation.getArgument(0, Promise.class); promise.setFailure(new IOException()); return promise; }); } public void stubIncompleteDownstreamAcquire() { Mockito.when(downstreamChannelPool.acquire(any())).thenAnswer(invocation -> invocation.getArgument(0, Promise.class)); } public void stubForIgnoredTimeout() { Mockito.when(eventLoopGroup.schedule(any(Runnable.class), anyLong(), any())) .thenAnswer(i -> scheduledFuture); } private void stubAcquireTwiceFirstTimeNotKeepAlive() { OngoingStubbing<Future<Channel>> stubbing = Mockito.when(downstreamChannelPool.acquire(any())); stubbing = stubbing.thenAnswer(invocation -> { Promise<Channel> promise = invocation.getArgument(0, Promise.class); Channel channel = Mockito.mock(Channel.class); stubKeepAliveAttribute(channel, false); Mockito.when(channel.isActive()).thenReturn(true); channels.add(channel); promise.setSuccess(channel); return promise; }); stubbing.thenAnswer(invocation -> { Promise<Channel> promise = invocation.getArgument(0, Promise.class); Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.isActive()).thenReturn(true); channels.add(channel); promise.setSuccess(channel); stubKeepAliveAttribute(channel, true); return promise; }); } }
1,318
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/internal/OldConnectionReaperHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import io.netty.channel.ChannelHandlerContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.internal.verification.Times; public class OldConnectionReaperHandlerTest { @Test @SuppressWarnings("unchecked") public void inUseChannelsAreFlaggedToBeClosed() throws Exception { // Given MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(true); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); // When new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); // Then Mockito.verify(ctx, new Times(0)).close(); Mockito.verify(ctx, new Times(0)).close(any()); assertThat(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()).isTrue(); } @Test public void notInUseChannelsAreClosed() throws Exception { // Given MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.IN_USE).set(false); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.channel()).thenReturn(channel); // When new OldConnectionReaperHandler(1).handlerAdded(ctx); channel.runAllPendingTasks(); // Then Mockito.verify(ctx, new Times(1)).close(); Mockito.verify(ctx, new Times(0)).close(any()); } }
1,319
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/internal/NettyRequestExecutorTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.WRITE_TIMEOUT; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelPipeline; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Promise; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.utils.AttributeMap; public class NettyRequestExecutorTest { private SdkChannelPool mockChannelPool; private EventLoopGroup eventLoopGroup; private NettyRequestExecutor nettyRequestExecutor; private RequestContext requestContext; @BeforeEach public void setup() { mockChannelPool = mock(SdkChannelPool.class); eventLoopGroup = new NioEventLoopGroup(); AttributeMap attributeMap = AttributeMap.builder() .put(WRITE_TIMEOUT, Duration.ofSeconds(3)) .build(); requestContext = new RequestContext(mockChannelPool, eventLoopGroup, AsyncExecuteRequest.builder().request(SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .host("amazonaws.com") .protocol("https") .build()) .build(), new NettyConfiguration(attributeMap)); nettyRequestExecutor = new NettyRequestExecutor(requestContext); } @AfterEach public void teardown() throws InterruptedException { eventLoopGroup.shutdownGracefully().await(); } @Test public void cancelExecuteFuture_channelNotAcquired_failsAcquirePromise() { ArgumentCaptor<Promise> acquireCaptor = ArgumentCaptor.forClass(Promise.class); when(mockChannelPool.acquire(acquireCaptor.capture())).thenAnswer((Answer<Promise>) invocationOnMock -> { return invocationOnMock.getArgument(0, Promise.class); }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); executeFuture.cancel(true); assertThat(acquireCaptor.getValue().isDone()).isTrue(); assertThat(acquireCaptor.getValue().isSuccess()).isFalse(); } @Test public void cancelExecuteFuture_channelAcquired_submitsRunnable() throws InterruptedException { EventLoop mockEventLoop = mock(EventLoop.class); Channel mockChannel = mock(Channel.class); ChannelPipeline mockPipeline = mock(ChannelPipeline.class); when(mockChannel.pipeline()).thenReturn(mockPipeline); when(mockChannel.eventLoop()).thenReturn(mockEventLoop); when(mockChannel.isActive()).thenReturn(true); Attribute<Boolean> mockInUseAttr = mock(Attribute.class); when(mockInUseAttr.get()).thenReturn(Boolean.TRUE); CompletableFuture<Protocol> protocolFuture = CompletableFuture.completedFuture(Protocol.HTTP1_1); Attribute<CompletableFuture<Protocol>> mockProtocolFutureAttr = mock(Attribute.class); when(mockProtocolFutureAttr.get()).thenReturn(protocolFuture); when(mockChannel.attr(any(AttributeKey.class))).thenAnswer(i -> { AttributeKey argumentAt = i.getArgument(0, AttributeKey.class); if (argumentAt == IN_USE) { return mockInUseAttr; } if (argumentAt == PROTOCOL_FUTURE) { return mockProtocolFutureAttr; } return mock(Attribute.class); }); when(mockChannel.writeAndFlush(any(Object.class))).thenReturn(new DefaultChannelPromise(mockChannel)); ChannelConfig mockChannelConfig = mock(ChannelConfig.class); when(mockChannel.config()).thenReturn(mockChannelConfig); CountDownLatch submitLatch = new CountDownLatch(1); when(mockEventLoop.submit(any(Runnable.class))).thenAnswer(i -> { i.getArgument(0, Runnable.class).run(); // Need to wait until the first submit() happens which sets up the channel before cancelling the future. submitLatch.countDown(); return null; }); when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> { Promise p = invocationOnMock.getArgument(0, Promise.class); p.setSuccess(mockChannel); return p; }); CountDownLatch exceptionFiredLatch = new CountDownLatch(1); when(mockPipeline.fireExceptionCaught(any(FutureCancelledException.class))).thenAnswer(i -> { exceptionFiredLatch.countDown(); return mockPipeline; }); CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute(); submitLatch.await(1, TimeUnit.SECONDS); executeFuture.cancel(true); exceptionFiredLatch.await(1, TimeUnit.SECONDS); verify(mockEventLoop, times(2)).submit(any(Runnable.class)); } }
1,320
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/internal/SslCloseCompletionEventHandlerTest.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 org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.ssl.SslCloseCompletionEvent; import java.nio.channels.ClosedChannelException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SslCloseCompletionEventHandlerTest { private ChannelHandlerContext ctx; private MockChannel channel; @BeforeEach public void setup() throws Exception { ctx = mock(ChannelHandlerContext.class); channel = new MockChannel(); when(ctx.channel()).thenReturn(channel); } @AfterEach public void teardown() { channel.close(); } @Test public void userEventTriggeredUnusedChannel_ClosesChannel() { SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance(); handler.userEventTriggered(ctx, new SslCloseCompletionEvent(new ClosedChannelException())); verify(ctx).close(); } @Test public void userEventTriggered_StaticVariable_ClosesChannel() { SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance(); handler.userEventTriggered(ctx, SslCloseCompletionEvent.SUCCESS); verify(ctx).close(); } @Test public void userEventTriggered_channelInUse_shouldForwardEvent() { SslCloseCompletionEventHandler handler = SslCloseCompletionEventHandler.getInstance(); channel.attr(IN_USE).set(true); SslCloseCompletionEvent event = new SslCloseCompletionEvent(new ClosedChannelException()); handler.userEventTriggered(ctx, event); verify(ctx).fireUserEventTriggered(event); } }
1,321
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/internal/StaticKeyManagerFactorySpiTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Arrays; import java.util.stream.IntStream; import javax.net.ssl.KeyManager; import org.junit.Test; /** * Tests for {@link StaticKeyManagerFactorySpi}. */ public class StaticKeyManagerFactorySpiTest { @Test(expected = NullPointerException.class) public void nullListInConstructor_throws() { new StaticKeyManagerFactorySpi(null); } @Test public void constructorCreatesArrayCopy() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); KeyManager[] arg = Arrays.copyOf(keyManagers, keyManagers.length); StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(arg); for (int i = 0; i < keyManagers.length; ++i) { arg[i] = null; } assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers); } @Test public void engineGetKeyManagers_returnsProvidedList() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); StaticKeyManagerFactorySpi spi = new StaticKeyManagerFactorySpi(keyManagers); assertThat(spi.engineGetKeyManagers()).containsExactly(keyManagers); } @Test(expected = UnsupportedOperationException.class) public void engineInit_storeAndPasswords_throws() { StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]); staticKeyManagerFactorySpi.engineInit(null, null); } @Test(expected = UnsupportedOperationException.class) public void engineInit_spec_throws() { StaticKeyManagerFactorySpi staticKeyManagerFactorySpi = new StaticKeyManagerFactorySpi(new KeyManager[0]); staticKeyManagerFactorySpi.engineInit(null); } }
1,322
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/internal/UnusedChannelExceptionHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.DefaultChannelId; import io.netty.util.Attribute; import java.io.IOException; import java.util.concurrent.CompletableFuture; import org.mockito.Mockito; import org.mockito.internal.verification.Times; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class UnusedChannelExceptionHandlerTest { private Throwable exception = new Throwable(); private IOException ioException = new IOException(); private ChannelHandlerContext ctx; private Channel channel; private Attribute<Boolean> inUseAttribute; private Attribute<CompletableFuture<Void>> futureAttribute; @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { ctx = Mockito.mock(ChannelHandlerContext.class); channel = Mockito.mock(Channel.class); Mockito.when(channel.id()).thenReturn(DefaultChannelId.newInstance()); inUseAttribute = Mockito.mock(Attribute.class); futureAttribute = Mockito.mock(Attribute.class); Mockito.when(ctx.channel()).thenReturn(channel); Mockito.when(channel.attr(ChannelAttributeKey.IN_USE)).thenReturn(inUseAttribute); Mockito.when(channel.attr(ChannelAttributeKey.EXECUTE_FUTURE_KEY)).thenReturn(futureAttribute); } @Test public void inUseDoesNothing() { Mockito.when(inUseAttribute.get()).thenReturn(true); UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception); Mockito.verify(ctx).fireExceptionCaught(exception); Mockito.verify(ctx, new Times(0)).close(); } @Test public void notInUseNonIoExceptionCloses() { notInUseCloses(exception); } @Test public void notInUseIoExceptionCloses() { notInUseCloses(ioException); } @Test public void notInUseHasIoExceptionCauseCloses() { notInUseCloses(new RuntimeException(ioException)); } private void notInUseCloses(Throwable exception) { Mockito.when(inUseAttribute.get()).thenReturn(false); Mockito.when(futureAttribute.get()).thenReturn(CompletableFuture.completedFuture(null)); UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception); Mockito.verify(ctx).close(); } @Test public void notInUseFutureCompletes() { CompletableFuture<Void> incompleteFuture = new CompletableFuture<>(); Mockito.when(inUseAttribute.get()).thenReturn(false); Mockito.when(futureAttribute.get()).thenReturn(incompleteFuture); UnusedChannelExceptionHandler.getInstance().exceptionCaught(ctx, exception); Mockito.verify(ctx).close(); assertThat(incompleteFuture.isDone()).isTrue(); } }
1,323
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/internal/OneTimeReadTimeoutHandlerTest.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 org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import java.time.Duration; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class OneTimeReadTimeoutHandlerTest { private static final long TIMEOUT_IN_MILLIS = 1000; private static OneTimeReadTimeoutHandler handler; @Mock private ChannelHandlerContext context; @Mock private ChannelPipeline channelPipeline; @Mock private Object object; @BeforeClass public static void setup() { handler = new OneTimeReadTimeoutHandler(Duration.ofMillis(TIMEOUT_IN_MILLIS)); } @Test public void channelRead_removesSelf() throws Exception { when(context.pipeline()).thenReturn(channelPipeline); handler.channelRead(context, object); verify(channelPipeline, times(1)).remove(eq(handler)); verify(context, times(1)).fireChannelRead(object); } }
1,324
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/internal/MockChannel.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.embedded.EmbeddedChannel; public class MockChannel extends EmbeddedChannel { public MockChannel() throws Exception { super.doRegister(); } public void runAllPendingTasks() throws InterruptedException { super.runPendingTasks(); while (runScheduledPendingTasks() != -1) { Thread.sleep(1); } } }
1,325
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/internal/PublisherAdapterTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTE_FUTURE_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.EmptyByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoopGroup; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.EmptyHttpHeaders; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.reactivex.Flowable; import java.net.URI; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.nio.netty.internal.nrs.DefaultStreamedHttpResponse; import software.amazon.awssdk.http.nio.netty.internal.nrs.StreamedHttpResponse; @RunWith(MockitoJUnitRunner.class) public class PublisherAdapterTest { @Mock private ChannelHandlerContext ctx; private MockChannel channel; @Mock private SdkChannelPool channelPool; @Mock private EventLoopGroup eventLoopGroup; @Mock private SdkAsyncHttpResponseHandler responseHandler; private HttpContent fullHttpResponse; private RequestContext requestContext; private CompletableFuture<Void> executeFuture; private ResponseHandler nettyResponseHandler; @Before public void setUp() throws Exception { executeFuture = new CompletableFuture<>(); fullHttpResponse = mock(DefaultHttpContent.class); when(fullHttpResponse.content()).thenReturn(new EmptyByteBuf(ByteBufAllocator.DEFAULT)); requestContext = new RequestContext(channelPool, eventLoopGroup, AsyncExecuteRequest.builder() .request(SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .build()) .responseHandler(responseHandler) .build(), null); channel = new MockChannel(); channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); channel.attr(REQUEST_CONTEXT_KEY).set(requestContext); channel.attr(EXECUTE_FUTURE_KEY).set(executeFuture); when(ctx.channel()).thenReturn(channel); nettyResponseHandler = ResponseHandler.getInstance(); DefaultHttpResponse defaultFullHttpResponse = mock(DefaultHttpResponse.class); when(defaultFullHttpResponse.headers()).thenReturn(EmptyHttpHeaders.INSTANCE); when(defaultFullHttpResponse.status()).thenReturn(HttpResponseStatus.CREATED); when(defaultFullHttpResponse.protocolVersion()).thenReturn(HttpVersion.HTTP_1_1); nettyResponseHandler.channelRead0(ctx, defaultFullHttpResponse); } @Test public void successfulStreaming_shouldNotInvokeChannelRead() { Flowable<HttpContent> testPublisher = Flowable.just(fullHttpResponse); StreamedHttpResponse streamedHttpResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED, testPublisher); ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedHttpResponse, ctx, requestContext, executeFuture ); TestSubscriber subscriber = new TestSubscriber(); publisherAdapter.subscribe(subscriber); verify(ctx, times(0)).read(); verify(ctx, times(0)).close(); assertThat(subscriber.isCompleted).isEqualTo(true); verify(channelPool).release(channel); executeFuture.join(); assertThat(executeFuture).isCompleted(); } @Test public void errorOccurred_shouldInvokeResponseHandler() { RuntimeException exception = new RuntimeException("boom"); Flowable<HttpContent> testPublisher = Flowable.error(exception); StreamedHttpResponse streamedHttpResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED, testPublisher); ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedHttpResponse, ctx, requestContext, executeFuture ); TestSubscriber subscriber = new TestSubscriber(); publisherAdapter.subscribe(subscriber); verify(ctx, times(0)).read(); verify(ctx).close(); assertThat(subscriber.errorOccurred).isEqualTo(true); verify(channelPool).release(channel); assertThat(executeFuture).isCompletedExceptionally(); verify(responseHandler).onError(exception); } @Test public void subscriptionCancelled_upstreamPublisherCallsOnNext_httpContentReleased() { HttpContent firstContent = mock(HttpContent.class); when(firstContent.content()).thenReturn(Unpooled.EMPTY_BUFFER); HttpContent[] contentToIgnore = new HttpContent[8]; for (int i = 0; i < contentToIgnore.length; ++i) { contentToIgnore[i] = mock(HttpContent.class); } Publisher<HttpContent> publisher = subscriber -> subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { // We ignore any cancel signal and just publish all the content subscriber.onNext(firstContent); for (int i = 0; i < l && i < contentToIgnore.length; ++i) { subscriber.onNext(contentToIgnore[i]); } } @Override public void cancel() { // no-op } }); DefaultStreamedHttpResponse streamedResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, publisher); Subscriber<ByteBuffer> subscriber = new Subscriber<ByteBuffer>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { subscription.cancel(); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }; ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedResponse, ctx, requestContext, executeFuture); publisherAdapter.subscribe(subscriber); // First one should be accessed as normal verify(firstContent).content(); verify(firstContent).release(); for (int i = 0; i < contentToIgnore.length; ++i) { verify(contentToIgnore[i]).release(); verifyNoMoreInteractions(contentToIgnore[i]); } } @Test public void contentLengthValidationFails_closesAndReleasesConnection() { channel.attr(ChannelAttributeKey.RESPONSE_CONTENT_LENGTH).set(1L); channel.attr(ChannelAttributeKey.RESPONSE_DATA_READ).set(0L); Publisher<HttpContent> publisher = subscriber -> subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { subscriber.onComplete(); } @Override public void cancel() { } }); DefaultStreamedHttpResponse streamedResponse = new DefaultStreamedHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, publisher); Subscriber<ByteBuffer> subscriber = new Subscriber<ByteBuffer>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }; ResponseHandler.PublisherAdapter publisherAdapter = new ResponseHandler.PublisherAdapter(streamedResponse, ctx, requestContext, executeFuture); publisherAdapter.subscribe(subscriber); verify(ctx).close(); verify(channelPool).release(channel); } static final class TestSubscriber implements Subscriber<ByteBuffer> { private Subscription subscription; private boolean isCompleted = false; private boolean errorOccurred = false; @Override public void onSubscribe(Subscription s) { this.subscription = s; subscription.request(1); } @Override public void onNext(ByteBuffer byteBuffer) { subscription.request(1); } @Override public void onError(Throwable t) { errorOccurred = true; } @Override public void onComplete() { isCompleted = true; } } }
1,326
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/internal/BootstrapProviderTest.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 org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TCP_KEEPALIVE; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelOption; import java.net.InetSocketAddress; import java.net.SocketAddress; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; import software.amazon.awssdk.utils.AttributeMap; @RunWith(MockitoJUnitRunner.class) public class BootstrapProviderTest { private final BootstrapProvider bootstrapProvider = new BootstrapProvider(SdkEventLoopGroup.builder().build(), new NettyConfiguration(GLOBAL_HTTP_DEFAULTS), new SdkChannelOptions()); // IMPORTANT: This unit test asserts that the bootstrap provider creates bootstraps using 'unresolved // InetSocketAddress'. If this test is replaced or removed, perhaps due to a different implementation of // SocketAddress, a different test must be created that ensures that the hostname will be resolved on every // connection attempt and not cached between connection attempts. @Test public void createBootstrap_usesUnresolvedInetSocketAddress() { Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false); SocketAddress socketAddress = bootstrap.config().remoteAddress(); assertThat(socketAddress).isInstanceOf(InetSocketAddress.class); InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress; assertThat(inetSocketAddress.isUnresolved()).isTrue(); } @Test public void createBootstrapNonBlockingDns_usesUnresolvedInetSocketAddress() { Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, true); SocketAddress socketAddress = bootstrap.config().remoteAddress(); assertThat(socketAddress).isInstanceOf(InetSocketAddress.class); InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress; assertThat(inetSocketAddress.isUnresolved()).isTrue(); } @Test public void createBootstrap_defaultConfiguration_tcpKeepAliveShouldBeFalse() { Bootstrap bootstrap = bootstrapProvider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false); Boolean keepAlive = (Boolean) bootstrap.config().options().get(ChannelOption.SO_KEEPALIVE); assertThat(keepAlive).isFalse(); } @Test public void createBootstrap_tcpKeepAliveTrue_shouldApply() { NettyConfiguration nettyConfiguration = new NettyConfiguration(AttributeMap.builder().put(TCP_KEEPALIVE, true) .build().merge(GLOBAL_HTTP_DEFAULTS)); BootstrapProvider provider = new BootstrapProvider(SdkEventLoopGroup.builder().build(), nettyConfiguration, new SdkChannelOptions()); Bootstrap bootstrap = provider.createBootstrap("some-awesome-service-1234.amazonaws.com", 443, false); Boolean keepAlive = (Boolean) bootstrap.config().options().get(ChannelOption.SO_KEEPALIVE); assertThat(keepAlive).isTrue(); } }
1,327
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/internal/DnsResolverLoaderTest.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 org.assertj.core.api.Assertions.assertThat; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.oio.OioDatagramChannel; import io.netty.resolver.dns.DnsAddressResolverGroup; import org.junit.jupiter.api.Test; public class DnsResolverLoaderTest { @Test public void canResolveChannelFactory() { assertThat(DnsResolverLoader.init(NioDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class); assertThat(DnsResolverLoader.init(EpollDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class); assertThat(DnsResolverLoader.init(OioDatagramChannel::new)).isInstanceOf(DnsAddressResolverGroup.class); } }
1,328
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/internal/AwaitCloseChannelPoolMapTest.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 com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER; import com.github.tomakehurst.wiremock.junit.WireMockRule; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.handler.ssl.SslProvider; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.Future; import java.net.URI; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.TlsKeyManagersProvider; import software.amazon.awssdk.http.nio.netty.ProxyConfiguration; import software.amazon.awssdk.http.nio.netty.RecordingNetworkTrafficListener; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; import software.amazon.awssdk.utils.AttributeMap; public class AwaitCloseChannelPoolMapTest { private final RecordingNetworkTrafficListener recorder = new RecordingNetworkTrafficListener(); private AwaitCloseChannelPoolMap channelPoolMap; @Rule public WireMockRule mockProxy = new WireMockRule(wireMockConfig() .dynamicPort() .networkTrafficListener(recorder)); @After public void methodTeardown() { if (channelPoolMap != null) { channelPoolMap.close(); } channelPoolMap = null; recorder.reset(); } @Test public void close_underlyingPoolsShouldBeClosed() { channelPoolMap = AwaitCloseChannelPoolMap.builder() .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL) .build(); int numberOfChannelPools = 5; List<SimpleChannelPoolAwareChannelPool> channelPools = new ArrayList<>(); for (int i = 0; i < numberOfChannelPools; i++) { channelPools.add( channelPoolMap.get(URI.create("http://" + RandomStringUtils.randomAlphabetic(2) + i + "localhost:" + numberOfChannelPools))); } assertThat(channelPoolMap.pools().size()).isEqualTo(numberOfChannelPools); channelPoolMap.close(); channelPools.forEach(channelPool -> { assertThat(channelPool.underlyingSimpleChannelPool().closeFuture()).isDone(); assertThat(channelPool.underlyingSimpleChannelPool().closeFuture().join()).isTrue(); }); } @Test public void get_callsInjectedBootstrapProviderCorrectly() { BootstrapProvider bootstrapProvider = Mockito.spy( new BootstrapProvider(SdkEventLoopGroup.builder().build(), new NettyConfiguration(GLOBAL_HTTP_DEFAULTS), new SdkChannelOptions())); URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080"); AwaitCloseChannelPoolMap.Builder builder = AwaitCloseChannelPoolMap.builder() .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL); channelPoolMap = new AwaitCloseChannelPoolMap(builder, null, bootstrapProvider); channelPoolMap.get(targetUri); verify(bootstrapProvider).createBootstrap("some-awesome-service-1234.amazonaws.com", 8080, null); } @Test public void get_usingProxy_callsInjectedBootstrapProviderCorrectly() { BootstrapProvider bootstrapProvider = Mockito.spy( new BootstrapProvider(SdkEventLoopGroup.builder().build(), new NettyConfiguration(GLOBAL_HTTP_DEFAULTS), new SdkChannelOptions())); URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080"); Map<URI, Boolean> shouldProxyCache = new HashMap<>(); shouldProxyCache.put(targetUri, true); ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder() .host("localhost") .port(mockProxy.port()) .build(); AwaitCloseChannelPoolMap.Builder builder = AwaitCloseChannelPoolMap.builder() .proxyConfiguration(proxyConfiguration) .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL); channelPoolMap = new AwaitCloseChannelPoolMap(builder, shouldProxyCache, bootstrapProvider); channelPoolMap.get(targetUri); verify(bootstrapProvider).createBootstrap("localhost", mockProxy.port(), null); } @Test public void usingProxy_usesCachedValueWhenPresent() { URI targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com"); Map<URI, Boolean> shouldProxyCache = new HashMap<>(); shouldProxyCache.put(targetUri, true); ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder() .host("localhost") .port(mockProxy.port()) // Deliberately set the target host as a non-proxy host to // see if it will check the cache first .nonProxyHosts(Stream.of(targetUri.getHost()).collect(Collectors.toSet())) .build(); AwaitCloseChannelPoolMap.Builder builder = AwaitCloseChannelPoolMap.builder() .proxyConfiguration(proxyConfiguration) .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL); channelPoolMap = new AwaitCloseChannelPoolMap(builder, shouldProxyCache, null); // The target host does not exist so acquiring a channel should fail unless we're configured to connect to // the mock proxy host for this URI. SimpleChannelPoolAwareChannelPool channelPool = channelPoolMap.newPool(targetUri); Future<Channel> channelFuture = channelPool.underlyingSimpleChannelPool().acquire().awaitUninterruptibly(); assertThat(channelFuture.isSuccess()).isTrue(); channelPool.release(channelFuture.getNow()).awaitUninterruptibly(); } @Test public void usingProxy_noSchemeGiven_defaultsToHttp() { ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder() .host("localhost") .port(mockProxy.port()) .build(); channelPoolMap = AwaitCloseChannelPoolMap.builder() .proxyConfiguration(proxyConfiguration) .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL) .build(); SimpleChannelPoolAwareChannelPool simpleChannelPoolAwareChannelPool = channelPoolMap.newPool( URI.create("https://some-awesome-service:443")); simpleChannelPoolAwareChannelPool.acquire().awaitUninterruptibly(); String requests = recorder.requests().toString(); assertThat(requests).contains("CONNECT some-awesome-service:443"); } @Test public void usingProxy_withAuth() { ProxyConfiguration proxyConfiguration = ProxyConfiguration.builder() .host("localhost") .port(mockProxy.port()) .username("myuser") .password("mypassword") .build(); channelPoolMap = AwaitCloseChannelPoolMap.builder() .proxyConfiguration(proxyConfiguration) .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL) .build(); SimpleChannelPoolAwareChannelPool simpleChannelPoolAwareChannelPool = channelPoolMap.newPool( URI.create("https://some-awesome-service:443")); simpleChannelPoolAwareChannelPool.acquire().awaitUninterruptibly(); String requests = recorder.requests().toString(); assertThat(requests).contains("CONNECT some-awesome-service:443"); String authB64 = Base64.getEncoder().encodeToString("myuser:mypassword".getBytes(CharsetUtil.UTF_8)); String authHeaderValue = String.format("Basic %s", authB64); assertThat(requests).contains(String.format("proxy-authorization: %s", authHeaderValue)); } @Test public void usesProvidedKeyManagersProvider() { TlsKeyManagersProvider provider = mock(TlsKeyManagersProvider.class); AttributeMap config = AttributeMap.builder() .put(TLS_KEY_MANAGERS_PROVIDER, provider) .build(); channelPoolMap = AwaitCloseChannelPoolMap.builder() .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .protocol(Protocol.HTTP1_1) .configuration(new NettyConfiguration(config.merge(GLOBAL_HTTP_DEFAULTS))) .build(); ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port())); channelPool.acquire().awaitUninterruptibly(); verify(provider).keyManagers(); } @Test public void acquireChannel_autoReadDisabled() { channelPoolMap = AwaitCloseChannelPoolMap.builder() .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL) .build(); ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port())); Channel channel = channelPool.acquire().awaitUninterruptibly().getNow(); assertThat(channel.config().isAutoRead()).isFalse(); } @Test public void releaseChannel_autoReadEnabled() { channelPoolMap = AwaitCloseChannelPoolMap.builder() .sdkChannelOptions(new SdkChannelOptions()) .sdkEventLoopGroup(SdkEventLoopGroup.builder().build()) .configuration(new NettyConfiguration(GLOBAL_HTTP_DEFAULTS)) .protocol(Protocol.HTTP1_1) .maxStreams(100) .sslProvider(SslProvider.OPENSSL) .build(); ChannelPool channelPool = channelPoolMap.newPool(URI.create("https://localhost:" + mockProxy.port())); Channel channel = channelPool.acquire().awaitUninterruptibly().getNow(); channelPool.release(channel).awaitUninterruptibly(); assertThat(channel.config().isAutoRead()).isTrue(); } }
1,329
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/internal/HonorCloseOnReleaseChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import io.netty.channel.Channel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.internal.verification.Times; public class HonorCloseOnReleaseChannelPoolTest { @Test public void releaseDoesntCloseIfNotFlagged() throws Exception { ChannelPool channelPool = Mockito.mock(ChannelPool.class); MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(false); new HonorCloseOnReleaseChannelPool(channelPool).release(channel); channel.runAllPendingTasks(); assertThat(channel.isOpen()).isTrue(); Mockito.verify(channelPool, new Times(0)).release(any()); Mockito.verify(channelPool, new Times(1)).release(any(), any()); } @Test public void releaseClosesIfFlagged() throws Exception { ChannelPool channelPool = Mockito.mock(ChannelPool.class); MockChannel channel = new MockChannel(); channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).set(true); new HonorCloseOnReleaseChannelPool(channelPool).release(channel); channel.runAllPendingTasks(); assertThat(channel.isOpen()).isFalse(); Mockito.verify(channelPool, new Times(0)).release(any()); Mockito.verify(channelPool, new Times(1)).release(any(), any()); } @Test public void release_delegateReleaseFails_futureFailed() throws Exception { NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(); try { ChannelPool mockDelegatePool = Mockito.mock(ChannelPool.class); MockChannel channel = new MockChannel(); nioEventLoopGroup.register(channel); HonorCloseOnReleaseChannelPool channelPool = new HonorCloseOnReleaseChannelPool(mockDelegatePool); RuntimeException errorToThrow = new RuntimeException("failed!"); when(mockDelegatePool.release(any(Channel.class), any(Promise.class))).thenThrow(errorToThrow); Promise<Void> promise = channel.eventLoop().newPromise(); Future<Void> releasePromise = channelPool.release(channel, promise); try { releasePromise.get(1, TimeUnit.SECONDS); } catch (Exception e) { if (e instanceof InterruptedException) { throw e; } // ignore any other exception } assertThat(releasePromise.isSuccess()).isFalse(); assertThat(releasePromise.cause()).isSameAs(errorToThrow); } finally { nioEventLoopGroup.shutdownGracefully(); } } }
1,330
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/internal/ResponseCompletionTest.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 io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE; import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; 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.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpVersion; 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.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.RandomStringUtils; 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.utils.AttributeMap; public class ResponseCompletionTest { private SdkAsyncHttpClient netty; private Server server; @AfterEach public void teardown() throws InterruptedException { if (server != null) { server.shutdown(); } server = null; if (netty != null) { netty.close(); } netty = null; } @Test public void connectionCloseAfterResponse_shouldNotReuseConnection() throws Exception { server = new Server(); server.init(); netty = NettyNioAsyncHttpClient.builder() .eventLoopGroup(SdkEventLoopGroup.builder().numberOfThreads(2).build()) .protocol(Protocol.HTTP1_1) .buildWithDefaults(AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true).build()); sendGetRequest().join(); sendGetRequest().join(); assertThat(server.channels.size()).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<SocketChannel> { private static final byte[] CONTENT = RandomStringUtils.randomAscii(7000).getBytes(); private ServerBootstrap bootstrap; private ServerSocketChannel serverSock; private List<SocketChannel> channels = new ArrayList<>(); private final NioEventLoopGroup group = new NioEventLoopGroup(); private SslContext sslCtx; public void init() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); bootstrap = new ServerBootstrap() .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)) .group(group) .childHandler(this); serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel(); } @Override protected void initChannel(SocketChannel ch) throws Exception { channels.add(ch); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new AlwaysCloseConnectionChannelHandler()); } public void shutdown() throws InterruptedException { group.shutdownGracefully().await(); } public int port() { return serverSock.localAddress().getPort(); } private static class AlwaysCloseConnectionChannelHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers() .set(CONTENT_TYPE, TEXT_PLAIN) .set(CONNECTION, CLOSE) .setInt(CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response).addListener(i -> ctx.channel().close()); } } } } }
1,331
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/internal/SslContextProviderTest.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 org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; import io.netty.handler.codec.http2.Http2SecurityUtil; import io.netty.handler.ssl.SslProvider; import javax.net.ssl.TrustManager; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.TlsKeyManagersProvider; import software.amazon.awssdk.http.TlsTrustManagersProvider; import software.amazon.awssdk.utils.AttributeMap; public class SslContextProviderTest { @Test public void sslContext_h2WithJdk_h2CiphersShouldBeUsed() { SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS), Protocol.HTTP2, SslProvider.JDK); assertThat(sslContextProvider.sslContext().cipherSuites()).isSubsetOf(Http2SecurityUtil.CIPHERS); } @Test public void sslContext_h2WithOpenSsl_h2CiphersShouldBeUsed() { SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS), Protocol.HTTP2, SslProvider.OPENSSL); assertThat(sslContextProvider.sslContext().cipherSuites()).isSubsetOf(Http2SecurityUtil.CIPHERS); } @Test public void sslContext_h1_defaultCipherShouldBeUsed() { SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS), Protocol.HTTP1_1, SslProvider.JDK); assertThat(sslContextProvider.sslContext().cipherSuites()).isNotIn(Http2SecurityUtil.CIPHERS); } @Test public void customizedKeyManagerPresent_shouldUseCustomized() { TlsKeyManagersProvider mockProvider = Mockito.mock(TlsKeyManagersProvider.class); SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(AttributeMap.builder() .put(TRUST_ALL_CERTIFICATES, false) .put(TLS_KEY_MANAGERS_PROVIDER, mockProvider) .build()), Protocol.HTTP1_1, SslProvider.JDK); sslContextProvider.sslContext(); Mockito.verify(mockProvider).keyManagers(); } @Test public void customizedTrustManagerPresent_shouldUseCustomized() { TlsTrustManagersProvider mockProvider = Mockito.mock(TlsTrustManagersProvider.class); TrustManager mockTrustManager = Mockito.mock(TrustManager.class); Mockito.when(mockProvider.trustManagers()).thenReturn(new TrustManager[] {mockTrustManager}); SslContextProvider sslContextProvider = new SslContextProvider(new NettyConfiguration(AttributeMap.builder() .put(TRUST_ALL_CERTIFICATES, false) .put(TLS_TRUST_MANAGERS_PROVIDER, mockProvider) .build()), Protocol.HTTP1_1, SslProvider.JDK); sslContextProvider.sslContext(); Mockito.verify(mockProvider).trustManagers(); } @Test public void TlsTrustManagerAndTrustAllCertificates_shouldThrowException() { TlsTrustManagersProvider mockProvider = Mockito.mock(TlsTrustManagersProvider.class); assertThatThrownBy(() -> new SslContextProvider(new NettyConfiguration(AttributeMap.builder() .put(TRUST_ALL_CERTIFICATES, true) .put(TLS_TRUST_MANAGERS_PROVIDER, mockProvider) .build()), Protocol.HTTP1_1, SslProvider.JDK)).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("A TlsTrustManagerProvider can't" + " be provided if " + "TrustAllCertificates is also " + "set"); } }
1,332
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/internal/InUseTrackingChannelPoolListenerTest.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 org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE; import io.netty.channel.Channel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class InUseTrackingChannelPoolListenerTest { Channel mockChannel; InUseTrackingChannelPoolListener handler; @BeforeEach void setUp() throws Exception { mockChannel = new MockChannel(); handler = InUseTrackingChannelPoolListener.create(); } @Test void channelAcquired() { mockChannel.attr(IN_USE).set(false); handler.channelAcquired(mockChannel); assertThat(mockChannel.attr(IN_USE).get()).isTrue(); } @Test void channelReleased() { mockChannel.attr(IN_USE).set(true); handler.channelReleased(mockChannel); assertThat(mockChannel.attr(IN_USE).get()).isFalse(); } }
1,333
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/internal/FullResponseContentPublisherTckTest.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 org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.BeforeMethod; /** * TCK verification test for {@link software.amazon.awssdk.http.nio.netty.internal.ResponseHandler.FullResponseContentPublisher}. */ public class FullResponseContentPublisherTckTest extends PublisherVerification<ByteBuffer> { private static final byte[] CONTENT = new byte[16]; private CompletableFuture<Void> executeFuture; private ChannelHandlerContext mockCtx = mock(ChannelHandlerContext.class); @SuppressWarnings("unchecked") @BeforeMethod public void methodSetup() { Channel chan = mock(Channel.class); when(mockCtx.channel()).thenReturn(chan); when(chan.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class)); executeFuture = new CompletableFuture<>(); } public FullResponseContentPublisherTckTest() { super(new TestEnvironment()); } // This is a one-shot publisher @Override public long maxElementsFromPublisher() { return 1; } @Override public Publisher<ByteBuffer> createPublisher(long l) { return new ResponseHandler.FullResponseContentPublisher(mockCtx, ByteBuffer.wrap(CONTENT), executeFuture); } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } }
1,334
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/internal/ConnectionReaperTest.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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.Options; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.time.Duration; import java.time.Instant; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.internal.verification.AtLeast; import org.mockito.internal.verification.Times; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.ConnectionCountingTrafficListener; import software.amazon.awssdk.http.EmptyPublisher; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.RecordingResponseHandler; @RunWith(MockitoJUnitRunner.class) public class ConnectionReaperTest { private static final ConnectionCountingTrafficListener TRAFFIC_LISTENER = new ConnectionCountingTrafficListener(); @Rule public final WireMockRule mockServer = new WireMockRule(wireMockConfig().dynamicPort() .dynamicHttpsPort() .networkTrafficListener(TRAFFIC_LISTENER)); @Test public void idleConnectionReaperDoesNotReapActiveConnections() throws InterruptedException { Duration maxIdleTime = Duration.ofSeconds(2); try(SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder() .connectionMaxIdleTime(maxIdleTime) .buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) { Instant end = Instant.now().plus(maxIdleTime.plusSeconds(1)); // Send requests for longer than the max-idle time, ensuring no connections are closed. int connectionCount = TRAFFIC_LISTENER.openedConnections(); while (Instant.now().isBefore(end)) { makeRequest(client); Thread.sleep(100); } assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 1); // Do nothing for longer than the max-idle time, ensuring connections are closed. Thread.sleep(maxIdleTime.plusSeconds(1).toMillis()); makeRequest(client); assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 2); } } @Test public void oldConnectionReaperReapsActiveConnections() throws InterruptedException { Duration connectionTtl = Duration.ofMillis(200); try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder() .connectionTimeToLive(connectionTtl) .buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) { Instant end = Instant.now().plus(Duration.ofSeconds(5)); int connectionCount = TRAFFIC_LISTENER.openedConnections(); // Send requests frequently, validating that new connections are being opened. while (Instant.now().isBefore(end)) { makeRequest(client); Thread.sleep(100); } assertThat(TRAFFIC_LISTENER.openedConnections()).isGreaterThanOrEqualTo(connectionCount + 15); } } @Test public void noReapingWorks() throws InterruptedException { try (SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofMillis(10)) .useIdleConnectionReaper(false) .buildWithDefaults(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)) { int connectionCount = TRAFFIC_LISTENER.openedConnections(); makeRequest(client); Thread.sleep(2_000); makeRequest(client); assertThat(TRAFFIC_LISTENER.openedConnections()).isEqualTo(connectionCount + 1); } } private void makeRequest(SdkAsyncHttpClient client) { stubFor(WireMock.any(anyUrl()).willReturn(aResponse().withBody(randomAlphabetic(10)))); RecordingResponseHandler handler = new RecordingResponseHandler(); URI uri = URI.create("http://localhost:" + mockServer.port()); client.execute(AsyncExecuteRequest.builder() .request(SdkHttpRequest.builder() .uri(uri) .method(SdkHttpMethod.GET) .encodedPath("/") .putHeader("Host", uri.getHost()) .putHeader("Content-Length", "0") .build()) .requestContentPublisher(new EmptyPublisher()) .responseHandler(handler) .build()) .join(); assertThat(handler.fullResponseAsString()).hasSize(10); } }
1,335
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/internal/ChannelDiagnosticsTest.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 org.assertj.core.api.Assertions.assertThat; import io.netty.channel.embedded.EmbeddedChannel; import java.time.Duration; import org.junit.jupiter.api.Test; public class ChannelDiagnosticsTest { @Test public void stopIdleTimer_noPreviousCallToStartIdleTimer_noDurationCalculated() { ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel()); cd.stopIdleTimer(); assertThat(cd.lastIdleDuration()).isNull(); } @Test public void stopIdleTimer_previousCallToStartIdleTimer_durationCalculated() { ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel()); cd.startIdleTimer(); cd.stopIdleTimer(); assertThat(cd.lastIdleDuration().toNanos()).isPositive(); } @Test public void incrementResponseCount_reflectsCorrectValue() { ChannelDiagnostics cd = new ChannelDiagnostics(new EmbeddedChannel()); int count = 42; for (int i = 0; i < count; ++i) { cd.incrementResponseCount(); } assertThat(cd.responseCount()).isEqualTo(count); } }
1,336
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/internal/SdkChannelOptionsTest.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 org.junit.jupiter.api.Assertions.assertEquals; import io.netty.channel.ChannelOption; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class SdkChannelOptionsTest { @Test public void defaultSdkSocketOptionPresent() { SdkChannelOptions channelOptions = new SdkChannelOptions(); Map<ChannelOption, Object> expectedOptions = new HashMap<>(); expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); assertEquals(expectedOptions, channelOptions.channelOptions()); } @Test public void additionalSdkSocketOptionsPresent() { SdkChannelOptions channelOptions = new SdkChannelOptions(); channelOptions.putOption(ChannelOption.SO_LINGER, 0); Map<ChannelOption, Object> expectedOptions = new HashMap<>(); expectedOptions.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); expectedOptions.put(ChannelOption.SO_LINGER, 0); assertEquals(expectedOptions, channelOptions.channelOptions()); } }
1,337
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/internal/LastHttpContentSwallowerTest.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 org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.LastHttpContent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for {@link LastHttpContentSwallower}. */ public class LastHttpContentSwallowerTest { private final LastHttpContentSwallower lastHttpContentSwallower = LastHttpContentSwallower.getInstance(); private ChannelHandlerContext mockCtx; private ChannelPipeline mockPipeline; @BeforeEach public void setUp() { mockCtx = mock(ChannelHandlerContext.class); mockPipeline = mock(ChannelPipeline.class); when(mockCtx.pipeline()).thenReturn(mockPipeline); } @Test public void testOtherHttpObjectRead_removesSelfFromPipeline() { HttpObject contentObject = mock(HttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, contentObject); verify(mockPipeline).remove(eq(lastHttpContentSwallower)); } @Test public void testLastHttpContentRead_removesSelfFromPipeline() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockPipeline).remove(eq(lastHttpContentSwallower)); } @Test public void testLastHttpContentRead_swallowsObject() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockCtx, times(0)).fireChannelRead(eq(lastContent)); } @Test public void testOtherHttpObjectRead_doesNotSwallowObject() { HttpContent content = mock(HttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, content); verify(mockCtx).fireChannelRead(eq(content)); } @Test public void testCallsReadAfterSwallowingContent() { LastHttpContent lastContent = mock(LastHttpContent.class); lastHttpContentSwallower.channelRead0(mockCtx, lastContent); verify(mockCtx).read(); } }
1,338
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/internal/StaticKeyManagerFactoryTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.stream.IntStream; import javax.net.ssl.KeyManager; import org.junit.jupiter.api.Test; /** * Tests for {@link StaticKeyManagerFactory}. */ public class StaticKeyManagerFactoryTest { @Test public void createReturnFactoryWithCorrectKeyManagers() { KeyManager[] keyManagers = IntStream.range(0,8) .mapToObj(i -> mock(KeyManager.class)) .toArray(KeyManager[]::new); StaticKeyManagerFactory staticKeyManagerFactory = StaticKeyManagerFactory.create(keyManagers); assertThat(staticKeyManagerFactory.getKeyManagers()) .containsExactly(keyManagers); } }
1,339
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/internal/ChannelPipelineInitializerTest.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 org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.pool.ChannelPool; 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 java.net.URI; import java.time.Duration; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLException; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.Protocol; public class ChannelPipelineInitializerTest { private ChannelPipelineInitializer pipelineInitializer; private URI targetUri; @Test public void channelConfigOptionCheck() throws SSLException { targetUri = URI.create("https://some-awesome-service-1234.amazonaws.com:8080"); SslContext sslContext = SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .build(); AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>(); NettyConfiguration nettyConfiguration = new NettyConfiguration(GLOBAL_HTTP_DEFAULTS); pipelineInitializer = new ChannelPipelineInitializer(Protocol.HTTP1_1, sslContext, SslProvider.JDK, 100, 1024, Duration.ZERO, channelPoolRef, nettyConfiguration, targetUri); Channel channel = new EmbeddedChannel(); pipelineInitializer.channelCreated(channel); assertThat(channel.config().getOption(ChannelOption.ALLOCATOR), is(UnpooledByteBufAllocator.DEFAULT)); } }
1,340
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/internal/Http1TunnelConnectionPoolTest.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 org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.Http1TunnelConnectionPool.TUNNEL_ESTABLISHED_KEY; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelId; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.handler.ssl.ApplicationProtocolNegotiator; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.Attribute; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.CountDownLatch; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSessionContext; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.SdkHttpConfigurationOption; /** * Unit tests for {@link Http1TunnelConnectionPool}. */ @RunWith(MockitoJUnitRunner.class) public class Http1TunnelConnectionPoolTest { private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1); private static final URI HTTP_PROXY_ADDRESS = URI.create("http://localhost:1234"); private static final URI HTTPS_PROXY_ADDRESS = URI.create("https://localhost:5678"); private static final URI REMOTE_ADDRESS = URI.create("https://s3.amazonaws.com:5678"); private static final String PROXY_USER = "myuser"; private static final String PROXY_PASSWORD = "mypassword"; @Mock private ChannelPool delegatePool; @Mock private ChannelPoolHandler mockHandler; @Mock public Channel mockChannel; @Mock public ChannelPipeline mockPipeline; @Mock public Attribute mockAttr; @Mock public ChannelHandlerContext mockCtx; @Mock public ChannelId mockId; public NettyConfiguration configuration; @Before public void methodSetup() { Future<Channel> channelFuture = GROUP.next().newSucceededFuture(mockChannel); when(delegatePool.acquire(any(Promise.class))).thenReturn(channelFuture); when(mockChannel.attr(eq(TUNNEL_ESTABLISHED_KEY))).thenReturn(mockAttr); when(mockChannel.id()).thenReturn(mockId); when(mockChannel.pipeline()).thenReturn(mockPipeline); configuration = new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS); } @AfterClass public static void teardown() { GROUP.shutdownGracefully().awaitUninterruptibly(); } @Test public void tunnelAlreadyEstablished_doesNotAddInitHandler() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(mockAttr.get()).thenReturn(true); tunnelPool.acquire().awaitUninterruptibly(); verify(mockPipeline, never()).addLast(any()); } @Test(timeout = 1000) public void tunnelNotEstablished_addsInitHandler() throws InterruptedException { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(mockAttr.get()).thenReturn(false); CountDownLatch latch = new CountDownLatch(1); when(mockPipeline.addLast(any(ChannelHandler.class))).thenAnswer(i -> { latch.countDown(); return mockPipeline; }); tunnelPool.acquire(); latch.await(); verify(mockPipeline, times(1)).addLast(any(ProxyTunnelInitHandler.class)); } @Test public void tunnelInitFails_acquireFutureFails() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setFailure(new IOException("boom")); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS,null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } @Test public void tunnelInitSucceeds_acquireFutureSucceeds() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().getNow()).isEqualTo(mockChannel); } @Test public void acquireFromDelegatePoolFails_failsFuture() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(delegatePool.acquire(any(Promise.class))).thenReturn(GROUP.next().newFailedFuture(new IOException("boom"))); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } @Test public void sslContextProvided_andProxyUsingHttps_addsSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); SSLEngine mockSslEngine = mock(SSLEngine.class); when(mockSslHandler.engine()).thenReturn(mockSslEngine); when(mockSslEngine.getSSLParameters()).thenReturn(mock(SSLParameters.class)); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTPS_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline, times(2)).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler); } @Test public void sslContextProvided_andProxyNotUsingHttps_doesNotAddSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isNotInstanceOf(SslHandler.class); } @Test public void release_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); tunnelPool.release(mockChannel); verify(delegatePool).release(eq(mockChannel), any(Promise.class)); } @Test public void release_withGivenPromise_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); Promise mockPromise = mock(Promise.class); tunnelPool.release(mockChannel, mockPromise); verify(delegatePool).release(eq(mockChannel), eq(mockPromise)); } @Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); tunnelPool.close(); verify(delegatePool).close(); } @Test public void proxyAuthProvided_addInitHandler_withAuth(){ TestInitHandlerData data = new TestInitHandlerData(); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); data.proxyUser(proxyUser); data.proxyPassword(proxyPassword); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, PROXY_USER, PROXY_PASSWORD, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); assertThat(data.proxyUser()).isEqualTo(PROXY_USER); assertThat(data.proxyPassword()).isEqualTo(PROXY_PASSWORD); } private static class TestInitHandlerData { private String proxyUser; private String proxyPassword; public void proxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String proxyUser() { return this.proxyUser; } public void proxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } public String proxyPassword(){ return this.proxyPassword; } } private static class TestSslContext extends SslContext { private final SslHandler handler; protected TestSslContext(SslHandler handler) { this.handler = handler; } @Override public boolean isClient() { return false; } @Override public List<String> cipherSuites() { return null; } @Override public long sessionCacheSize() { return 0; } @Override public long sessionTimeout() { return 0; } @Override public ApplicationProtocolNegotiator applicationProtocolNegotiator() { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc) { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) { return null; } @Override public SSLSessionContext sessionContext() { return null; } @Override public SslHandler newHandler(ByteBufAllocator alloc, String host, int port, boolean startTls) { return handler; } } }
1,341
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/internal/RequestAdapterTest.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 org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; 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.HttpVersion; import io.netty.handler.codec.http2.HttpConversionUtil; import java.net.URI; import java.util.List; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; public class RequestAdapterTest { private final RequestAdapter h1Adapter = new RequestAdapter(Protocol.HTTP1_1); private final RequestAdapter h2Adapter = new RequestAdapter(Protocol.HTTP2); @Test public void adapt_h1Request_requestIsCorrect() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/foo/bar/baz")) .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET")); assertThat(adapted.uri()).isEqualTo("/foo/bar/baz?foo=bar&bar=baz"); assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1); assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345"); assertThat(adapted.headers().getAll("header1")).containsExactly("header1val"); assertThat(adapted.headers().getAll("header2")).containsExactly("header2val"); } @Test public void adapt_h2Request_addsSchemeExtension() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/foo/bar/baz")) .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h2Adapter.adapt(request); assertThat(adapted.headers().getAll(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text())).containsExactly("http"); } @Test public void adapt_noPathContainsQueryParams() { SdkHttpRequest request = SdkHttpRequest.builder() .host("localhost:12345") .protocol("http") .putRawQueryParameter("foo", "bar") .putRawQueryParameter("bar", "baz") .putHeader("header1", "header1val") .putHeader("header2", "header2val") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.method()).isEqualTo(HttpMethod.valueOf("GET")); assertThat(adapted.uri()).isEqualTo("/?foo=bar&bar=baz"); assertThat(adapted.protocolVersion()).isEqualTo(HttpVersion.HTTP_1_1); assertThat(adapted.headers().getAll("Host")).containsExactly("localhost:12345"); } @Test public void adapt_hostHeaderSet() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345/")) .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:12345"); } @Test public void adapt_standardHttpsPort_omittedInHeader() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https://localhost:443/")) .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost"); } @Test public void adapt_containsQueryParamsRequiringEncoding() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345")) .putRawQueryParameter("java", "☕") .putRawQueryParameter("python", "\uD83D\uDC0D") .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.uri()).isEqualTo("/?java=%E2%98%95&python=%F0%9F%90%8D"); } @Test public void adapt_pathEmpty_setToRoot() { SdkHttpRequest request = SdkHttpRequest.builder() .uri(URI.create("http://localhost:12345")) .method(SdkHttpMethod.GET) .build(); HttpRequest adapted = h1Adapter.adapt(request); assertThat(adapted.uri()).isEqualTo("/"); } @Test public void adapt_defaultPortUsed() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:80/")) .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.size()); assertEquals("localhost", hostHeaders.get(0)); sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https://localhost:443/")) .method(SdkHttpMethod.HEAD) .build(); result = h1Adapter.adapt(sdkRequest); hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertNotNull(hostHeaders); assertEquals(1, hostHeaders.size()); assertEquals("localhost", hostHeaders.get(0)); } @Test public void adapt_nonStandardHttpPort() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("http://localhost:8080/")) .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:8080"); } @Test public void adapt_nonStandardHttpsPort() { SdkHttpRequest sdkRequest = SdkHttpRequest.builder() .uri(URI.create("https://localhost:8443/")) .method(SdkHttpMethod.HEAD) .build(); HttpRequest result = h1Adapter.adapt(sdkRequest); List<String> hostHeaders = result.headers() .getAll(HttpHeaderNames.HOST.toString()); assertThat(hostHeaders).containsExactly("localhost:8443"); } }
1,342
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/internal/IdleConnectionCountingChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.metrics.MetricCollector; public class IdleConnectionCountingChannelPoolTest { private EventLoopGroup eventLoopGroup; private ChannelPool delegatePool; private IdleConnectionCountingChannelPool idleCountingPool; @Before public void setup() { delegatePool = mock(ChannelPool.class); eventLoopGroup = new NioEventLoopGroup(4); idleCountingPool = new IdleConnectionCountingChannelPool(eventLoopGroup.next(), delegatePool); } @After public void teardown() { eventLoopGroup.shutdownGracefully(); } @Test(timeout = 5_000) public void acquiresAndReleasesOfNewChannelsIncreaseCount() throws InterruptedException { stubDelegatePoolAcquires(createSuccessfulAcquire(), createSuccessfulAcquire()); stubDelegatePoolReleasesForSuccess(); assertThat(getIdleConnectionCount()).isEqualTo(0); Channel firstChannel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); Channel secondChannel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(firstChannel).await(); assertThat(getIdleConnectionCount()).isEqualTo(1); idleCountingPool.release(secondChannel).await(); assertThat(getIdleConnectionCount()).isEqualTo(2); } @Test(timeout = 5_000) public void channelsClosedInTheDelegatePoolAreNotCounted() throws InterruptedException { stubDelegatePoolAcquires(createSuccessfulAcquire()); stubDelegatePoolReleasesForSuccess(); assertThat(getIdleConnectionCount()).isEqualTo(0); Channel channel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel).await(); assertThat(getIdleConnectionCount()).isEqualTo(1); channel.close().await(); assertThat(getIdleConnectionCount()).isEqualTo(0); } @Test(timeout = 5_000) public void channelsClosedWhenCheckedOutAreNotCounted() throws InterruptedException { stubDelegatePoolAcquires(createSuccessfulAcquire()); stubDelegatePoolReleasesForSuccess(); assertThat(getIdleConnectionCount()).isEqualTo(0); Channel channel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); channel.close().await(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel).await(); assertThat(getIdleConnectionCount()).isEqualTo(0); } @Test public void checkingOutAnIdleChannelIsCountedCorrectly() throws InterruptedException { Future<Channel> successfulAcquire = createSuccessfulAcquire(); stubDelegatePoolAcquires(successfulAcquire, successfulAcquire); stubDelegatePoolReleasesForSuccess(); assertThat(getIdleConnectionCount()).isEqualTo(0); Channel channel1 = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel1).await(); assertThat(getIdleConnectionCount()).isEqualTo(1); Channel channel2 = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); assertThat(channel1).isEqualTo(channel2); } @Test public void stochastic_rapidAcquireReleaseIsCalculatedCorrectly() throws InterruptedException { Future<Channel> successfulAcquire = createSuccessfulAcquire(); Channel expectedChannel = successfulAcquire.getNow(); stubDelegatePoolAcquires(successfulAcquire); stubDelegatePoolReleasesForSuccess(); for (int i = 0; i < 1000; ++i) { Channel channel = idleCountingPool.acquire().await().getNow(); assertThat(channel).isEqualTo(expectedChannel); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel).await(); assertThat(getIdleConnectionCount()).isEqualTo(1); } } @Test public void stochastic_rapidAcquireReleaseCloseIsCalculatedCorrectly() throws InterruptedException { stubDelegatePoolAcquiresForSuccess(); stubDelegatePoolReleasesForSuccess(); for (int i = 0; i < 1000; ++i) { Channel channel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel).await(); assertThat(getIdleConnectionCount()).isEqualTo(1); channel.close().await(); assertThat(getIdleConnectionCount()).isEqualTo(0); } } @Test public void stochastic_rapidAcquireCloseReleaseIsCalculatedCorrectly() throws InterruptedException { stubDelegatePoolAcquiresForSuccess(); stubDelegatePoolReleasesForSuccess(); for (int i = 0; i < 1000; ++i) { Channel channel = idleCountingPool.acquire().await().getNow(); assertThat(getIdleConnectionCount()).isEqualTo(0); channel.close().await(); assertThat(getIdleConnectionCount()).isEqualTo(0); idleCountingPool.release(channel).await(); assertThat(getIdleConnectionCount()).isEqualTo(0); } } @Test public void collectChannelPoolMetrics_failes_futureFailed() throws Exception { MockChannel channel = new MockChannel(); eventLoopGroup.register(channel); RuntimeException errorToThrow = new RuntimeException("failed!"); MetricCollector mockMetricCollector = mock(MetricCollector.class); doThrow(errorToThrow).when(mockMetricCollector).reportMetric(any(), any()); CompletableFuture<Void> collectFuture = idleCountingPool.collectChannelPoolMetrics(mockMetricCollector); assertThatThrownBy(() -> collectFuture.get(1, TimeUnit.SECONDS)).hasCause(errorToThrow); } private int getIdleConnectionCount() { MetricCollector metricCollector = MetricCollector.create("test"); idleCountingPool.collectChannelPoolMetrics(metricCollector).join(); return metricCollector.collect().metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0); } @SafeVarargs private final void stubDelegatePoolAcquires(Future<Channel> result, Future<Channel>... extraResults) { Mockito.when(delegatePool.acquire(any())).thenReturn(result, extraResults); } private void stubDelegatePoolAcquiresForSuccess() { Mockito.when(delegatePool.acquire(any())).thenAnswer(a -> createSuccessfulAcquire()); } private void stubDelegatePoolReleasesForSuccess() { Mockito.when(delegatePool.release(any(Channel.class), any(Promise.class))).thenAnswer((Answer<Future<Void>>) invocation -> { Promise<Void> promise = invocation.getArgument(1, Promise.class); promise.setSuccess(null); return promise; }); } private Future<Channel> createSuccessfulAcquire() { try { EventLoop eventLoop = this.eventLoopGroup.next(); Promise<Channel> channelPromise = eventLoop.newPromise(); MockChannel channel = new MockChannel(); eventLoop.register(channel); channelPromise.setSuccess(channel); return channelPromise; } catch (Exception e) { throw new Error(e); } } }
1,343
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyUtilsTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.ReadTimeoutException; import io.netty.handler.timeout.WriteTimeoutException; import io.netty.util.Attribute; 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 java.io.IOException; import java.nio.channels.ClosedChannelException; import java.time.Duration; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLEngine; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; public class NettyUtilsTest { private static EventLoopGroup eventLoopGroup; @BeforeAll public static void setup() { eventLoopGroup = new NioEventLoopGroup(1); } @AfterAll public static void teardown() throws InterruptedException { eventLoopGroup.shutdownGracefully().await(); } @Test public void testGetOrCreateAttributeKey_calledTwiceWithSameName_returnsSameInstance() { String attr = "NettyUtilsTest.Foo"; AttributeKey<String> fooAttr = NettyUtils.getOrCreateAttributeKey(attr); assertThat(NettyUtils.getOrCreateAttributeKey(attr)).isSameAs(fooAttr); } @Test public void newSslHandler_sslEngineShouldBeConfigured() throws Exception { SslContext sslContext = SslContextBuilder.forClient().build(); Channel channel = null; try { channel = new MockChannel(); SslHandler sslHandler = NettyUtils.newSslHandler(sslContext, channel.alloc(), "localhost", 80, Duration.ofMillis(1000)); assertThat(sslHandler.getHandshakeTimeoutMillis()).isEqualTo(1000); SSLEngine engine = sslHandler.engine(); assertThat(engine.getSSLParameters().getEndpointIdentificationAlgorithm()).isEqualTo("HTTPS"); } finally { if (channel != null) { channel.close(); } } } @Test public void doInEventLoop_inEventLoop_doesNotSubmit() { EventExecutor mockExecutor = mock(EventExecutor.class); when(mockExecutor.inEventLoop()).thenReturn(true); NettyUtils.doInEventLoop(mockExecutor, () -> {}); verify(mockExecutor, never()).submit(any(Runnable.class)); } @Test public void doInEventLoop_notInEventLoop_submits() { EventExecutor mockExecutor = mock(EventExecutor.class); when(mockExecutor.inEventLoop()).thenReturn(false); NettyUtils.doInEventLoop(mockExecutor, () -> {}); verify(mockExecutor).submit(any(Runnable.class)); } @Test public void runOrPropagate_success_runs() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); AtomicBoolean reference = new AtomicBoolean(); GenericFutureListener<Future<Void>> listener = NettyUtils.runOrPropagate(destination, () -> reference.set(true)); Promise<Void> source = eventLoopGroup.next().newPromise(); source.setSuccess(null); listener.operationComplete(source); assertThat(reference.get()).isTrue(); } @Test public void runOrPropagate_exception_propagates() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); GenericFutureListener<Future<Void>> listener = NettyUtils.runOrPropagate(destination, () -> { }); Promise<Void> source = eventLoopGroup.next().newPromise(); source.setFailure(new RuntimeException("Intentional exception for testing purposes")); listener.operationComplete(source); assertThat(destination.cause()) .isInstanceOf(RuntimeException.class) .hasMessage("Intentional exception for testing purposes"); } @Test public void runOrPropagate_cancel_propagates() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); GenericFutureListener<Future<Void>> listener = NettyUtils.runOrPropagate(destination, () -> { }); Promise<Void> source = eventLoopGroup.next().newPromise(); source.cancel(false); listener.operationComplete(source); assertThat(destination.isCancelled()).isTrue(); } @Test public void consumeOrPropagate_success_consumes() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); AtomicReference<String> reference = new AtomicReference<>(); GenericFutureListener<Future<String>> listener = NettyUtils.consumeOrPropagate(destination, reference::set); Promise<String> source = eventLoopGroup.next().newPromise(); source.setSuccess("test"); listener.operationComplete(source); assertThat(reference.get()).isEqualTo("test"); } @Test public void consumeOrPropagate_exception_propagates() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); GenericFutureListener<Future<String>> listener = NettyUtils.consumeOrPropagate(destination, s -> { }); Promise<String> source = eventLoopGroup.next().newPromise(); source.setFailure(new RuntimeException("Intentional exception for testing purposes")); listener.operationComplete(source); assertThat(destination.cause()) .isInstanceOf(RuntimeException.class) .hasMessage("Intentional exception for testing purposes"); } @Test public void consumeOrPropagate_cancel_propagates() throws Exception { Promise<String> destination = eventLoopGroup.next().newPromise(); GenericFutureListener<Future<String>> listener = NettyUtils.consumeOrPropagate(destination, s -> { }); Promise<String> source = eventLoopGroup.next().newPromise(); source.cancel(false); listener.operationComplete(source); assertThat(destination.isCancelled()).isTrue(); } @Test public void runAndLogError_runnableDoesNotThrow_loggerNotInvoked() { Logger delegateLogger = mock(Logger.class); NettyClientLogger logger = new NettyClientLogger(delegateLogger); NettyUtils.runAndLogError(logger, "Something went wrong", () -> {}); verifyNoMoreInteractions(delegateLogger); } @Test public void runAndLogError_runnableThrows_loggerInvoked() { Logger delegateLogger = mock(Logger.class); when(delegateLogger.isErrorEnabled()).thenReturn(true); NettyClientLogger logger = new NettyClientLogger(delegateLogger); String msg = "Something went wrong"; RuntimeException error = new RuntimeException("Boom!"); NettyUtils.runAndLogError(logger, msg, () -> { throw error; }); verify(delegateLogger).error(msg, error); } @Test public void closedChannelMessage_with_nullChannelAttribute() throws Exception { Channel channel = Mockito.mock(Channel.class); when(channel.parent()).thenReturn(null); assertThat(NettyUtils.closedChannelMessage(channel)) .isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE); } @Test public void closedChannelMessage_with_nullChannel() throws Exception { Channel channel = null; assertThat(NettyUtils.closedChannelMessage(channel)) .isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE); } @Test public void closedChannelMessage_with_nullParentChannel() throws Exception { Channel channel = mock(Channel.class); Attribute attribute = mock(Attribute.class); when(channel.parent()).thenReturn(null); when(channel.attr(any())).thenReturn(attribute); assertThat(NettyUtils.closedChannelMessage(channel)) .isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE); } @Test public void closedChannelMessage_with_nullParentChannelAttribute() throws Exception { Channel channel = mock(Channel.class); Attribute attribute = mock(Attribute.class); Channel parentChannel = mock(Channel.class); when(channel.parent()).thenReturn(parentChannel); when(channel.attr(any())).thenReturn(attribute); when(parentChannel.attr(any())).thenReturn(null); assertThat(NettyUtils.closedChannelMessage(channel)) .isEqualTo(NettyUtils.CLOSED_CHANNEL_ERROR_MESSAGE); } @Test public void decorateException_with_TimeoutException() { Channel channel = mock(Channel.class); Throwable timeoutException = new TimeoutException("...Acquire operation took longer..."); Throwable output = NettyUtils.decorateException(channel, timeoutException); assertThat(output).isInstanceOf(Throwable.class); assertThat(output.getCause()).isInstanceOf(TimeoutException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_TimeoutException_noMsg() { Channel channel = mock(Channel.class); Throwable timeoutException = new TimeoutException(); Throwable output = NettyUtils.decorateException(channel, timeoutException); assertThat(output).isInstanceOf(TimeoutException.class); assertThat(output.getCause()).isNull(); } @Test public void decorateException_with_IllegalStateException() { Channel channel = mock(Channel.class); Throwable illegalStateException = new IllegalStateException("...Too many outstanding acquire operations..."); Throwable output = NettyUtils.decorateException(channel, illegalStateException); assertThat(output).isInstanceOf(Throwable.class); assertThat(output.getCause()).isInstanceOf(IllegalStateException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_IllegalStateException_noMsg() { Channel channel = mock(Channel.class); Throwable illegalStateException = new IllegalStateException(); Throwable output = NettyUtils.decorateException(channel, illegalStateException); assertThat(output).isInstanceOf(IllegalStateException.class); assertThat(output.getCause()).isNull(); } @Test public void decorateException_with_ReadTimeoutException() { Channel channel = mock(Channel.class); Throwable readTimeoutException = new ReadTimeoutException(); Throwable output = NettyUtils.decorateException(channel, readTimeoutException); assertThat(output).isInstanceOf(IOException.class); assertThat(output.getCause()).isInstanceOf(ReadTimeoutException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_WriteTimeoutException() { Channel channel = mock(Channel.class); Throwable writeTimeoutException = new WriteTimeoutException(); Throwable output = NettyUtils.decorateException(channel, writeTimeoutException); assertThat(output).isInstanceOf(IOException.class); assertThat(output.getCause()).isInstanceOf(WriteTimeoutException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_ClosedChannelException() { Channel channel = mock(Channel.class); Throwable closedChannelException = new ClosedChannelException(); Throwable output = NettyUtils.decorateException(channel, closedChannelException); assertThat(output).isInstanceOf(IOException.class); assertThat(output.getCause()).isInstanceOf(ClosedChannelException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_IOException_reset() { Channel channel = mock(Channel.class); Throwable closedChannelException = new IOException("...Connection reset by peer..."); Throwable output = NettyUtils.decorateException(channel, closedChannelException); assertThat(output).isInstanceOf(IOException.class); assertThat(output.getCause()).isInstanceOf(IOException.class); assertThat(output.getMessage()).isNotNull(); } @Test public void decorateException_with_IOException_noMsg() { Channel channel = mock(Channel.class); Throwable closedChannelException = new IOException(); Throwable output = NettyUtils.decorateException(channel, closedChannelException); assertThat(output).isInstanceOf(IOException.class); assertThat(output.getCause()).isNull(); } }
1,344
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelUtilsTest.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 org.assertj.core.api.Assertions.assertThat; 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 io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.ReadTimeoutHandler; import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; public class ChannelUtilsTest { @Test public void testGetAttributes() throws Exception { MockChannel channel = null; try { channel = new MockChannel(); channel.attr(MAX_CONCURRENT_STREAMS).set(1L); assertThat(ChannelUtils.getAttribute(channel, MAX_CONCURRENT_STREAMS).get()).isEqualTo(1L); assertThat(ChannelUtils.getAttribute(channel, HTTP2_MULTIPLEXED_CHANNEL_POOL)).isNotPresent(); } finally { Optional.ofNullable(channel).ifPresent(Channel::close); } } @Test public void removeIfExists() throws Exception { MockChannel channel = null; try { channel = new MockChannel(); ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new ReadTimeoutHandler(1)); pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); ChannelUtils.removeIfExists(pipeline, ReadTimeoutHandler.class, LoggingHandler.class); assertThat(pipeline.get(ReadTimeoutHandler.class)).isNull(); assertThat(pipeline.get(LoggingHandler.class)).isNull(); } finally { Optional.ofNullable(channel).ifPresent(Channel::close); } } }
1,345
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ExceptionHandlingUtilsTest.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 org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ExceptionHandlingUtilsTest { @Mock private Consumer<Throwable> errorNotifier; @Mock private Runnable cleanupExecutor; @Test public void tryCatch() { ExceptionHandlingUtils.tryCatch(() -> { }, errorNotifier); verify(errorNotifier, times(0)).accept(any(Throwable.class)); } @Test public void tryCatchExceptionThrows() { ExceptionHandlingUtils.tryCatch(() -> { throw new RuntimeException("helloworld"); }, errorNotifier); verify(errorNotifier).accept(any(Throwable.class)); } @Test public void tryCatchFinallyException() { ExceptionHandlingUtils.tryCatchFinally(() -> "blah", errorNotifier, cleanupExecutor ); verify(errorNotifier, times(0)).accept(any(Throwable.class)); verify(cleanupExecutor).run(); } @Test public void tryCatchFinallyExceptionThrows() { ExceptionHandlingUtils.tryCatchFinally(() -> { throw new RuntimeException("helloworld"); }, errorNotifier, cleanupExecutor ); verify(errorNotifier).accept(any(Throwable.class)); verify(cleanupExecutor).run(); } }
1,346
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelResolverTest.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 org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelResolver.resolveDatagramChannelFactory; import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelResolver.resolveSocketChannelFactory; import io.netty.channel.epoll.Epoll; 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.oio.OioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.oio.OioDatagramChannel; import io.netty.channel.socket.oio.OioSocketChannel; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.internal.DelegatingEventLoopGroup; public class ChannelResolverTest { @Test public void canDetectFactoryForStandardNioEventLoopGroup() { assertThat(resolveSocketChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioSocketChannel.class); assertThat(resolveDatagramChannelFactory(new NioEventLoopGroup()).newChannel()).isInstanceOf(NioDatagramChannel.class); } @Test public void canDetectEpollEventLoopGroupFactory() { Assumptions.assumeTrue(Epoll.isAvailable()); assertThat(resolveSocketChannelFactory(new EpollEventLoopGroup()).newChannel()).isInstanceOf(EpollSocketChannel.class); assertThat(resolveDatagramChannelFactory(new EpollEventLoopGroup()).newChannel()).isInstanceOf(EpollDatagramChannel.class); } @Test public void worksWithDelegateEventLoopGroupsFactory() { assertThat(resolveSocketChannelFactory(new DelegatingEventLoopGroup(new NioEventLoopGroup()) {}).newChannel()).isInstanceOf(NioSocketChannel.class); assertThat(resolveDatagramChannelFactory(new DelegatingEventLoopGroup(new NioEventLoopGroup()) {}).newChannel()).isInstanceOf(NioDatagramChannel.class); } @Test public void worksWithOioEventLoopGroupFactory() { assertThat(resolveSocketChannelFactory(new OioEventLoopGroup()).newChannel()).isInstanceOf(OioSocketChannel.class); assertThat(resolveDatagramChannelFactory(new OioEventLoopGroup()).newChannel()).isInstanceOf(OioDatagramChannel.class); } }
1,347
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyClientLoggerTest.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 org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.netty.channel.Channel; import io.netty.channel.ChannelId; import io.netty.channel.DefaultChannelId; import io.netty.channel.embedded.EmbeddedChannel; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; @RunWith(MockitoJUnitRunner.class) public class NettyClientLoggerTest { private static final String TEST_MSG = "test"; private static final ChannelId CHANNEL_ID = DefaultChannelId.newInstance(); private static final String CHANNEL_TO_STRING = "NettyClientLoggerTest_TestChannel"; private static final String EXPECTED_MESSAGE_SHORT = String.format("[Channel: %s] %s", CHANNEL_ID.asShortText(), TEST_MSG); private static final String EXPECTED_MESSAGE_FULL = String.format("[Channel: %s] %s", CHANNEL_TO_STRING, TEST_MSG); @Mock public Logger delegateLogger; @Mock public Supplier<String> msgSupplier; private NettyClientLogger logger; private EmbeddedChannel ch; @BeforeClass public static void setup() throws InterruptedException { } @Before public void methodSetup() { when(msgSupplier.get()).thenReturn(TEST_MSG); logger = new NettyClientLogger(delegateLogger); ch = spy(new EmbeddedChannel(CHANNEL_ID)); when(ch.toString()).thenReturn(CHANNEL_TO_STRING); } @After public void methodTeardown() throws InterruptedException { ch.close().await(); } @Test public void debugNotEnabled_doesNotInvokeLogger() { when(delegateLogger.isDebugEnabled()).thenReturn(false); Channel channel = mock(Channel.class); logger.debug(channel, msgSupplier, null); verify(delegateLogger, never()).debug(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); verifyNoMoreInteractions(channel); } @Test public void debugEnabled_invokesLogger() { when(delegateLogger.isDebugEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.debug(ch, msgSupplier, exception); verify(delegateLogger).debug(EXPECTED_MESSAGE_FULL, exception); } @Test public void debugNotEnabled_channelNotProvided_doesNotInvokeLogger() { when(delegateLogger.isDebugEnabled()).thenReturn(false); logger.debug(null, msgSupplier, null); verify(delegateLogger, never()).debug(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); } @Test public void debugEnabled_channelNotProvided_invokesLogger() { when(delegateLogger.isDebugEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.debug(null, msgSupplier, exception); verify(delegateLogger).debug(TEST_MSG, exception); } @Test public void warnNotEnabled_doesNotInvokeLogger() { when(delegateLogger.isWarnEnabled()).thenReturn(false); Channel channel = mock(Channel.class); logger.warn(channel, msgSupplier, null); verify(delegateLogger, never()).warn(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); verifyNoMoreInteractions(channel); } @Test public void warnEnabled_invokesLogger() { when(delegateLogger.isWarnEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.warn(ch, msgSupplier, exception); verify(delegateLogger).warn(EXPECTED_MESSAGE_SHORT, exception); } @Test public void warnEnabled_debugEnabled_invokesLogger() { when(delegateLogger.isWarnEnabled()).thenReturn(true); when(delegateLogger.isDebugEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.warn(ch, msgSupplier, exception); verify(delegateLogger).warn(EXPECTED_MESSAGE_FULL, exception); } @Test public void errorNotEnabled_noChannelProvided_doesNotInvokeLogger() { when(delegateLogger.isErrorEnabled()).thenReturn(false); logger.error(null, msgSupplier, null); verify(delegateLogger, never()).error(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); } @Test public void errorEnabled_noChannelProvided_invokesLogger() { when(delegateLogger.isErrorEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.error(null, msgSupplier, exception); verify(delegateLogger).error(TEST_MSG, exception); } @Test public void errorNotEnabled_doesNotInvokeLogger() { when(delegateLogger.isErrorEnabled()).thenReturn(false); Channel channel = mock(Channel.class); logger.error(channel, msgSupplier, null); verify(delegateLogger, never()).error(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); verifyNoMoreInteractions(channel); } @Test public void errorEnabled_invokesLogger() { when(delegateLogger.isErrorEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.error(ch, msgSupplier, exception); verify(delegateLogger).error(EXPECTED_MESSAGE_SHORT, exception); } @Test public void errorEnabled_debugEnabled_invokesLogger() { when(delegateLogger.isErrorEnabled()).thenReturn(true); when(delegateLogger.isDebugEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.error(ch, msgSupplier, exception); verify(delegateLogger).error(EXPECTED_MESSAGE_FULL, exception); } @Test public void warnNotEnabled_noChannelProvided_doesNotInvokeLogger() { when(delegateLogger.isWarnEnabled()).thenReturn(false); logger.warn(null, msgSupplier, null); verify(delegateLogger, never()).warn(anyString(), any(Throwable.class)); verifyNoMoreInteractions(msgSupplier); } @Test public void warnEnabled_noChannelProvided_invokesLogger() { when(delegateLogger.isWarnEnabled()).thenReturn(true); RuntimeException exception = new RuntimeException("boom!"); logger.warn(null, msgSupplier, exception); verify(delegateLogger).warn(TEST_MSG, exception); } @Test public void traceNotEnabled_doesNotInvokeLogger() { when(delegateLogger.isTraceEnabled()).thenReturn(false); Channel channel = mock(Channel.class); logger.trace(channel, msgSupplier); verify(delegateLogger, never()).trace(anyString()); verifyNoMoreInteractions(msgSupplier); verifyNoMoreInteractions(channel); } @Test public void traceEnabled_invokesLogger() { when(delegateLogger.isTraceEnabled()).thenReturn(true); when(delegateLogger.isDebugEnabled()).thenReturn(true); logger.trace(ch, msgSupplier); verify(delegateLogger).trace(EXPECTED_MESSAGE_FULL); } @Test public void traceNotEnabled_noChannelProvided_doesNotInvokeLogger() { when(delegateLogger.isTraceEnabled()).thenReturn(false); logger.trace(null, msgSupplier); verify(delegateLogger, never()).trace(anyString()); verifyNoMoreInteractions(msgSupplier); } @Test public void traceEnabled_noChannelProvided_invokesLogger() { when(delegateLogger.isTraceEnabled()).thenReturn(true); logger.trace(null, msgSupplier); verify(delegateLogger).trace(TEST_MSG); } }
1,348
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/utils/BetterFixedChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool.AcquireTimeoutAction; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; public class BetterFixedChannelPoolTest { private static EventLoopGroup eventLoopGroup; private BetterFixedChannelPool channelPool; private SdkChannelPool delegatePool; @BeforeClass public static void setupClass() { eventLoopGroup = new NioEventLoopGroup(1); } @AfterClass public static void teardownClass() throws InterruptedException { eventLoopGroup.shutdownGracefully().await(); } @Before public void setup() { delegatePool = mock(SdkChannelPool.class); channelPool = BetterFixedChannelPool.builder() .channelPool(delegatePool) .maxConnections(2) .maxPendingAcquires(2) .acquireTimeoutAction(AcquireTimeoutAction.FAIL) .acquireTimeoutMillis(10_000) .executor(eventLoopGroup.next()) .build(); } @After public void teardown() { channelPool.close(); } @Test public void delegateChannelPoolMetricFailureIsReported() { Throwable t = new Throwable(); Mockito.when(delegatePool.collectChannelPoolMetrics(any())).thenReturn(CompletableFutureUtils.failedFuture(t)); CompletableFuture<Void> result = channelPool.collectChannelPoolMetrics(MetricCollector.create("test")); waitForCompletion(result); assertThat(result).hasFailedWithThrowableThat().isEqualTo(t); } @Test(timeout = 5_000) public void metricCollectionHasCorrectValuesAfterAcquiresAndReleases() throws Exception { List<Promise<Channel>> acquirePromises = Collections.synchronizedList(new ArrayList<>()); Mockito.when(delegatePool.acquire(isA(Promise.class))).thenAnswer(i -> { Promise<Channel> promise = eventLoopGroup.next().newPromise(); acquirePromises.add(promise); return promise; }); List<Promise<Channel>> releasePromises = Collections.synchronizedList(new ArrayList<>()); Mockito.when(delegatePool.release(isA(Channel.class), isA(Promise.class))).thenAnswer(i -> { Promise promise = i.getArgument(1, Promise.class); releasePromises.add(promise); return promise; }); Mockito.when(delegatePool.collectChannelPoolMetrics(any())).thenReturn(CompletableFuture.completedFuture(null)); assertConnectionsCheckedOutAndPending(0, 0); channelPool.acquire(); completePromise(acquirePromises, 0); assertConnectionsCheckedOutAndPending(1, 0); channelPool.acquire(); completePromise(acquirePromises, 1); assertConnectionsCheckedOutAndPending(2, 0); channelPool.acquire(); assertConnectionsCheckedOutAndPending(2, 1); channelPool.acquire(); assertConnectionsCheckedOutAndPending(2, 2); Future<Channel> f = channelPool.acquire(); assertConnectionsCheckedOutAndPending(2, 2); assertThat(f.isSuccess()).isFalse(); assertThat(f.cause()).isInstanceOf(IllegalStateException.class); channelPool.release(acquirePromises.get(1).getNow()); assertConnectionsCheckedOutAndPending(2, 2); completePromise(releasePromises, 0); completePromise(acquirePromises, 2); assertConnectionsCheckedOutAndPending(2, 1); channelPool.release(acquirePromises.get(2).getNow()); completePromise(releasePromises, 1); completePromise(acquirePromises, 3); assertConnectionsCheckedOutAndPending(2, 0); channelPool.release(acquirePromises.get(0).getNow()); completePromise(releasePromises, 2); assertConnectionsCheckedOutAndPending(1, 0); channelPool.release(acquirePromises.get(3).getNow()); completePromise(releasePromises, 3); assertConnectionsCheckedOutAndPending(0, 0); } private void completePromise(List<Promise<Channel>> promises, int promiseIndex) throws Exception { waitForPromise(promises, promiseIndex); MockChannel channel = new MockChannel(); eventLoopGroup.next().register(channel); promises.get(promiseIndex).setSuccess(channel); } private void waitForPromise(List<Promise<Channel>> promises, int promiseIndex) throws Exception { while (promises.size() < promiseIndex + 1) { Thread.sleep(1); } } private void assertConnectionsCheckedOutAndPending(int checkedOut, int pending) { MetricCollector metricCollector = MetricCollector.create("foo"); waitForCompletion(channelPool.collectChannelPoolMetrics(metricCollector)); MetricCollection metrics = metricCollector.collect(); assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY)).containsExactly(2); assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY)).containsExactly(checkedOut); assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES)).containsExactly(pending); } private void waitForCompletion(CompletableFuture<Void> future) { try { future.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { return; } catch (InterruptedException | TimeoutException e) { throw new Error(e); } } }
1,349
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2StreamExceptionHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PING_TRACKER; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.timeout.ReadTimeoutException; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; @RunWith(MockitoJUnitRunner.class) public class Http2StreamExceptionHandlerTest { private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1); private Http2StreamExceptionHandler handler; @Mock private ChannelHandlerContext context; @Mock private Channel mockParentChannel; private MockChannel embeddedParentChannel; @Mock private Channel streamChannel; private TestVerifyExceptionHandler verifyExceptionHandler; @Before public void setup() throws Exception { embeddedParentChannel = new MockChannel(); verifyExceptionHandler = new TestVerifyExceptionHandler(); embeddedParentChannel.pipeline().addLast(verifyExceptionHandler); when(context.channel()).thenReturn(streamChannel); handler = Http2StreamExceptionHandler.create(); when(context.executor()).thenReturn(GROUP.next()); } @After public void tearDown() { embeddedParentChannel.close().awaitUninterruptibly(); Mockito.reset(streamChannel, context, mockParentChannel); } @AfterClass public static void teardown() { GROUP.shutdownGracefully().awaitUninterruptibly(); } @Test public void timeoutException_shouldFireExceptionAndPropagateException() { when(streamChannel.parent()).thenReturn(embeddedParentChannel); handler.exceptionCaught(context, ReadTimeoutException.INSTANCE); assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class); verify(context).fireExceptionCaught(ReadTimeoutException.INSTANCE); } @Test public void ioException_shouldFireExceptionAndPropagateException() { IOException ioException = new IOException("yolo"); when(streamChannel.parent()).thenReturn(embeddedParentChannel); handler.exceptionCaught(context, ioException); assertThat(verifyExceptionHandler.exceptionCaught).isExactlyInstanceOf(Http2ConnectionTerminatingException.class); verify(context).fireExceptionCaught(ioException); } @Test public void otherException_shouldJustPropagateException() { when(streamChannel.parent()).thenReturn(embeddedParentChannel); RuntimeException otherException = new RuntimeException("test"); handler.exceptionCaught(context, otherException); assertThat(embeddedParentChannel.attr(PING_TRACKER).get()).isNull(); verify(context).fireExceptionCaught(otherException); assertThat(verifyExceptionHandler.exceptionCaught).isNull(); } private static final class TestVerifyExceptionHandler extends ChannelInboundHandlerAdapter { private Throwable exceptionCaught; @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { exceptionCaught = cause; } } }
1,350
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2MultiplexedChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION; import static software.amazon.awssdk.http.nio.netty.internal.http2.utils.Http2TestUtils.newHttp2Channel; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2LocalFlowController; import io.netty.handler.codec.http2.Http2Stream; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.FailedFuture; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; /** * Tests for {@link Http2MultiplexedChannelPool}. */ public class Http2MultiplexedChannelPoolTest { private static EventLoopGroup loopGroup; @BeforeClass public static void setup() { loopGroup = new NioEventLoopGroup(4); } @AfterClass public static void teardown() { loopGroup.shutdownGracefully().awaitUninterruptibly(); } @Test public void failedConnectionAcquireNotifiesPromise() throws InterruptedException { IOException exception = new IOException(); ChannelPool connectionPool = mock(ChannelPool.class); when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception)); ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null); Future<Channel> acquirePromise = pool.acquire().await(); assertThat(acquirePromise.isSuccess()).isFalse(); assertThat(acquirePromise.cause()).isEqualTo(exception); } @Test public void releaseParentChannelIfReleasingLastChildChannelOnGoAwayChannel() { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); ChannelPool connectionPool = mock(ChannelPool.class); ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class); when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> { Promise<?> promise = releasePromise.getValue(); promise.setSuccess(null); return promise; }); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); h2Pool.close(); InOrder inOrder = Mockito.inOrder(connectionPool); inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class)); inOrder.verify(connectionPool).close(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquireAfterCloseFails() throws InterruptedException { ChannelPool connectionPool = mock(ChannelPool.class); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null); h2Pool.close(); Future<Channel> acquireResult = h2Pool.acquire().await(); assertThat(acquireResult.isSuccess()).isFalse(); assertThat(acquireResult.cause()).isInstanceOf(IOException.class); } @Test public void closeWaitsForConnectionToBeReleasedBeforeClosingConnectionPool() { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); ChannelPool connectionPool = mock(ChannelPool.class); ArgumentCaptor<Promise> releasePromise = ArgumentCaptor.forClass(Promise.class); when(connectionPool.release(eq(channel), releasePromise.capture())).thenAnswer(invocation -> { Promise<?> promise = releasePromise.getValue(); promise.setSuccess(null); return promise; }); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); h2Pool.close(); InOrder inOrder = Mockito.inOrder(connectionPool); inOrder.verify(connectionPool).release(eq(channel), isA(Promise.class)); inOrder.verify(connectionPool).close(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquire_shouldAcquireAgainIfExistingNotReusable() throws Exception { Channel channel = new EmbeddedChannel(); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.emptySet(), null); h2Pool.acquire().awaitUninterruptibly(); h2Pool.acquire().awaitUninterruptibly(); Mockito.verify(connectionPool, Mockito.times(2)).acquire(); } finally { channel.close(); } } @Test(timeout = 5_000) public void interruptDuringClosePreservesFlag() throws InterruptedException { SocketChannel channel = new NioSocketChannel(); try { loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); ChannelPool connectionPool = mock(ChannelPool.class); Promise<Void> releasePromise = Mockito.spy(new DefaultPromise<>(loopGroup.next())); when(connectionPool.release(eq(channel))).thenReturn(releasePromise); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 8, null); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.singleton(record), null); CompletableFuture<Boolean> interrupteFlagPreserved = new CompletableFuture<>(); Thread t = new Thread(() -> { try { h2Pool.close(); } catch (Exception e) { if (e.getCause() instanceof InterruptedException && Thread.currentThread().isInterrupted()) { interrupteFlagPreserved.complete(true); } } }); t.start(); t.interrupt(); t.join(); assertThat(interrupteFlagPreserved.join()).isTrue(); } finally { channel.close().awaitUninterruptibly(); } } @Test public void acquire_shouldExpandConnectionWindowSizeProportionally() { int maxConcurrentStream = 3; EmbeddedChannel channel = newHttp2Channel(); channel.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); Mockito.when(connectionPool.acquire()).thenReturn(channelPromise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup, Collections.emptySet(), null); Future<Channel> acquire = h2Pool.acquire(); acquire.awaitUninterruptibly(); channel.runPendingTasks(); Http2Connection http2Connection = channel.attr(HTTP2_CONNECTION).get(); Http2LocalFlowController flowController = http2Connection.local().flowController(); System.out.println(flowController.initialWindowSize()); Http2Stream connectionStream = http2Connection.stream(0); // 1_048_576 (initial configured window size), 65535 (configured initial window size) // (1048576 - 65535) *2 + 65535 = 2031617 assertThat(flowController.windowSize(connectionStream)).isEqualTo(2031617); // 2031617 + 1048576 (configured initial window size) = 3080193 assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(3080193); // acquire again h2Pool.acquire().awaitUninterruptibly(); channel.runPendingTasks(); // 3080193 + 1048576 (configured initial window size) = 4128769 assertThat(flowController.initialWindowSize(connectionStream)).isEqualTo(4128769); Mockito.verify(connectionPool, Mockito.times(1)).acquire(); } finally { channel.close(); } } @Test public void metricsShouldSumAllChildChannels() throws InterruptedException { int maxConcurrentStream = 2; EmbeddedChannel channel1 = newHttp2Channel(); EmbeddedChannel channel2 = newHttp2Channel(); channel1.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); channel2.attr(ChannelAttributeKey.MAX_CONCURRENT_STREAMS).set((long) maxConcurrentStream); try { ChannelPool connectionPool = Mockito.mock(ChannelPool.class); loopGroup.register(channel1).awaitUninterruptibly(); loopGroup.register(channel2).awaitUninterruptibly(); Promise<Channel> channel1Promise = new DefaultPromise<>(loopGroup.next()); Promise<Channel> channel2Promise = new DefaultPromise<>(loopGroup.next()); channel1Promise.setSuccess(channel1); channel2Promise.setSuccess(channel2); Mockito.when(connectionPool.acquire()).thenReturn(channel1Promise, channel2Promise); Http2MultiplexedChannelPool h2Pool = new Http2MultiplexedChannelPool(connectionPool, Http2MultiplexedChannelPoolTest.loopGroup, Collections.emptySet(), null); MetricCollection metrics; metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); Channel lastAcquire = doAcquire(channel1, channel2, h2Pool); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); lastAcquire.close(); h2Pool.release(lastAcquire).awaitUninterruptibly(); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); channel1.close(); h2Pool.release(channel1); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(1); channel2.close(); metrics = getMetrics(h2Pool); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY)).containsExactly(0); } finally { channel1.close(); channel2.close(); } } private Channel doAcquire(EmbeddedChannel channel1, EmbeddedChannel channel2, Http2MultiplexedChannelPool h2Pool) { Future<Channel> acquire = h2Pool.acquire(); acquire.awaitUninterruptibly(); runPendingTasks(channel1, channel2); return acquire.getNow(); } private void runPendingTasks(EmbeddedChannel channel1, EmbeddedChannel channel2) { channel1.runPendingTasks(); channel2.runPendingTasks(); } private MetricCollection getMetrics(Http2MultiplexedChannelPool h2Pool) { MetricCollector metricCollector = MetricCollector.create("test"); h2Pool.collectChannelPoolMetrics(metricCollector); return metricCollector.collect(); } }
1,351
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2GoAwayEventListenerTest.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 org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.DefaultChannelId; import io.netty.util.Attribute; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; public class Http2GoAwayEventListenerTest { private ChannelHandlerContext ctx; private Channel channel; private ChannelPipeline channelPipeline; private Attribute<Http2MultiplexedChannelPool> attribute; @BeforeEach public void setup() { this.ctx = mock(ChannelHandlerContext.class); this.channel = mock(Channel.class); this.channelPipeline = mock(ChannelPipeline.class); this.attribute = mock(Attribute.class); when(ctx.channel()).thenReturn(channel); when(channel.pipeline()).thenReturn(channelPipeline); when(channel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL)).thenReturn(attribute); when(channel.id()).thenReturn(DefaultChannelId.newInstance()); } @Test public void goAwayWithNoChannelPoolRecordRaisesNoExceptions() throws Exception { when(attribute.get()).thenReturn(null); ByteBuf emptyBuffer = Unpooled.EMPTY_BUFFER; new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, emptyBuffer); verify(channelPipeline).fireExceptionCaught(isA(GoAwayException.class)); assertEquals(1, emptyBuffer.refCnt()); } @Test public void goAwayWithChannelPoolRecordPassesAlongTheFrame() throws Exception { Http2MultiplexedChannelPool record = mock(Http2MultiplexedChannelPool.class); when(attribute.get()).thenReturn(record); ByteBuf emptyBuffer = Unpooled.EMPTY_BUFFER; new Http2GoAwayEventListener(channel).onGoAwayReceived(0, 0, emptyBuffer); verify(record).handleGoAway(eq(channel), eq(0), isA(GoAwayException.class)); verifyNoMoreInteractions(record); assertEquals(1, emptyBuffer.refCnt()); } }
1,352
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpOrHttp2ChannelPoolTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.time.Duration; import java.util.concurrent.CompletableFuture; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.AttributeMap; /** * Tests for {@link HttpOrHttp2ChannelPool}. */ @RunWith(MockitoJUnitRunner.class) public class HttpOrHttp2ChannelPoolTest { private static EventLoopGroup eventLoopGroup; @Mock private ChannelPool mockDelegatePool; private HttpOrHttp2ChannelPool httpOrHttp2ChannelPool; @BeforeClass public static void setup() { eventLoopGroup = new NioEventLoopGroup(1); } @AfterClass public static void teardown() throws InterruptedException { eventLoopGroup.shutdownGracefully().await(); } @Before public void methodSetup() { httpOrHttp2ChannelPool = new HttpOrHttp2ChannelPool(mockDelegatePool, eventLoopGroup, 4, new NettyConfiguration(AttributeMap.builder() .put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofSeconds(1)) .put(MAX_PENDING_CONNECTION_ACQUIRES, 5) .put(REAP_IDLE_CONNECTIONS, false) .build())); } @Test public void protocolConfigNotStarted_closeSucceeds() { httpOrHttp2ChannelPool.close(); } @Test(timeout = 5_000) public void invalidProtocolConfig_shouldFailPromise() throws Exception { HttpOrHttp2ChannelPool invalidChannelPool = new HttpOrHttp2ChannelPool(mockDelegatePool, eventLoopGroup, 4, new NettyConfiguration(AttributeMap.builder() .put(CONNECTION_ACQUIRE_TIMEOUT, Duration.ofSeconds(1)) .put(MAX_PENDING_CONNECTION_ACQUIRES, 0) .build())); Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); Thread.sleep(500); Channel channel = new MockChannel(); eventLoopGroup.register(channel); channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); acquirePromise.setSuccess(channel); Future<Channel> p = invalidChannelPool.acquire(); assertThat(p.await().cause().getMessage()).contains("maxPendingAcquires: 0 (expected: >= 1)"); verify(mockDelegatePool).release(channel); assertThat(channel.isOpen()).isFalse(); } @Test public void protocolConfigNotStarted_closeClosesDelegatePool() throws InterruptedException { httpOrHttp2ChannelPool.close(); Thread.sleep(500); verify(mockDelegatePool).close(); } @Test(timeout = 5_000) public void poolClosed_acquireFails() throws InterruptedException { httpOrHttp2ChannelPool.close(); Thread.sleep(500); Future<Channel> p = httpOrHttp2ChannelPool.acquire(eventLoopGroup.next().newPromise()); assertThat(p.await().cause().getMessage()).contains("pool is closed"); } @Test(timeout = 5_000) public void protocolConfigInProgress_poolClosed_closesChannelAndDelegatePoolOnAcquireSuccess() throws InterruptedException { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); // initiate the configuration httpOrHttp2ChannelPool.acquire(); // close the pool before the config can complete (we haven't completed acquirePromise yet) httpOrHttp2ChannelPool.close(); Thread.sleep(500); Channel channel = new NioSocketChannel(); eventLoopGroup.register(channel); try { channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); acquirePromise.setSuccess(channel); assertThat(channel.closeFuture().await().isDone()).isTrue(); Thread.sleep(500); verify(mockDelegatePool).release(eq(channel)); verify(mockDelegatePool).close(); } finally { channel.close(); } } @Test public void protocolConfigInProgress_poolClosed_delegatePoolClosedOnAcquireFailure() throws InterruptedException { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); // initiate the configuration httpOrHttp2ChannelPool.acquire(); // close the pool before the config can complete (we haven't completed acquirePromise yet) httpOrHttp2ChannelPool.close(); Thread.sleep(500); acquirePromise.setFailure(new RuntimeException("Some failure")); Thread.sleep(500); verify(mockDelegatePool).close(); } @Test(timeout = 5_000) public void protocolConfigComplete_poolClosed_closesDelegatePool() throws InterruptedException { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); // initiate the configuration httpOrHttp2ChannelPool.acquire(); Thread.sleep(500); Channel channel = new NioSocketChannel(); eventLoopGroup.register(channel); try { channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); // this should complete the protocol config acquirePromise.setSuccess(channel); Thread.sleep(500); // close the pool httpOrHttp2ChannelPool.close(); Thread.sleep(500); verify(mockDelegatePool).close(); } finally { channel.close(); } } @Test(timeout = 5_000) public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsFailures() throws InterruptedException { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); // startConnection httpOrHttp2ChannelPool.acquire(); // query for metrics before the config can complete (we haven't completed acquirePromise yet) CompletableFuture<Void> metrics = httpOrHttp2ChannelPool.collectChannelPoolMetrics(MetricCollector.create("test")); Thread.sleep(500); assertThat(metrics.isDone()).isFalse(); acquirePromise.setFailure(new RuntimeException("Some failure")); Thread.sleep(500); assertThat(metrics.isCompletedExceptionally()).isTrue(); } @Test(timeout = 5_000) public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForHttp1() throws Exception { incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol.HTTP1_1); } @Test(timeout = 5_000) public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForHttp2() throws Exception { incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol.HTTP2); } public void incompleteProtocolFutureDelaysMetricsDelegationAndForwardsSuccessForProtocol(Protocol protocol) throws Exception { Promise<Channel> acquirePromise = eventLoopGroup.next().newPromise(); Promise<Void> releasePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(acquirePromise); when(mockDelegatePool.release(any(Channel.class))).thenReturn(releasePromise); // startConnection httpOrHttp2ChannelPool.acquire(); // query for metrics before the config can complete (we haven't completed acquirePromise yet) MetricCollector metricCollector = MetricCollector.create("foo"); CompletableFuture<Void> metricsFuture = httpOrHttp2ChannelPool.collectChannelPoolMetrics(metricCollector); Thread.sleep(500); assertThat(metricsFuture.isDone()).isFalse(); Channel channel = new MockChannel(); eventLoopGroup.register(channel); channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(protocol)); acquirePromise.setSuccess(channel); releasePromise.setSuccess(null); metricsFuture.join(); MetricCollection metrics = metricCollector.collect(); assertThat(metrics.metricValues(HttpMetric.PENDING_CONCURRENCY_ACQUIRES).get(0)).isEqualTo(0); assertThat(metrics.metricValues(HttpMetric.MAX_CONCURRENCY).get(0)).isEqualTo(4); assertThat(metrics.metricValues(HttpMetric.AVAILABLE_CONCURRENCY).get(0)).isBetween(0, 1); assertThat(metrics.metricValues(HttpMetric.LEASED_CONCURRENCY).get(0)).isBetween(0, 1); } @Test(timeout = 5_000) public void protocolFutureAwaitsReleaseFuture() throws Exception { Promise<Channel> delegateAcquirePromise = eventLoopGroup.next().newPromise(); Promise<Void> releasePromise = eventLoopGroup.next().newPromise(); when(mockDelegatePool.acquire()).thenReturn(delegateAcquirePromise); when(mockDelegatePool.release(any(Channel.class))).thenReturn(releasePromise); MockChannel channel = new MockChannel(); eventLoopGroup.register(channel); channel.attr(PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP1_1)); // Acquire a new connection and save the returned future Future<Channel> acquireFuture = httpOrHttp2ChannelPool.acquire(); // Return a successful connection from the delegate pool delegateAcquirePromise.setSuccess(channel); // The returned future should not complete until the release completes assertThat(acquireFuture.isDone()).isFalse(); // Complete the release releasePromise.setSuccess(null); // Assert the returned future completes (within the test timeout) acquireFuture.await(); } }
1,353
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2SettingsFrameHandlerTest.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 org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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 io.netty.channel.ChannelHandlerContext; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.codec.http2.Http2SettingsFrame; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; @RunWith(MockitoJUnitRunner.class) public class Http2SettingsFrameHandlerTest { private Http2SettingsFrameHandler handler; private MockChannel channel; private AtomicReference<ChannelPool> channelPoolRef; @Mock private ChannelHandlerContext context; @Mock private ChannelPool channelPool; private CompletableFuture<Protocol> protocolCompletableFuture; private long clientMaxStreams; @Before public void setup() throws Exception { clientMaxStreams = 1000L; protocolCompletableFuture = new CompletableFuture<>(); channel = new MockChannel(); channel.attr(MAX_CONCURRENT_STREAMS).set(null); channel.attr(PROTOCOL_FUTURE).set(protocolCompletableFuture); channelPoolRef = new AtomicReference<>(channelPool); handler = new Http2SettingsFrameHandler(channel, clientMaxStreams, channelPoolRef); } @Test public void channelRead_useServerMaxStreams() { long serverMaxStreams = 50L; Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams); handler.channelRead0(context, http2SettingsFrame); assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(serverMaxStreams); assertThat(protocolCompletableFuture).isDone(); assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2); } @Test public void channelRead_useClientMaxStreams() { long serverMaxStreams = 10000L; Http2SettingsFrame http2SettingsFrame = http2SettingsFrame(serverMaxStreams); handler.channelRead0(context, http2SettingsFrame); assertThat(channel.attr(MAX_CONCURRENT_STREAMS).get()).isEqualTo(clientMaxStreams); assertThat(protocolCompletableFuture).isDone(); assertThat(protocolCompletableFuture.join()).isEqualTo(Protocol.HTTP2); } @Test public void exceptionCaught_shouldHandleErrorCloseChannel() throws Exception { Throwable cause = new Throwable(new RuntimeException("BOOM")); handler.exceptionCaught(context, cause); verifyChannelError(cause.getClass()); } @Test public void channelUnregistered_ProtocolFutureNotDone_ShouldRaiseError() throws InterruptedException { handler.channelUnregistered(context); verifyChannelError(IOException.class); } private void verifyChannelError(Class<? extends Throwable> cause) throws InterruptedException { channel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(null); channel.runAllPendingTasks(); assertThat(channel.isOpen()).isFalse(); assertThat(protocolCompletableFuture).isDone(); assertThatThrownBy(() -> protocolCompletableFuture.join()).hasCauseExactlyInstanceOf(cause); Mockito.verify(channelPool).release(channel); } private Http2SettingsFrame http2SettingsFrame(long serverMaxStreams) { return new Http2SettingsFrame() { @Override public Http2Settings settings() { Http2Settings http2Settings = new Http2Settings(); http2Settings.maxConcurrentStreams(serverMaxStreams); return http2Settings; } @Override public String name() { return "test"; } }; } }
1,354
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/ReadTimeoutTest.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.bootstrap.ServerBootstrap; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; 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.DefaultHttp2Headers; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame; 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.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2Settings; import io.netty.util.ReferenceCountUtil; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Optional; import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; 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.async.SdkHttpContentPublisher; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; public class ReadTimeoutTest { private static final int N_FRAMES = 10; private TestH2Server testServer; private SdkAsyncHttpClient netty; @AfterEach public void methodTeardown() throws InterruptedException { if (testServer != null) { testServer.shutdown(); } testServer = null; if (netty != null) { netty.close(); } netty = null; } @Test public void readTimeoutActivatedAfterRequestFullyWritten() throws InterruptedException { testServer = new TestH2Server(StreamHandler::new); testServer.init(); // Set a very short read timeout, shorter than it will take to transfer // the body netty = NettyNioAsyncHttpClient.builder() .protocol(Protocol.HTTP2) .readTimeout(Duration.ofMillis(500)) .build(); SdkHttpFullRequest sdkRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.PUT) .protocol("http") .host("localhost") .port(testServer.port()) .build(); // at 10 frames, should take approximately 3-4 seconds for the server // to receive given that it sleeps for 500ms between data frames and // sleeps for most of them byte[] data = new byte[16384 * N_FRAMES]; Publisher<ByteBuffer> dataPublisher = Flowable.just(ByteBuffer.wrap(data)); AsyncExecuteRequest executeRequest = AsyncExecuteRequest.builder() .request(sdkRequest) .responseHandler(new SdkAsyncHttpResponseHandler() { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { Flowable.fromPublisher(stream).forEach(s -> {}); } @Override public void onError(Throwable error) { } }) .requestContentPublisher(new SdkHttpContentPublisher() { @Override public Optional<Long> contentLength() { return Optional.of((long) data.length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { dataPublisher.subscribe(s); } }) .build(); netty.execute(executeRequest).join(); } private static final class TestH2Server extends ChannelInitializer<SocketChannel> { private final Supplier<ChannelHandler> handlerSupplier; private ServerBootstrap bootstrap; private ServerSocketChannel channel; private TestH2Server(Supplier<ChannelHandler> handlerSupplier) { this.handlerSupplier = handlerSupplier; } public void init() throws InterruptedException { bootstrap = new ServerBootstrap() .channel(NioServerSocketChannel.class) .group(new NioEventLoopGroup()) .childHandler(this) .localAddress(0) .childOption(ChannelOption.SO_KEEPALIVE, true); channel = ((ServerSocketChannel) bootstrap.bind().await().channel()); } public int port() { return channel.localAddress().getPort(); } public void shutdown() throws InterruptedException { channel.close().await(); } @Override protected void initChannel(SocketChannel ch) { Http2FrameCodec codec = Http2FrameCodecBuilder.forServer() .autoAckPingFrame(true) .initialSettings(new Http2Settings() .initialWindowSize(16384) .maxFrameSize(16384) .maxConcurrentStreams(5)) .build(); ch.pipeline().addLast(codec); ch.pipeline().addLast(handlerSupplier.get()); } } private static class StreamHandler extends ChannelInboundHandlerAdapter { private int sleeps = N_FRAMES - 3; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof Http2Frame)) { ctx.fireChannelRead(msg); return; } Http2Frame frame = (Http2Frame) msg; if (frame instanceof Http2DataFrame) { Http2DataFrame dataFrame = (Http2DataFrame) frame; ReferenceCountUtil.release(frame); if (dataFrame.isEndStream()) { Http2HeadersFrame respHeaders = new DefaultHttp2HeadersFrame( new DefaultHttp2Headers().status("204"), true) .stream(dataFrame.stream()); ctx.writeAndFlush(respHeaders); } if (sleeps > 0) { --sleeps; // Simulate a server that's slow to read data. Since our // window size is equal to the max frame size, the client // shouldn't be able to send more data until we update our // window try { Thread.sleep(500); } catch (InterruptedException ie) { } } ctx.writeAndFlush(new DefaultHttp2WindowUpdateFrame(dataFrame.initialFlowControlledBytes()) .stream(dataFrame.stream())); } } } }
1,355
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/WindowSizeTest.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 org.assertj.core.api.Assertions.assertThat; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; 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.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.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.codec.http2.Http2SettingsFrame; import io.netty.util.ReferenceCountUtil; import java.nio.ByteBuffer; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Supplier; import java.util.stream.Collectors; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; 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.Http2Configuration; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; public class WindowSizeTest { private static final int DEFAULT_INIT_WINDOW_SIZE = 1024 * 1024; private TestH2Server server; private SdkAsyncHttpClient netty; @Rule public ExpectedException expected = ExpectedException.none(); @After public void methodTeardown() throws InterruptedException { if (netty != null) { netty.close(); } netty = null; if (server != null) { server.shutdown(); } server = null; } @Test public void builderSetter_negativeValue_throws() { expected.expect(IllegalArgumentException.class); NettyNioAsyncHttpClient.builder() .http2Configuration(Http2Configuration.builder() .initialWindowSize(-1) .build()) .build(); } @Test public void builderSetter_0Value_throws() { expected.expect(IllegalArgumentException.class); NettyNioAsyncHttpClient.builder() .http2Configuration(Http2Configuration.builder() .initialWindowSize(0) .build()) .build(); } @Test public void builderSetter_explicitNullSet_usesDefaultValue() throws InterruptedException { expectCorrectWindowSizeValueTest(null, DEFAULT_INIT_WINDOW_SIZE); } @Test public void execute_customWindowValue_valueSentInSettings() throws InterruptedException { int windowSize = 128 * 1024 * 1024; expectCorrectWindowSizeValueTest(windowSize, windowSize); } @Test public void execute_noExplicitValueSet_sendsDefaultValueInSettings() throws InterruptedException { ConcurrentLinkedQueue<Http2Frame> receivedFrames = new ConcurrentLinkedQueue<>(); server = new TestH2Server(() -> new StreamHandler(receivedFrames)); server.init(); netty = NettyNioAsyncHttpClient.builder() .protocol(Protocol.HTTP2) .build(); AsyncExecuteRequest req = AsyncExecuteRequest.builder() .requestContentPublisher(new EmptyPublisher()) .request(SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("http") .host("localhost") .port(server.port()) .build()) .responseHandler(new SdkAsyncHttpResponseHandler() { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { } @Override public void onError(Throwable error) { } }) .build(); netty.execute(req).join(); List<Http2Settings> receivedSettings = receivedFrames.stream() .filter(f -> f instanceof Http2SettingsFrame) .map(f -> (Http2SettingsFrame) f) .map(Http2SettingsFrame::settings) .collect(Collectors.toList()); assertThat(receivedSettings.size()).isGreaterThan(0); for (Http2Settings s : receivedSettings) { assertThat(s.initialWindowSize()).isEqualTo(DEFAULT_INIT_WINDOW_SIZE); } } private void expectCorrectWindowSizeValueTest(Integer builderSetterValue, int settingsFrameValue) throws InterruptedException { ConcurrentLinkedQueue<Http2Frame> receivedFrames = new ConcurrentLinkedQueue<>(); server = new TestH2Server(() -> new StreamHandler(receivedFrames)); server.init(); netty = NettyNioAsyncHttpClient.builder() .protocol(Protocol.HTTP2) .http2Configuration(Http2Configuration.builder() .initialWindowSize(builderSetterValue) .build()) .build(); AsyncExecuteRequest req = AsyncExecuteRequest.builder() .requestContentPublisher(new EmptyPublisher()) .request(SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("http") .host("localhost") .port(server.port()) .build()) .responseHandler(new SdkAsyncHttpResponseHandler() { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { } @Override public void onError(Throwable error) { } }) .build(); netty.execute(req).join(); List<Http2Settings> receivedSettings = receivedFrames.stream() .filter(f -> f instanceof Http2SettingsFrame) .map(f -> (Http2SettingsFrame) f) .map(Http2SettingsFrame::settings) .collect(Collectors.toList()); assertThat(receivedSettings.size()).isGreaterThan(0); for (Http2Settings s : receivedSettings) { assertThat(s.initialWindowSize()).isEqualTo(settingsFrameValue); } } private static final class TestH2Server extends ChannelInitializer<SocketChannel> { private final Supplier<ChannelHandler> handlerSupplier; private ServerBootstrap bootstrap; private ServerSocketChannel channel; private TestH2Server(Supplier<ChannelHandler> handlerSupplier) { this.handlerSupplier = handlerSupplier; } public void init() throws InterruptedException { bootstrap = new ServerBootstrap() .channel(NioServerSocketChannel.class) .group(new NioEventLoopGroup()) .childHandler(this) .localAddress(0) .childOption(ChannelOption.SO_KEEPALIVE, true); channel = ((ServerSocketChannel) bootstrap.bind().await().channel()); } public int port() { return channel.localAddress().getPort(); } public void shutdown() throws InterruptedException { channel.close().await(); } @Override protected void initChannel(SocketChannel ch) { Http2FrameCodec codec = Http2FrameCodecBuilder.forServer() .initialSettings(new Http2Settings() .maxConcurrentStreams(5)) .build(); ch.pipeline().addLast(codec); ch.pipeline().addLast(handlerSupplier.get()); } } private static class StreamHandler extends ChannelInboundHandlerAdapter { private final Queue<Http2Frame> receivedFrames; private StreamHandler(Queue<Http2Frame> receivedFrames) { this.receivedFrames = receivedFrames; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof Http2Frame)) { ctx.fireChannelRead(msg); return; } Http2Frame frame = (Http2Frame) msg; receivedFrames.add(frame); if (frame instanceof Http2DataFrame) { Http2DataFrame dataFrame = (Http2DataFrame) frame; if (dataFrame.isEndStream()) { Http2HeadersFrame respHeaders = new DefaultHttp2HeadersFrame( new DefaultHttp2Headers().status("204"), true) .stream(dataFrame.stream()); ctx.writeAndFlush(respHeaders); } } ReferenceCountUtil.release(frame); } } }
1,356
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpToHttp2OutboundAdapterTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http2.HttpConversionUtil; import java.util.List; import org.junit.AfterClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class HttpToHttp2OutboundAdapterTest { private static final NioEventLoopGroup EVENT_LOOP_GROUP = new NioEventLoopGroup(1); @Mock public ChannelHandlerContext ctx; @Mock public Channel channel; @AfterClass public static void classTeardown() { EVENT_LOOP_GROUP.shutdownGracefully(); } @Test public void aggregatesWritePromises() { when(ctx.executor()).thenReturn(EVENT_LOOP_GROUP.next()); when(ctx.channel()).thenReturn(channel); HttpToHttp2OutboundAdapter adapter = new HttpToHttp2OutboundAdapter(); ChannelPromise writePromise = new DefaultChannelPromise(channel, EVENT_LOOP_GROUP.next()); writeRequest(adapter, writePromise); ArgumentCaptor<ChannelPromise> writePromiseCaptor = ArgumentCaptor.forClass(ChannelPromise.class); verify(ctx, atLeastOnce()).write(any(Object.class), writePromiseCaptor.capture()); List<ChannelPromise> writePromises = writePromiseCaptor.getAllValues(); assertThat(writePromise.isDone()).isFalse(); writePromises.forEach(ChannelPromise::setSuccess); assertThat(writePromise.isDone()).isTrue(); } private void writeRequest(HttpToHttp2OutboundAdapter adapter, ChannelPromise promise) { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/", Unpooled.wrappedBuffer(new byte[16])); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), "http"); adapter.write(ctx, request, promise); } }
1,357
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/MultiplexedChannelRecordTest.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 org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; import io.netty.handler.codec.http2.Http2MultiplexHandler; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.time.Duration; import java.util.concurrent.CompletableFuture; 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.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.http.nio.netty.internal.MockChannel; import software.amazon.awssdk.http.nio.netty.internal.UnusedChannelExceptionHandler; public class MultiplexedChannelRecordTest { private EventLoopGroup loopGroup; private MockChannel channel; @BeforeEach public void setup() throws Exception { loopGroup = new NioEventLoopGroup(4); channel = new MockChannel(); } @AfterEach public void teardown() { loopGroup.shutdownGracefully().awaitUninterruptibly(); channel.close(); } @Test public void nullIdleTimeoutSeemsToDisableReaping() throws InterruptedException { EmbeddedChannel channel = newHttp2Channel(); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, null); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); record.acquireStream(streamPromise); channel.runPendingTasks(); assertThat(streamPromise.isSuccess()).isTrue(); assertThat(channel.isOpen()).isTrue(); record.closeAndReleaseChild(streamPromise.getNow()); assertThat(channel.isOpen()).isTrue(); Thread.sleep(1_000); channel.runPendingTasks(); assertThat(channel.isOpen()).isTrue(); } @Test public void recordsWithoutReservedStreamsAreClosedAfterTimeout() throws InterruptedException { int idleTimeoutMillis = 1000; EmbeddedChannel channel = newHttp2Channel(); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, Duration.ofMillis(idleTimeoutMillis)); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); record.acquireStream(streamPromise); channel.runPendingTasks(); assertThat(streamPromise.isSuccess()).isTrue(); assertThat(channel.isOpen()).isTrue(); record.closeAndReleaseChild(streamPromise.getNow()); assertThat(channel.isOpen()).isTrue(); Thread.sleep(idleTimeoutMillis * 2); channel.runPendingTasks(); assertThat(channel.isOpen()).isFalse(); } @Test public void recordsWithReservedStreamsAreNotClosedAfterTimeout() throws InterruptedException { int idleTimeoutMillis = 1000; EmbeddedChannel channel = newHttp2Channel(); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis)); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); Promise<Channel> streamPromise2 = channel.eventLoop().newPromise(); record.acquireStream(streamPromise); record.acquireStream(streamPromise2); channel.runPendingTasks(); assertThat(streamPromise.isSuccess()).isTrue(); assertThat(streamPromise2.isSuccess()).isTrue(); assertThat(channel.isOpen()).isTrue(); record.closeAndReleaseChild(streamPromise.getNow()); assertThat(channel.isOpen()).isTrue(); Thread.sleep(idleTimeoutMillis * 2); channel.runPendingTasks(); assertThat(channel.isOpen()).isTrue(); } @Test public void acquireRequestResetsCloseTimer() throws InterruptedException { int idleTimeoutMillis = 1000; EmbeddedChannel channel = newHttp2Channel(); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis)); for (int i = 0; i < 20; ++i) { Thread.sleep(idleTimeoutMillis / 10); channel.runPendingTasks(); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); assertThat(record.acquireStream(streamPromise)).isTrue(); channel.runPendingTasks(); assertThat(streamPromise.isSuccess()).isTrue(); assertThat(channel.isOpen()).isTrue(); record.closeAndReleaseChild(streamPromise.getNow()); channel.runPendingTasks(); } assertThat(channel.isOpen()).isTrue(); Thread.sleep(idleTimeoutMillis * 2); channel.runPendingTasks(); assertThat(channel.isOpen()).isFalse(); } @Test public void idleTimerDoesNotApplyBeforeFirstChannelIsCreated() throws InterruptedException { int idleTimeoutMillis = 1000; EmbeddedChannel channel = newHttp2Channel(); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis)); Thread.sleep(idleTimeoutMillis * 2); channel.runPendingTasks(); assertThat(channel.isOpen()).isTrue(); } @Test public void availableStream0_reusableShouldBeFalse() { loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 0, Duration.ofSeconds(10)); assertThat(record.acquireStream(null)).isFalse(); } @Test public void acquireClaimedConnection_channelClosed_shouldThrowIOException() { loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 1, Duration.ofSeconds(10)); record.closeChildChannels(); record.acquireClaimedStream(channelPromise); assertThatThrownBy(() -> channelPromise.get()).hasCauseInstanceOf(IOException.class); } @Test public void closeChildChannels_shouldDeliverException() throws Exception { EmbeddedChannel channel = newHttp2Channel(); loopGroup.register(channel).awaitUninterruptibly(); Promise<Channel> channelPromise = new DefaultPromise<>(loopGroup.next()); channelPromise.setSuccess(channel); MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofSeconds(10)); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); record.acquireStream(streamPromise); channel.runPendingTasks(); Channel childChannel = streamPromise.get(); VerifyExceptionHandler verifyExceptionHandler = new VerifyExceptionHandler(); childChannel.pipeline().addFirst(verifyExceptionHandler); IOException ioException = new IOException("foobar"); record.closeChildChannels(ioException); assertThat(childChannel.pipeline().get(UnusedChannelExceptionHandler.class)).isNotNull(); assertThat(verifyExceptionHandler.exceptionCaught).hasStackTraceContaining("foobar") .hasRootCauseInstanceOf(IOException.class); // should be closed by UnusedChannelExceptionHandler assertThat(childChannel.isOpen()).isFalse(); } @Test public void closeToNewStreams_AcquireStreamShouldReturnFalse() { MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofSeconds(10)); Promise<Channel> streamPromise = channel.eventLoop().newPromise(); assertThat(record.acquireStream(streamPromise)).isTrue(); record.closeToNewStreams(); assertThat(record.acquireStream(streamPromise)).isFalse(); } private static final class VerifyExceptionHandler extends ChannelInboundHandlerAdapter { private Throwable exceptionCaught; @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { exceptionCaught = cause; ctx.fireExceptionCaught(cause); } } private EmbeddedChannel newHttp2Channel() { EmbeddedChannel channel = new EmbeddedChannel(Http2FrameCodecBuilder.forClient().build(), new Http2MultiplexHandler(new NoOpHandler())); channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2)); return channel; } private static class NoOpHandler extends ChannelInitializer<Channel> { @Override protected void initChannel(Channel ch) { } } }
1,358
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2PingHandlerTest.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.time.temporal.ChronoUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http2.DefaultHttp2PingFrame; import io.netty.handler.codec.http2.Http2PingFrame; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; public class Http2PingHandlerTest { private static final int FAST_CHECKER_DURATION_MILLIS = 100; private Http2PingHandler fastChecker; private Http2PingHandler slowChecker; @BeforeEach public void setup() throws Exception { this.fastChecker = new Http2PingHandler(FAST_CHECKER_DURATION_MILLIS); this.slowChecker = new Http2PingHandler(30 * 1_000); } @Test public void register_withoutProtocol_Fails() { EmbeddedChannel channel = new EmbeddedChannel(slowChecker); assertThat(channel.pipeline().get(Http2PingHandler.class)).isNull(); } @Test public void register_withIncompleteProtocol_doesNotPing() { EmbeddedChannel channel = createChannelWithoutProtocol(fastChecker); channel.runPendingTasks(); DefaultHttp2PingFrame sentFrame = channel.readOutbound(); assertThat(sentFrame).isNull(); } @Test public void register_withHttp1Protocol_doesNotPing() { EmbeddedChannel channel = createHttp1Channel(fastChecker); channel.runPendingTasks(); DefaultHttp2PingFrame sentFrame = channel.readOutbound(); assertThat(sentFrame).isNull(); } @Test public void register_WithHttp2Protocol_pingsImmediately() { EmbeddedChannel channel = createHttp2Channel(slowChecker); channel.runPendingTasks(); DefaultHttp2PingFrame sentFrame = channel.readOutbound(); assertThat(sentFrame).isNotNull(); assertThat(sentFrame.ack()).isFalse(); } @Test public void unregister_stopsRunning() throws InterruptedException { EmbeddedChannel channel = createHttp2Channel(fastChecker); channel.pipeline().remove(Http2PingHandler.class); // Flush out any tasks that happened before we closed channel.runPendingTasks(); while (channel.readOutbound() != null) { // Discard } Thread.sleep(FAST_CHECKER_DURATION_MILLIS); DefaultHttp2PingFrame sentFrame = channel.readOutbound(); assertThat(sentFrame).isNull(); } @Test public void ignoredPingsResultInOneChannelException() throws InterruptedException { PipelineExceptionCatcher catcher = new PipelineExceptionCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher); Thread.sleep(FAST_CHECKER_DURATION_MILLIS); channel.runPendingTasks(); assertThat(catcher.caughtExceptions).hasSize(1); assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class); } @Test public void respondedToPingsResultInNoAction() { PipelineExceptionCatcher catcher = new PipelineExceptionCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher); channel.eventLoop().scheduleAtFixedRate(() -> channel.writeInbound(new DefaultHttp2PingFrame(0, true)), 0, FAST_CHECKER_DURATION_MILLIS, TimeUnit.MILLISECONDS); Instant runEnd = Instant.now().plus(1, SECONDS); while (Instant.now().isBefore(runEnd)) { channel.runPendingTasks(); } assertThat(catcher.caughtExceptions).isEmpty(); } @Test public void nonAckPingsResultInOneChannelException() { PipelineExceptionCatcher catcher = new PipelineExceptionCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher); channel.eventLoop().scheduleAtFixedRate(() -> channel.writeInbound(new DefaultHttp2PingFrame(0, false)), 0, FAST_CHECKER_DURATION_MILLIS, TimeUnit.MILLISECONDS); Instant runEnd = Instant.now().plus(1, SECONDS); while (Instant.now().isBefore(runEnd)) { channel.runPendingTasks(); } assertThat(catcher.caughtExceptions).hasSize(1); assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class); } @Test public void failedWriteResultsInOneChannelException() throws InterruptedException { PipelineExceptionCatcher catcher = new PipelineExceptionCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher, new FailingWriter()); channel.runPendingTasks(); assertThat(catcher.caughtExceptions).hasSize(1); assertThat(catcher.caughtExceptions.get(0)).isInstanceOf(IOException.class); } @Test public void ackPingsAreNotForwardedToOtherHandlers() throws InterruptedException { PingReadCatcher catcher = new PingReadCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher); channel.writeInbound(new DefaultHttp2PingFrame(0, true)); channel.runPendingTasks(); assertThat(catcher.caughtPings).isEmpty(); } private static EmbeddedChannel createChannelWithoutProtocol(ChannelHandler... handlers) { EmbeddedChannel channel = new EmbeddedChannel(); channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(new CompletableFuture<>()); channel.pipeline().addLast(handlers); return channel; } private static EmbeddedChannel createHttp1Channel(ChannelHandler... handlers) { EmbeddedChannel channel = createChannelWithoutProtocol(handlers); channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().complete(Protocol.HTTP1_1); return channel; } private static EmbeddedChannel createHttp2Channel(ChannelHandler... handlers) { EmbeddedChannel channel = createChannelWithoutProtocol(handlers); channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().complete(Protocol.HTTP2); return channel; } @Test public void nonAckPingsAreForwardedToOtherHandlers() throws InterruptedException { PingReadCatcher catcher = new PingReadCatcher(); EmbeddedChannel channel = createHttp2Channel(fastChecker, catcher); channel.writeInbound(new DefaultHttp2PingFrame(0, false)); channel.runPendingTasks(); assertThat(catcher.caughtPings).hasSize(1); } @Test public void channelInactive_shouldCancelTaskAndForwardToOtherHandlers() { EmbeddedChannel channel = createHttp2Channel(fastChecker); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); fastChecker.channelInactive(context); Mockito.verify(context).fireChannelInactive(); channel.writeInbound(new DefaultHttp2PingFrame(0, false)); assertThat(channel.runScheduledPendingTasks()).isEqualTo(-1L); } private static final class PingReadCatcher extends SimpleChannelInboundHandler<Http2PingFrame> { private final List<Http2PingFrame> caughtPings = Collections.synchronizedList(new ArrayList<>()); @Override protected void channelRead0(ChannelHandlerContext ctx, Http2PingFrame msg) { caughtPings.add(msg); } } private static final class PipelineExceptionCatcher extends ChannelInboundHandlerAdapter { private final List<Throwable> caughtExceptions = Collections.synchronizedList(new ArrayList<>()); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { caughtExceptions.add(cause); super.exceptionCaught(ctx, cause); } } private static final class FailingWriter extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { promise.setFailure(new IOException("Failed!")); } } }
1,359
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/FlushOnReadTest.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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class FlushOnReadTest { @Mock private ChannelHandlerContext mockCtx; @Mock private Channel mockChannel; @Mock private Channel mockParentChannel; @Test public void read_forwardsReadBeforeParentFlush() { when(mockCtx.channel()).thenReturn(mockChannel); when(mockChannel.parent()).thenReturn(mockParentChannel); FlushOnReadHandler handler = FlushOnReadHandler.getInstance(); handler.read(mockCtx); InOrder inOrder = Mockito.inOrder(mockCtx, mockParentChannel); inOrder.verify(mockCtx).read(); inOrder.verify(mockParentChannel).flush(); } @Test public void getInstance_returnsSingleton() { assertThat(FlushOnReadHandler.getInstance() == FlushOnReadHandler.getInstance()).isTrue(); } }
1,360
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/http2/utils/Http2TestUtils.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.utils; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.embedded.EmbeddedChannel; 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 java.util.concurrent.CompletableFuture; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; public final class Http2TestUtils { public static final int INITIAL_WINDOW_SIZE = 1_048_576; public static EmbeddedChannel newHttp2Channel() { return newHttp2Channel(new NoOpHandler()); } public static EmbeddedChannel newHttp2Channel(ChannelHandler channelHandler) { Http2FrameCodec http2FrameCodec = Http2FrameCodecBuilder.forClient().initialSettings( Http2Settings.defaultSettings().initialWindowSize(INITIAL_WINDOW_SIZE)) .frameLogger(new Http2FrameLogger(LogLevel.DEBUG)).build(); EmbeddedChannel channel = new EmbeddedChannel(http2FrameCodec, new Http2MultiplexHandler(channelHandler)); channel.attr(ChannelAttributeKey.HTTP2_CONNECTION).set(http2FrameCodec.connection()); channel.attr(ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE).set(INITIAL_WINDOW_SIZE); channel.attr(ChannelAttributeKey.PROTOCOL_FUTURE).set(CompletableFuture.completedFuture(Protocol.HTTP2)); return channel; } private static class NoOpHandler extends ChannelInitializer<Channel> { @Override protected void initChannel(Channel ch) { } } }
1,361
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/ChannelPublisherTest.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; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Promise; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; /** * 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 ChannelPublisherTest { private EventLoopGroup group; private Channel channel; private Publisher<Channel> publisher; private SubscriberProbe<Channel> subscriber; @BeforeEach public void start() throws Exception { group = new NioEventLoopGroup(); EventLoop eventLoop = group.next(); HandlerPublisher<Channel> handlerPublisher = new HandlerPublisher<>(eventLoop, Channel.class); Bootstrap bootstrap = new Bootstrap(); bootstrap .channel(NioServerSocketChannel.class) .group(eventLoop) .option(ChannelOption.AUTO_READ, false) .handler(handlerPublisher) .localAddress("127.0.0.1", 0); channel = bootstrap.bind().await().channel(); this.publisher = handlerPublisher; subscriber = new SubscriberProbe<>(); } @AfterEach public void stop() throws Exception { channel.unsafe().closeForcibly(); group.shutdownGracefully(); } @Test public void test() throws Exception { publisher.subscribe(subscriber); Subscription sub = subscriber.takeSubscription(); // Try one cycle sub.request(1); Socket socket1 = connect(); receiveConnection(); readWriteData(socket1, 1); // Check back pressure Socket socket2 = connect(); subscriber.expectNoElements(); // Now request the next connection sub.request(1); receiveConnection(); readWriteData(socket2, 2); // Close the channel channel.close(); subscriber.expectNoElements(); subscriber.expectComplete(); } private Socket connect() throws Exception { InetSocketAddress address = (InetSocketAddress) channel.localAddress(); return new Socket(address.getAddress(), address.getPort()); } private void readWriteData(Socket socket, int data) throws Exception { OutputStream os = socket.getOutputStream(); os.write(data); os.flush(); InputStream is = socket.getInputStream(); int received = is.read(); socket.close(); assertEquals(received, data); } private void receiveConnection() throws Exception { Channel channel = subscriber.take(); channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.writeAndFlush(msg); } }); group.register(channel); } private class SubscriberProbe<T> implements Subscriber<T> { final BlockingQueue<Subscription> subscriptions = new LinkedBlockingQueue<>(); final BlockingQueue<T> elements = new LinkedBlockingQueue<>(); final Promise<Void> promise = new DefaultPromise<>(group.next()); public void onSubscribe(Subscription s) { subscriptions.add(s); } public void onNext(T t) { elements.add(t); } public void onError(Throwable t) { promise.setFailure(t); } public void onComplete() { promise.setSuccess(null); } Subscription takeSubscription() throws Exception { Subscription sub = subscriptions.poll(100, TimeUnit.MILLISECONDS); assertNotNull(sub); return sub; } T take() throws Exception { T t = elements.poll(1000, TimeUnit.MILLISECONDS); assertNotNull(t); return t; } void expectNoElements() throws Exception { T t = elements.poll(100, TimeUnit.MILLISECONDS); assertNull(t); } void expectComplete() throws Exception { promise.get(100, TimeUnit.MILLISECONDS); } } }
1,362
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerPublisherVerificationTest.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; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.local.LocalChannel; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import software.amazon.awssdk.http.nio.netty.internal.nrs.util.BatchedProducer; import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ClosedLoopChannel; import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ScheduledBatchedProducer; /** * 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 HandlerPublisherVerificationTest extends PublisherVerification<Long> { private final int batchSize; // The number of elements to publish initially, before the subscriber is received private final int publishInitial; // Whether we should use scheduled publishing (with a small delay) private final boolean scheduled; private ScheduledExecutorService executor; private DefaultEventLoopGroup eventLoop; @Factory(dataProvider = "data") public HandlerPublisherVerificationTest(int batchSize, int publishInitial, boolean scheduled) { super(new TestEnvironment(200)); this.batchSize = batchSize; this.publishInitial = publishInitial; this.scheduled = scheduled; } @DataProvider public static Object[][] data() { final int defaultBatchSize = 3; final int defaultPublishInitial = 3; final boolean defaultScheduled = false; return new Object[][] { { defaultBatchSize, defaultPublishInitial, defaultScheduled }, { 1, defaultPublishInitial, defaultScheduled }, { defaultBatchSize, 0, defaultScheduled }, { defaultBatchSize, defaultPublishInitial, true } }; } // I tried making this before/after class, but encountered a strange error where after 32 publishers were created, // the following tests complained about the executor being shut down when I registered the channel. Though, it // doesn't happen if you create 32 publishers in a single test. @BeforeMethod public void startEventLoop() { eventLoop = new DefaultEventLoopGroup(); } @AfterMethod public void stopEventLoop() { eventLoop.shutdownGracefully(); eventLoop = null; } @BeforeClass public void startExecutor() { executor = Executors.newSingleThreadScheduledExecutor(); } @AfterClass public void stopExecutor() { executor.shutdown(); } @Override public Publisher<Long> createPublisher(final long elements) { final BatchedProducer out; if (scheduled) { out = new ScheduledBatchedProducer(elements, batchSize, publishInitial, executor, 5); } else { out = new BatchedProducer(elements, batchSize, publishInitial, executor); } final ClosedLoopChannel channel = new ClosedLoopChannel(); channel.config().setAutoRead(false); ChannelFuture registered = eventLoop.register(channel); final HandlerPublisher<Long> publisher = new HandlerPublisher<>(registered.channel().eventLoop(), Long.class); registered.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().addLast("out", out); channel.pipeline().addLast("publisher", publisher); for (long i = 0; i < publishInitial && i < elements; i++) { channel.pipeline().fireChannelRead(i); } if (elements <= publishInitial) { channel.pipeline().fireChannelInactive(); } } }); return publisher; } @Override public Publisher<Long> createFailedPublisher() { LocalChannel channel = new LocalChannel(); eventLoop.register(channel); HandlerPublisher<Long> publisher = new HandlerPublisher<>(channel.eventLoop(), Long.class); channel.pipeline().addLast("publisher", publisher); channel.pipeline().fireExceptionCaught(new RuntimeException("failed")); return publisher; } @Override public void stochastic_spec103_mustSignalOnMethodsSequentially() throws Throwable { try { super.stochastic_spec103_mustSignalOnMethodsSequentially(); } catch (Throwable t) { // CI is failing here, but maven doesn't tell us which parameters failed System.out.println("Stochastic test failed with parameters batchSize=" + batchSize + " publishInitial=" + publishInitial + " scheduled=" + scheduled); throw t; } } }
1,363
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberTest.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; import static org.assertj.core.api.Assertions.assertThat; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.concurrent.AbstractEventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.internal.ObjectUtil; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; /** * 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 HandlerSubscriberTest { private EmbeddedChannel channel; private CustomEmbeddedEventLoop eventLoop; private HandlerSubscriber<HttpContent> handler; @BeforeEach public void setup() throws Exception { channel = new CustomEmbeddedChannel(); eventLoop = new CustomEmbeddedEventLoop(); eventLoop.register(channel).syncUninterruptibly(); handler = new HandlerSubscriber<>(eventLoop); channel.pipeline().addLast(handler); } @AfterEach public void teardown() { channel.close(); } /** * Ensures that onNext invocations against the {@link HandlerSubscriber} do not order things based on which thread is calling * onNext. */ @Test public void onNextWritesInProperOrderFromAnyThread() { HttpContent front = emptyHttpRequest(); HttpContent back = emptyHttpRequest(); handler.onSubscribe(doNothingSubscription()); eventLoop.inEventLoop(false); handler.onNext(front); eventLoop.inEventLoop(true); handler.onNext(back); eventLoop.runTasks(); Queue<Object> outboundMessages = channel.outboundMessages(); assertThat(outboundMessages).hasSize(2); assertThat(outboundMessages.poll()).isSameAs(front); assertThat(outboundMessages.poll()).isSameAs(back); } private DefaultFullHttpRequest emptyHttpRequest() { return new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://fake.com"); } private Subscription doNothingSubscription() { return new Subscription() { @Override public void request(long n) { } @Override public void cancel() { } }; } private static class CustomEmbeddedChannel extends EmbeddedChannel { public volatile CustomEmbeddedEventLoop loop; private CustomEmbeddedChannel() { super(false, false); } @Override protected boolean isCompatible(EventLoop loop) { return loop instanceof CustomEmbeddedEventLoop; } @Override public void runPendingTasks() { loop.runTasks(); } } private static class CustomEmbeddedEventLoop extends AbstractEventExecutor implements EventLoop { private final Queue<Runnable> tasks = new ArrayDeque<>(2); private volatile boolean inEventLoop = true; @Override public EventLoopGroup parent() { return (EventLoopGroup) super.parent(); } @Override public EventLoop next() { return (EventLoop) super.next(); } @Override public void execute(Runnable runnable) { tasks.add(runnable); } public void runTasks() { for (;;) { Runnable task = tasks.poll(); if (task == null) { break; } task.run(); } } @Override public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { throw new UnsupportedOperationException(); } @Override public Future<?> terminationFuture() { throw new UnsupportedOperationException(); } @Override @Deprecated public void shutdown() { throw new UnsupportedOperationException(); } @Override public boolean isShuttingDown() { return false; } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) { return false; } @Override public ChannelFuture register(Channel channel) { ((CustomEmbeddedChannel) channel).loop = this; return register(new DefaultChannelPromise(channel, this)); } @Override public ChannelFuture register(ChannelPromise promise) { ObjectUtil.checkNotNull(promise, "promise"); promise.channel().unsafe().register(this, promise); return promise; } @Deprecated @Override public ChannelFuture register(Channel channel, ChannelPromise promise) { channel.unsafe().register(this, promise); return promise; } public void inEventLoop(boolean inEventLoop) { this.inEventLoop = inEventLoop; } @Override public boolean inEventLoop() { return inEventLoop; } @Override public boolean inEventLoop(Thread thread) { return inEventLoop; } } }
1,364
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberBlackboxVerificationTest.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; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.embedded.EmbeddedChannel; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberBlackboxVerification; import org.reactivestreams.tck.TestEnvironment; /** * 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 HandlerSubscriberBlackboxVerificationTest extends SubscriberBlackboxVerification<Long> { public HandlerSubscriberBlackboxVerificationTest() { super(new TestEnvironment()); } @Override public Subscriber<Long> createSubscriber() { // Embedded channel requires at least one handler when it's created, but HandlerSubscriber // needs the channels event loop in order to be created, so start with a dummy, then replace. ChannelHandler dummy = new ChannelDuplexHandler(); EmbeddedChannel channel = new EmbeddedChannel(dummy); HandlerSubscriber<Long> subscriber = new HandlerSubscriber<>(channel.eventLoop(), 2, 4); channel.pipeline().replace(dummy, "subscriber", subscriber); return new SubscriberWithChannel<>(channel, subscriber); } @Override public Long createElement(int element) { return (long) element; } @Override public void triggerRequest(Subscriber<? super Long> subscriber) { EmbeddedChannel channel = ((SubscriberWithChannel) subscriber).channel; channel.runPendingTasks(); while (channel.readOutbound() != null) { channel.runPendingTasks(); } channel.runPendingTasks(); } /** * Delegate subscriber that makes the embedded channel available so we can talk to it to trigger a request. */ private static class SubscriberWithChannel<T> implements Subscriber<T> { final EmbeddedChannel channel; final HandlerSubscriber<T> subscriber; public SubscriberWithChannel(EmbeddedChannel channel, HandlerSubscriber<T> subscriber) { this.channel = channel; this.subscriber = subscriber; } public void onSubscribe(Subscription s) { subscriber.onSubscribe(s); } public void onNext(T t) { subscriber.onNext(t); } public void onError(Throwable t) { subscriber.onError(t); } public void onComplete() { subscriber.onComplete(); } } }
1,365
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/test/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriberWhiteboxVerificationTest.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; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.DefaultEventLoopGroup; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Promise; import org.reactivestreams.Subscriber; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ClosedLoopChannel; import software.amazon.awssdk.http.nio.netty.internal.nrs.util.ProbeHandler; /** * 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 HandlerSubscriberWhiteboxVerificationTest extends SubscriberWhiteboxVerification<Long> { private boolean workAroundIssue277; public HandlerSubscriberWhiteboxVerificationTest() { super(new TestEnvironment()); } private DefaultEventLoopGroup eventLoop; // I tried making this before/after class, but encountered a strange error where after 32 publishers were created, // the following tests complained about the executor being shut down when I registered the channel. Though, it // doesn't happen if you create 32 publishers in a single test. @BeforeMethod public void startEventLoop() { workAroundIssue277 = false; eventLoop = new DefaultEventLoopGroup(); } @AfterMethod public void stopEventLoop() { eventLoop.shutdownGracefully(); eventLoop = null; } @Override public Subscriber<Long> createSubscriber(WhiteboxSubscriberProbe<Long> probe) { final ClosedLoopChannel channel = new ClosedLoopChannel(); channel.config().setAutoRead(false); ChannelFuture registered = eventLoop.register(channel); final HandlerSubscriber<Long> subscriber = new HandlerSubscriber<>(registered.channel().eventLoop(), 2, 4); final ProbeHandler<Long> probeHandler = new ProbeHandler<>(probe, Long.class); final Promise<Void> handlersInPlace = new DefaultPromise<>(eventLoop.next()); registered.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel.pipeline().addLast("probe", probeHandler); channel.pipeline().addLast("subscriber", subscriber); handlersInPlace.setSuccess(null); // Channel needs to be active before the subscriber starts responding to demand channel.pipeline().fireChannelActive(); } }); if (workAroundIssue277) { try { // Wait for the pipeline to be setup, so we're ready to receive elements even if they aren't requested, // because https://github.com/reactive-streams/reactive-streams-jvm/issues/277 handlersInPlace.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } return probeHandler.wrap(subscriber); } @Override public void required_spec208_mustBePreparedToReceiveOnNextSignalsAfterHavingCalledSubscriptionCancel() throws Throwable { // See https://github.com/reactive-streams/reactive-streams-jvm/issues/277 workAroundIssue277 = true; super.required_spec208_mustBePreparedToReceiveOnNextSignalsAfterHavingCalledSubscriptionCancel(); } @Override public void required_spec308_requestMustRegisterGivenNumberElementsToBeProduced() throws Throwable { workAroundIssue277 = true; super.required_spec308_requestMustRegisterGivenNumberElementsToBeProduced(); } @Override public Long createElement(int element) { return (long) element; } }
1,366
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/BatchedProducer.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 io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import java.util.concurrent.Executor; /** * 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 BatchedProducer extends ChannelOutboundHandlerAdapter { protected final long eofOn; protected final int batchSize; private final Executor executor; protected long sequence; public BatchedProducer(long eofOn, int batchSize, long sequence, Executor executor) { this.eofOn = eofOn; this.batchSize = batchSize; this.sequence = sequence; this.executor = executor; } private boolean cancelled = false; @Override public void read(final ChannelHandlerContext ctx) throws Exception { if (cancelled) { throw new IllegalStateException("Received demand after being cancelled"); } executor.execute(() -> { for (int i = 0; i < batchSize && sequence != eofOn; i++) { ctx.fireChannelRead(sequence++); } if (eofOn == sequence) { ctx.fireChannelInactive(); } else { ctx.fireChannelReadComplete(); } }); } @Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { if (cancelled) { throw new IllegalStateException("Cancelled twice"); } cancelled = true; } }
1,367
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/PublisherProbe.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 org.reactivestreams.Publisher; import org.reactivestreams.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. */ public class PublisherProbe<T> extends Probe implements Publisher<T> { private final Publisher<T> publisher; public PublisherProbe(Publisher<T> publisher, String name) { super(name); this.publisher = publisher; } @Override public void subscribe(Subscriber<? super T> s) { String sName = s == null ? "null" : s.getClass().getName(); log("invoke subscribe with subscriber " + sName); publisher.subscribe(new SubscriberProbe<>(s, name, start)); log("finish subscribe"); } }
1,368
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/ClosedLoopChannel.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.AbstractChannel; import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelConfig; import io.netty.channel.EventLoop; import java.net.SocketAddress; /** * A closed loop channel that sends no events and receives no events, for testing purposes. * * Any outgoing events that reach the channel will throw an exception. All events should be caught * be inserting a handler that catches them and responds accordingly. * * 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 ClosedLoopChannel extends AbstractChannel { private final ChannelConfig config = new DefaultChannelConfig(this); private static final ChannelMetadata metadata = new ChannelMetadata(false); private volatile boolean open = true; private volatile boolean active = true; public ClosedLoopChannel() { super(null); } public void setOpen(boolean open) { this.open = open; } public void setActive(boolean active) { this.active = active; } @Override protected AbstractUnsafe newUnsafe() { return new AbstractUnsafe() { @Override public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { throw new UnsupportedOperationException(); } }; } @Override protected boolean isCompatible(EventLoop loop) { return true; } @Override protected SocketAddress localAddress0() { throw new UnsupportedOperationException(); } @Override protected SocketAddress remoteAddress0() { throw new UnsupportedOperationException(); } @Override protected void doBind(SocketAddress localAddress) throws Exception { throw new UnsupportedOperationException(); } @Override protected void doDisconnect() throws Exception { throw new UnsupportedOperationException(); } @Override protected void doClose() throws Exception { this.open = false; } @Override protected void doBeginRead() throws Exception { throw new UnsupportedOperationException(); } @Override protected void doWrite(ChannelOutboundBuffer in) throws Exception { throw new UnsupportedOperationException(); } @Override public ChannelConfig config() { return config; } @Override public boolean isOpen() { return open; } @Override public boolean isActive() { return active; } @Override public ChannelMetadata metadata() { return metadata; } }
1,369
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/Probe.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 java.util.Date; /** * 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 Probe { protected final String name; protected final Long start; /** * Create a new probe and log that it started. */ protected Probe(String name) { this.name = name; start = System.nanoTime(); log("Probe created at " + new Date()); } /** * Create a new probe with the start time from another probe. */ protected Probe(String name, long start) { this.name = name; this.start = start; } protected void log(String message) { System.out.println(String.format("%10d %-5s %-15s %s", (System.nanoTime() - start) / 1000, name, Thread.currentThread().getName(), message)); } }
1,370
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/SubscriberProbe.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 org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; /** * 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 SubscriberProbe<T> extends Probe implements Subscriber<T> { private final Subscriber<T> subscriber; public SubscriberProbe(Subscriber<T> subscriber, String name) { super(name); this.subscriber = subscriber; } SubscriberProbe(Subscriber<T> subscriber, String name, long start) { super(name, start); this.subscriber = subscriber; } @Override public void onSubscribe(final Subscription s) { String sName = s == null ? "null" : s.getClass().getName(); log("invoke onSubscribe with subscription " + sName); subscriber.onSubscribe(new Subscription() { @Override public void request(long n) { log("invoke request " + n); s.request(n); log("finish request"); } @Override public void cancel() { log("invoke cancel"); s.cancel(); log("finish cancel"); } }); log("finish onSubscribe"); } @Override public void onNext(T t) { log("invoke onNext with message " + t); subscriber.onNext(t); log("finish onNext"); } @Override public void onError(Throwable t) { String tName = t == null ? "null" : t.getClass().getName(); log("invoke onError with " + tName); subscriber.onError(t); log("finish onError"); } @Override public void onComplete() { log("invoke onComplete"); subscriber.onComplete(); log("finish onComplete"); } }
1,371
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/ProbeHandler.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.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; /** * 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 ProbeHandler<T> extends ChannelDuplexHandler implements SubscriberWhiteboxVerification.SubscriberPuppet { private static final int NO_CONTEXT = 0; private static final int RUN = 1; private static final int CANCEL = 2; private final SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<T> probe; private final Class<T> clazz; private final Queue<WriteEvent> queue = new LinkedList<>(); private final AtomicInteger state = new AtomicInteger(NO_CONTEXT); private volatile ChannelHandlerContext ctx; // Netty doesn't provide a way to send errors out, so we capture whether it was an error or complete here private volatile Throwable receivedError = null; public ProbeHandler(SubscriberWhiteboxVerification.WhiteboxSubscriberProbe<T> probe, Class<T> clazz) { this.probe = probe; this.clazz = clazz; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; if (!state.compareAndSet(NO_CONTEXT, RUN)) { ctx.fireChannelInactive(); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { queue.add(new WriteEvent(clazz.cast(msg), promise)); } @Override public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (receivedError == null) { probe.registerOnComplete(); } else { probe.registerOnError(receivedError); } } @Override public void flush(ChannelHandlerContext ctx) throws Exception { while (!queue.isEmpty()) { WriteEvent event = queue.remove(); probe.registerOnNext(event.msg); event.future.setSuccess(); } } @Override public void triggerRequest(long elements) { // No need, the channel automatically requests } @Override public void signalCancel() { if (!state.compareAndSet(NO_CONTEXT, CANCEL)) { ctx.fireChannelInactive(); } } private class WriteEvent { final T msg; final ChannelPromise future; private WriteEvent(T msg, ChannelPromise future) { this.msg = msg; this.future = future; } } public Subscriber<T> wrap(final Subscriber<T> subscriber) { return new Subscriber<T>() { public void onSubscribe(Subscription s) { probe.registerOnSubscribe(ProbeHandler.this); subscriber.onSubscribe(s); } public void onNext(T t) { subscriber.onNext(t); } public void onError(Throwable t) { receivedError = t; subscriber.onError(t); } public void onComplete() { subscriber.onComplete(); } }; } }
1,372
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,373
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,374
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,375
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,376
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,377
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,378
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,379
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,380
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,381
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,382
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,383
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,384
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,385
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,386
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,387
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,388
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,389
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,390
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,391
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,392
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,393
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,394
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,395
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,396
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,397
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,398
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,399