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/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelledException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi final class FutureCancelledException extends RuntimeException { private final long executionId; FutureCancelledException(long executionId, Throwable cause) { super(cause); this.executionId = executionId; } long getExecutionId() { return executionId; } }
1,400
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/InUseTrackingChannelPoolListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.IN_USE; import io.netty.channel.Channel; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.ListenerInvokingChannelPool.ChannelPoolListener; import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils; /** * Marks {@link Channel}s as in-use when they are leased from the pool. An in-use channel is not eligible to be closed by {@link * IdleConnectionReaperHandler} or {@link OldConnectionReaperHandler}. */ @SdkInternalApi public final class InUseTrackingChannelPoolListener implements ChannelPoolListener { private static final InUseTrackingChannelPoolListener INSTANCE = new InUseTrackingChannelPoolListener(); private InUseTrackingChannelPoolListener() { } public static InUseTrackingChannelPoolListener create() { return INSTANCE; } @Override public void channelAcquired(Channel channel) { channel.attr(IN_USE).set(true); ChannelUtils.getAttribute(channel, CHANNEL_DIAGNOSTICS).ifPresent(ChannelDiagnostics::stopIdleTimer); } @Override public void channelReleased(Channel channel) { channel.attr(IN_USE).set(false); ChannelUtils.getAttribute(channel, CHANNEL_DIAGNOSTICS).ifPresent(ChannelDiagnostics::startIdleTimer); } }
1,401
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/HandlerRemovingChannelPoolListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.removeIfExists; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.ListenerInvokingChannelPool.ChannelPoolListener; import software.amazon.awssdk.http.nio.netty.internal.http2.FlushOnReadHandler; import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler; /** * Removes any per-request {@link ChannelHandler} from the pipeline when releasing it to the pool. */ @SdkInternalApi public final class HandlerRemovingChannelPoolListener implements ChannelPoolListener { private static final HandlerRemovingChannelPoolListener INSTANCE = new HandlerRemovingChannelPoolListener(); private HandlerRemovingChannelPoolListener() { } public static HandlerRemovingChannelPoolListener create() { return INSTANCE; } @Override public void channelReleased(Channel channel) { // Only remove per request handler if the channel is registered // or open since DefaultChannelPipeline would remove handlers if // channel is closed and unregistered if (channel.isOpen() || channel.isRegistered()) { removeIfExists(channel.pipeline(), HttpStreamsClientHandler.class, FlushOnReadHandler.class, ResponseHandler.class, ReadTimeoutHandler.class, WriteTimeoutHandler.class); } } }
1,402
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/UnusedChannelExceptionHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.getAttribute; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.TimeoutException; import java.io.IOException; import java.util.Optional; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * A handler for exceptions occurring on channels not current in use (according to {@link ChannelAttributeKey#IN_USE}). This * does nothing if the channel is currently in use. If it's not currently in use, it will close the channel and log an * appropriate notification. * * This prevents spamming customer logs when errors (eg. connection resets) occur on an unused channel. */ @SdkInternalApi @ChannelHandler.Sharable public final class UnusedChannelExceptionHandler extends ChannelInboundHandlerAdapter { public static final UnusedChannelExceptionHandler INSTANCE = new UnusedChannelExceptionHandler(); private static final NettyClientLogger log = NettyClientLogger.getLogger(UnusedChannelExceptionHandler.class); private UnusedChannelExceptionHandler() { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { boolean channelInUse = getAttribute(ctx.channel(), ChannelAttributeKey.IN_USE).orElse(false); if (channelInUse) { ctx.fireExceptionCaught(cause); } else { ctx.close(); Optional<CompletableFuture<Void>> executeFuture = getAttribute(ctx.channel(), ChannelAttributeKey.EXECUTE_FUTURE_KEY); if (executeFuture.isPresent() && !executeFuture.get().isDone()) { log.error(ctx.channel(), () -> "An exception occurred on an channel (" + ctx.channel().id() + ") that was not " + "in use, but was associated with a future that wasn't completed. This " + "indicates a bug in the Java SDK, where a future was not completed while the " + "channel was in use. The channel has been closed, and the future will be " + "completed to prevent any ongoing issues.", cause); executeFuture.get().completeExceptionally(cause); } else if (isNettyIoException(cause) || hasNettyIoExceptionCause(cause)) { log.debug(ctx.channel(), () -> "An I/O exception (" + cause.getMessage() + ") occurred on a channel (" + ctx.channel().id() + ") that was not in use. The channel has been closed. This is usually normal."); } else { log.warn(ctx.channel(), () -> "A non-I/O exception occurred on a channel (" + ctx.channel().id() + ") that was " + "not in use. The channel has been closed to prevent any ongoing issues.", cause); } } } public static UnusedChannelExceptionHandler getInstance() { return INSTANCE; } private boolean isNettyIoException(Throwable cause) { return cause instanceof IOException || cause instanceof TimeoutException; } private boolean hasNettyIoExceptionCause(Throwable cause) { return cause.getCause() != null && isNettyIoException(cause.getCause()); } }
1,403
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTE_FUTURE_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.KEEP_ALIVE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_COMPLETE_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_CONTENT_LENGTH; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_DATA_READ; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.RESPONSE_STATUS_CODE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.STREAMING_COMPLETE_KEY; import static software.amazon.awssdk.http.nio.netty.internal.utils.ExceptionHandlingUtils.tryCatch; import static software.amazon.awssdk.http.nio.netty.internal.utils.ExceptionHandlingUtils.tryCatchFinally; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import java.util.stream.Collectors; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkCancellationException; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2ResetSendingSubscription; import software.amazon.awssdk.http.nio.netty.internal.nrs.HttpStreamsClientHandler; import software.amazon.awssdk.http.nio.netty.internal.nrs.StreamedHttpResponse; import software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.utils.FunctionalUtils.UnsafeRunnable; import software.amazon.awssdk.utils.async.DelegatingSubscription; @Sharable @SdkInternalApi public class ResponseHandler extends SimpleChannelInboundHandler<HttpObject> { private static final NettyClientLogger log = NettyClientLogger.getLogger(ResponseHandler.class); private static final ResponseHandler INSTANCE = new ResponseHandler(); private ResponseHandler() { } @Override protected void channelRead0(ChannelHandlerContext channelContext, HttpObject msg) throws Exception { RequestContext requestContext = channelContext.channel().attr(REQUEST_CONTEXT_KEY).get(); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; SdkHttpResponse sdkResponse = SdkHttpFullResponse.builder() .headers(fromNettyHeaders(response.headers())) .statusCode(response.status().code()) .statusText(response.status().reasonPhrase()) .build(); channelContext.channel().attr(RESPONSE_STATUS_CODE).set(response.status().code()); channelContext.channel().attr(RESPONSE_CONTENT_LENGTH).set(responseContentLength(response)); channelContext.channel().attr(KEEP_ALIVE).set(shouldKeepAlive(response)); ChannelUtils.getAttribute(channelContext.channel(), CHANNEL_DIAGNOSTICS) .ifPresent(ChannelDiagnostics::incrementResponseCount); requestContext.handler().onHeaders(sdkResponse); } CompletableFuture<Void> ef = executeFuture(channelContext); if (msg instanceof StreamedHttpResponse) { requestContext.handler().onStream( new DataCountingPublisher(channelContext, new PublisherAdapter((StreamedHttpResponse) msg, channelContext, requestContext, ef))); } else if (msg instanceof FullHttpResponse) { ByteBuf fullContent = null; try { // Be prepared to take care of (ignore) a trailing LastHttpResponse // from the HttpClientCodec if there is one. channelContext.pipeline().replace(HttpStreamsClientHandler.class, channelContext.name() + "-LastHttpContentSwallower", LastHttpContentSwallower.getInstance()); fullContent = ((FullHttpResponse) msg).content(); ByteBuffer bb = copyToByteBuffer(fullContent); requestContext.handler().onStream(new DataCountingPublisher(channelContext, new FullResponseContentPublisher(channelContext, bb, ef))); try { validateResponseContentLength(channelContext); finalizeResponse(requestContext, channelContext); } catch (IOException e) { exceptionCaught(channelContext, e); } } finally { Optional.ofNullable(fullContent).ifPresent(ByteBuf::release); } } } private Long responseContentLength(HttpResponse response) { String length = response.headers().get(HttpHeaderNames.CONTENT_LENGTH); if (length == null) { return null; } return Long.parseLong(length); } private static void validateResponseContentLength(ChannelHandlerContext ctx) throws IOException { if (!shouldValidateResponseContentLength(ctx)) { return; } Long contentLengthHeader = ctx.channel().attr(RESPONSE_CONTENT_LENGTH).get(); Long actualContentLength = ctx.channel().attr(RESPONSE_DATA_READ).get(); if (contentLengthHeader == null) { return; } if (actualContentLength == null) { actualContentLength = 0L; } if (actualContentLength.equals(contentLengthHeader)) { return; } throw new IOException("Response had content-length of " + contentLengthHeader + " bytes, but only received " + actualContentLength + " bytes before the connection was closed."); } private static boolean shouldValidateResponseContentLength(ChannelHandlerContext ctx) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); // HEAD requests may return Content-Length without a payload if (requestContext.executeRequest().request().method() == SdkHttpMethod.HEAD) { return false; } // 304 responses may contain Content-Length without a payload Integer responseStatusCode = ctx.channel().attr(RESPONSE_STATUS_CODE).get(); if (responseStatusCode != null && responseStatusCode == HttpResponseStatus.NOT_MODIFIED.code()) { return false; } return true; } /** * Finalize the response by completing the execute future and release the channel pool being used. * * @param requestContext the request context * @param channelContext the channel context */ private static void finalizeResponse(RequestContext requestContext, ChannelHandlerContext channelContext) { channelContext.channel().attr(RESPONSE_COMPLETE_KEY).set(true); executeFuture(channelContext).complete(null); if (!channelContext.channel().attr(KEEP_ALIVE).get()) { closeAndRelease(channelContext); } else { requestContext.channelPool().release(channelContext.channel()); } } private boolean shouldKeepAlive(HttpResponse response) { if (HttpStatusFamily.of(response.status().code()) == HttpStatusFamily.SERVER_ERROR) { return false; } return HttpUtil.isKeepAlive(response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); log.debug(ctx.channel(), () -> "Exception processing request: " + requestContext.executeRequest().request(), cause); Throwable throwable = NettyUtils.decorateException(ctx.channel(), cause); executeFuture(ctx).completeExceptionally(throwable); runAndLogError(ctx.channel(), () -> "Fail to execute SdkAsyncHttpResponseHandler#onError", () -> requestContext.handler().onError(throwable)); runAndLogError(ctx.channel(), () -> "Could not release channel back to the pool", () -> closeAndRelease(ctx)); } @Override public void channelInactive(ChannelHandlerContext handlerCtx) { notifyIfResponseNotCompleted(handlerCtx); } public static ResponseHandler getInstance() { return INSTANCE; } /** * Close the channel and release it back into the pool. * * @param ctx Context for channel */ private static void closeAndRelease(ChannelHandlerContext ctx) { Channel channel = ctx.channel(); channel.attr(KEEP_ALIVE).set(false); RequestContext requestContext = channel.attr(REQUEST_CONTEXT_KEY).get(); ctx.close(); requestContext.channelPool().release(channel); } /** * Runs a given {@link UnsafeRunnable} and logs an error without throwing. * * @param errorMsg Message to log with exception thrown. * @param runnable Action to perform. */ private static void runAndLogError(Channel ch, Supplier<String> errorMsg, UnsafeRunnable runnable) { try { runnable.run(); } catch (Exception e) { log.error(ch, errorMsg, e); } } private static Map<String, List<String>> fromNettyHeaders(HttpHeaders headers) { return headers.entries().stream() .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, Collectors.toList()))); } private static ByteBuffer copyToByteBuffer(ByteBuf byteBuf) { ByteBuffer bb = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.getBytes(byteBuf.readerIndex(), bb); bb.flip(); return bb; } private static CompletableFuture<Void> executeFuture(ChannelHandlerContext ctx) { return ctx.channel().attr(EXECUTE_FUTURE_KEY).get(); } static class PublisherAdapter implements Publisher<ByteBuffer> { private final StreamedHttpResponse response; private final ChannelHandlerContext channelContext; private final RequestContext requestContext; private final CompletableFuture<Void> executeFuture; private final AtomicBoolean isDone = new AtomicBoolean(false); PublisherAdapter(StreamedHttpResponse response, ChannelHandlerContext channelContext, RequestContext requestContext, CompletableFuture<Void> executeFuture) { this.response = response; this.channelContext = channelContext; this.requestContext = requestContext; this.executeFuture = executeFuture; } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { response.subscribe(new Subscriber<HttpContent>() { @Override public void onSubscribe(Subscription subscription) { subscriber.onSubscribe(new OnCancelSubscription(resolveSubscription(subscription), this::onCancel)); } private Subscription resolveSubscription(Subscription subscription) { // For HTTP2 we send a RST_STREAM frame on cancel to stop the service from sending more data if (ChannelAttributeKey.getProtocolNow(channelContext.channel()) == Protocol.HTTP2) { return new Http2ResetSendingSubscription(channelContext, subscription); } else { return subscription; } } private void onCancel() { if (!isDone.compareAndSet(false, true)) { return; } try { SdkCancellationException e = new SdkCancellationException( "Subscriber cancelled before all events were published"); log.warn(channelContext.channel(), () -> "Subscriber cancelled before all events were published"); executeFuture.completeExceptionally(e); } finally { runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool", () -> closeAndRelease(channelContext)); } } @Override public void onNext(HttpContent httpContent) { // isDone may be true if the subscriber cancelled if (isDone.get()) { ReferenceCountUtil.release(httpContent); return; } // Needed to prevent use-after-free bug if the subscriber's onNext is asynchronous ByteBuffer byteBuffer = tryCatchFinally(() -> copyToByteBuffer(httpContent.content()), this::onError, httpContent::release); //As per reactive-streams rule 2.13, we should not call subscriber#onError when //exception is thrown from subscriber#onNext if (byteBuffer != null) { tryCatch(() -> subscriber.onNext(byteBuffer), this::notifyError); } } @Override public void onError(Throwable t) { if (!isDone.compareAndSet(false, true)) { return; } try { runAndLogError(channelContext.channel(), () -> String.format("Subscriber %s threw an exception in onError.", subscriber), () -> subscriber.onError(t)); notifyError(t); } finally { runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool", () -> closeAndRelease(channelContext)); } } @Override public void onComplete() { // For HTTP/2 it's possible to get an onComplete after we cancel due to the channel becoming // inactive. We guard against that here and just ignore the signal (see HandlerPublisher) if (!isDone.compareAndSet(false, true)) { return; } try { validateResponseContentLength(channelContext); try { runAndLogError(channelContext.channel(), () -> String.format("Subscriber %s threw an exception in onComplete.", subscriber), subscriber::onComplete); } finally { finalizeResponse(requestContext, channelContext); } } catch (IOException e) { notifyError(e); runAndLogError(channelContext.channel(), () -> "Could not release channel back to the pool", () -> closeAndRelease(channelContext)); } } private void notifyError(Throwable throwable) { SdkAsyncHttpResponseHandler handler = requestContext.handler(); runAndLogError(channelContext.channel(), () -> String.format("SdkAsyncHttpResponseHandler %s threw an exception in onError.", handler), () -> handler.onError(throwable)); executeFuture.completeExceptionally(throwable); } }); } } /** * Decorator around a {@link Subscription} to notify if a cancellation occurs. */ private static class OnCancelSubscription extends DelegatingSubscription { private final Runnable onCancel; private OnCancelSubscription(Subscription subscription, Runnable onCancel) { super(subscription); this.onCancel = onCancel; } @Override public void cancel() { onCancel.run(); super.cancel(); } } static class FullResponseContentPublisher implements Publisher<ByteBuffer> { private final ChannelHandlerContext channelContext; private final ByteBuffer fullContent; private final CompletableFuture<Void> executeFuture; private boolean running = true; private Subscriber<? super ByteBuffer> subscriber; FullResponseContentPublisher(ChannelHandlerContext channelContext, ByteBuffer fullContent, CompletableFuture<Void> executeFuture) { this.channelContext = channelContext; this.fullContent = fullContent; this.executeFuture = executeFuture; } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { if (this.subscriber != null) { subscriber.onComplete(); return; } this.subscriber = subscriber; channelContext.channel().attr(ChannelAttributeKey.SUBSCRIBER_KEY) .set(subscriber); subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { if (running) { running = false; if (l <= 0) { subscriber.onError(new IllegalArgumentException("Demand must be positive!")); } else { if (fullContent.hasRemaining()) { subscriber.onNext(fullContent); } subscriber.onComplete(); executeFuture.complete(null); } } } @Override public void cancel() { running = false; } }); } } private void notifyIfResponseNotCompleted(ChannelHandlerContext handlerCtx) { RequestContext requestCtx = handlerCtx.channel().attr(REQUEST_CONTEXT_KEY).get(); Boolean responseCompleted = handlerCtx.channel().attr(RESPONSE_COMPLETE_KEY).get(); Boolean isStreamingComplete = handlerCtx.channel().attr(STREAMING_COMPLETE_KEY).get(); handlerCtx.channel().attr(KEEP_ALIVE).set(false); if (!Boolean.TRUE.equals(responseCompleted) && !Boolean.TRUE.equals(isStreamingComplete)) { IOException err = new IOException(NettyUtils.closedChannelMessage(handlerCtx.channel())); runAndLogError(handlerCtx.channel(), () -> "Fail to execute SdkAsyncHttpResponseHandler#onError", () -> requestCtx.handler().onError(err)); executeFuture(handlerCtx).completeExceptionally(err); runAndLogError(handlerCtx.channel(), () -> "Could not release channel", () -> closeAndRelease(handlerCtx)); } } private static final class DataCountingPublisher implements Publisher<ByteBuffer> { private final ChannelHandlerContext ctx; private final Publisher<ByteBuffer> delegate; private DataCountingPublisher(ChannelHandlerContext ctx, Publisher<ByteBuffer> delegate) { this.ctx = ctx; this.delegate = delegate; } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { delegate.subscribe(new Subscriber<ByteBuffer>() { @Override public void onSubscribe(Subscription subscription) { subscriber.onSubscribe(subscription); } @Override public void onNext(ByteBuffer byteBuffer) { Long responseDataSoFar = ctx.channel().attr(RESPONSE_DATA_READ).get(); if (responseDataSoFar == null) { responseDataSoFar = 0L; } ctx.channel().attr(RESPONSE_DATA_READ).set(responseDataSoFar + byteBuffer.remaining()); subscriber.onNext(byteBuffer); } @Override public void onError(Throwable throwable) { subscriber.onError(throwable); } @Override public void onComplete() { subscriber.onComplete(); } }); } } }
1,404
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelPoolMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.utils.Validate.paramNotNull; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.ChannelPoolMap; import java.io.Closeable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Replacement for {@link io.netty.channel.pool.AbstractChannelPoolMap}. This implementation guarantees * only one instance of a {@link ChannelPool} is created for each key. */ // TODO do we need to use this for H2? @SdkInternalApi public abstract class SdkChannelPoolMap<K, P extends ChannelPool> implements ChannelPoolMap<K, P>, Iterable<Map.Entry<K, P>>, Closeable { private final ConcurrentMap<K, P> map = new ConcurrentHashMap<>(); @Override public final P get(K key) { return map.computeIfAbsent(key, this::newPool); } /** * Remove the {@link ChannelPool} from this {@link io.netty.channel.pool.AbstractChannelPoolMap}. Returns {@code true} if * removed, {@code false} otherwise. * * Please note that {@code null} keys are not allowed. */ public final boolean remove(K key) { P pool = map.remove(paramNotNull(key, "key")); if (pool != null) { pool.close(); return true; } return false; } @Override public final Iterator<Map.Entry<K, P>> iterator() { return new ReadOnlyIterator<>(map.entrySet().iterator()); } /** * Returns the number of {@link ChannelPool}s currently in this {@link io.netty.channel.pool.AbstractChannelPoolMap}. */ public final int size() { return map.size(); } /** * Returns {@code true} if the {@link io.netty.channel.pool.AbstractChannelPoolMap} is empty, otherwise {@code false}. */ public final boolean isEmpty() { return map.isEmpty(); } @Override public final boolean contains(K key) { return map.containsKey(paramNotNull(key, "key")); } /** * Called once a new {@link ChannelPool} needs to be created as non exists yet for the {@code key}. */ protected abstract P newPool(K key); @Override public void close() { map.keySet().forEach(this::remove); } public final Map<K, P> pools() { return Collections.unmodifiableMap(new HashMap<>(map)); } /** * {@link Iterator} that prevents removal. * * @param <T> Type of object being iterated. */ private final class ReadOnlyIterator<T> implements Iterator<T> { private final Iterator<? extends T> iterator; private ReadOnlyIterator(Iterator<? extends T> iterator) { this.iterator = paramNotNull(iterator, "iterator"); } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public T next() { return this.iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException("Read-only iterator doesn't support removal."); } } }
1,405
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/FutureCancelHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.EXECUTION_ID_KEY; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.REQUEST_CONTEXT_KEY; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.Attribute; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Closes the channel if the execution future has been cancelled. */ @SdkInternalApi @ChannelHandler.Sharable public final class FutureCancelHandler extends ChannelInboundHandlerAdapter { private static final NettyClientLogger LOG = NettyClientLogger.getLogger(FutureCancelHandler.class); private static final FutureCancelHandler INSTANCE = new FutureCancelHandler(); private FutureCancelHandler() { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { if (!(e instanceof FutureCancelledException)) { ctx.fireExceptionCaught(e); return; } FutureCancelledException cancelledException = (FutureCancelledException) e; Long channelExecutionId = executionId(ctx); if (channelExecutionId == null) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); LOG.warn(ctx.channel(), () -> String.format("Received a cancellation exception on a channel that doesn't have an " + "execution Id attached. Exception's execution ID is %d. " + "Exception is being ignored. Closing the channel", executionId(ctx))); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else if (currentRequestCancelled(channelExecutionId, cancelledException)) { RequestContext requestContext = ctx.channel().attr(REQUEST_CONTEXT_KEY).get(); requestContext.handler().onError(e); ctx.fireExceptionCaught(new IOException("Request cancelled")); ctx.close(); requestContext.channelPool().release(ctx.channel()); } else { LOG.debug(ctx.channel(), () -> String.format("Received a cancellation exception but it did not match the current " + "execution ID. Exception's execution ID is %d, but the current ID on " + "the channel is %d. Exception is being ignored.", cancelledException.getExecutionId(), executionId(ctx))); } } public static FutureCancelHandler getInstance() { return INSTANCE; } private static boolean currentRequestCancelled(long executionId, FutureCancelledException e) { return e.getExecutionId() == executionId; } private static Long executionId(ChannelHandlerContext ctx) { Attribute<Long> attr = ctx.channel().attr(EXECUTION_ID_KEY); if (attr == null) { return null; } return attr.get(); } }
1,406
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ProxyTunnelInitHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.net.URI; import java.util.Base64; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.utils.StringUtils; /** * Handler that initializes the HTTP tunnel. */ @SdkInternalApi public final class ProxyTunnelInitHandler extends ChannelDuplexHandler { public static final NettyClientLogger log = NettyClientLogger.getLogger(ProxyTunnelInitHandler.class); private final ChannelPool sourcePool; private final String username; private final String password; private final URI remoteHost; private final Promise<Channel> initPromise; private final Supplier<HttpClientCodec> httpCodecSupplier; public ProxyTunnelInitHandler(ChannelPool sourcePool, String proxyUsername, String proxyPassword, URI remoteHost, Promise<Channel> initPromise) { this(sourcePool, proxyUsername, proxyPassword, remoteHost, initPromise, HttpClientCodec::new); } public ProxyTunnelInitHandler(ChannelPool sourcePool, URI remoteHost, Promise<Channel> initPromise) { this(sourcePool, null, null, remoteHost, initPromise, HttpClientCodec::new); } @SdkTestInternalApi public ProxyTunnelInitHandler(ChannelPool sourcePool, String prosyUsername, String proxyPassword, URI remoteHost, Promise<Channel> initPromise, Supplier<HttpClientCodec> httpCodecSupplier) { this.sourcePool = sourcePool; this.remoteHost = remoteHost; this.initPromise = initPromise; this.username = prosyUsername; this.password = proxyPassword; this.httpCodecSupplier = httpCodecSupplier; } @Override public void handlerAdded(ChannelHandlerContext ctx) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get()); HttpRequest connectRequest = connectRequest(); ctx.channel().writeAndFlush(connectRequest).addListener(f -> { if (!f.isSuccess()) { handleConnectRequestFailure(ctx, f.cause()); } }); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { if (ctx.pipeline().get(HttpClientCodec.class) != null) { ctx.pipeline().remove(HttpClientCodec.class); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status().code() == 200) { ctx.pipeline().remove(this); // Note: we leave the SslHandler here (if we added it) initPromise.setSuccess(ctx.channel()); return; } } // Fail if we received any other type of message or we didn't get a 200 from the proxy ctx.pipeline().remove(this); ctx.close(); sourcePool.release(ctx.channel()); initPromise.setFailure(new IOException("Could not connect to proxy")); } @Override public void channelInactive(ChannelHandlerContext ctx) { if (!initPromise.isDone()) { handleConnectRequestFailure(ctx, null); } else { log.debug(ctx.channel(), () -> "The proxy channel (" + ctx.channel().id() + ") is inactive"); closeAndRelease(ctx); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (!initPromise.isDone()) { handleConnectRequestFailure(ctx, cause); } else { log.debug(ctx.channel(), () -> "An exception occurred on the proxy tunnel channel (" + ctx.channel().id() + "). " + "The channel has been closed to prevent any ongoing issues.", cause); closeAndRelease(ctx); } } private void handleConnectRequestFailure(ChannelHandlerContext ctx, Throwable cause) { closeAndRelease(ctx); String errorMsg = "Unable to send CONNECT request to proxy"; IOException ioException = cause == null ? new IOException(errorMsg) : new IOException(errorMsg, cause); initPromise.setFailure(ioException); } private void closeAndRelease(ChannelHandlerContext ctx) { ctx.close(); sourcePool.release(ctx.channel()); } private HttpRequest connectRequest() { String uri = getUri(); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri, Unpooled.EMPTY_BUFFER, false); request.headers().add(HttpHeaderNames.HOST, uri); if (!StringUtils.isEmpty(this.username) && !StringUtils.isEmpty(this.password)) { String authToken = String.format("%s:%s", this.username, this.password); String authB64 = Base64.getEncoder().encodeToString(authToken.getBytes(CharsetUtil.UTF_8)); request.headers().add(HttpHeaderNames.PROXY_AUTHORIZATION, String.format("Basic %s", authB64)); } return request; } private String getUri() { return remoteHost.getHost() + ":" + remoteHost.getPort(); } }
1,407
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/RequestContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.EventLoopGroup; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.NoOpMetricCollector; @SdkInternalApi public final class RequestContext { private final SdkChannelPool channelPool; private final EventLoopGroup eventLoopGroup; private final AsyncExecuteRequest executeRequest; private final NettyConfiguration configuration; private final MetricCollector metricCollector; public RequestContext(SdkChannelPool channelPool, EventLoopGroup eventLoopGroup, AsyncExecuteRequest executeRequest, NettyConfiguration configuration) { this.channelPool = channelPool; this.eventLoopGroup = eventLoopGroup; this.executeRequest = executeRequest; this.configuration = configuration; this.metricCollector = executeRequest.metricCollector().orElseGet(NoOpMetricCollector::create); } public SdkChannelPool channelPool() { return channelPool; } public EventLoopGroup eventLoopGroup() { return eventLoopGroup; } public AsyncExecuteRequest executeRequest() { return executeRequest; } /** * Convenience method to retrieve the {@link SdkAsyncHttpResponseHandler} contained in the {@link AsyncExecuteRequest} * returned by {@link #executeRequest}. * * @return The response handler for this request. */ public SdkAsyncHttpResponseHandler handler() { return executeRequest().responseHandler(); } public NettyConfiguration configuration() { return configuration; } public MetricCollector metricCollector() { return metricCollector; } }
1,408
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/LastHttpContentSwallower.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.LastHttpContent; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Simple handler that swallows the next read object if it is an instance of * {@code LastHttpContent}, then removes itself from the pipeline. * <p> * This handler is sharable. */ @SdkInternalApi @ChannelHandler.Sharable final class LastHttpContentSwallower extends SimpleChannelInboundHandler<HttpObject> { private static final LastHttpContentSwallower INSTANCE = new LastHttpContentSwallower(); private LastHttpContentSwallower() { } @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject obj) { if (obj instanceof LastHttpContent) { // Queue another read to make up for the one we just ignored ctx.read(); } else { ctx.fireChannelRead(obj); } // Remove self from pipeline since we only care about potentially // ignoring the very first message ctx.pipeline().remove(this); } public static LastHttpContentSwallower getInstance() { return INSTANCE; } }
1,409
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SharedSdkEventLoopGroup.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.SUCCEEDED_FUTURE; import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; /** * Provides access and manages a shared {@link SdkEventLoopGroup}. Uses reference counting to keep track of how many HTTP * clients are using the shared event loop group and will automatically close it when that count reaches zero. Event loop * group is lazily initialized for the first time and and subsequent requests after the count reaches zero. */ @SdkInternalApi public final class SharedSdkEventLoopGroup { /** * Lazily initialized shared default event loop group. */ private static SdkEventLoopGroup sharedSdkEventLoopGroup; /** * Reference count of clients using the shared event loop group. */ private static int referenceCount = 0; private SharedSdkEventLoopGroup() { } /** * @return The default {@link SdkEventLoopGroup} that will be shared across all service clients. * This is used when the customer does not specify a custom {@link SdkEventLoopGroup} or {@link SdkEventLoopGroup.Builder}. * Each SdkEventLoopGroup returned is wrapped with a new {@link ReferenceCountingEventLoopGroup}. */ @SdkInternalApi public static synchronized SdkEventLoopGroup get() { if (sharedSdkEventLoopGroup == null) { sharedSdkEventLoopGroup = SdkEventLoopGroup.builder().build(); } referenceCount++; return SdkEventLoopGroup.create(new ReferenceCountingEventLoopGroup(sharedSdkEventLoopGroup.eventLoopGroup()), sharedSdkEventLoopGroup.channelFactory()); } /** * Decrement the reference count and close if necessary. * * @param quietPeriod the quite period to use * @param timeout the timeout to use * @param unit the time unit * * @return the close future. If the shared event loop group is still being used, return a completed close future, * otherwise return the future from {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit)}; */ private static synchronized Future<?> decrementReference(long quietPeriod, long timeout, TimeUnit unit) { referenceCount--; if (referenceCount == 0) { Future<?> shutdownGracefully = sharedSdkEventLoopGroup.eventLoopGroup().shutdownGracefully(quietPeriod, timeout, unit); sharedSdkEventLoopGroup = null; return shutdownGracefully; } return SUCCEEDED_FUTURE; } @SdkTestInternalApi static synchronized int referenceCount() { return referenceCount; } /** * Special event loop group that prevents shutdown and decrements the reference count when the event loop group * is closed. */ private static class ReferenceCountingEventLoopGroup extends DelegatingEventLoopGroup { private final AtomicBoolean hasBeenClosed = new AtomicBoolean(false); private ReferenceCountingEventLoopGroup(EventLoopGroup delegate) { super(delegate); } @Override public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { // Only want to decrement the reference the first time it's closed. Shutdown is idempotent and may be // called multiple times. if (hasBeenClosed.compareAndSet(false, true)) { return decrementReference(quietPeriod, timeout, unit); } return SUCCEEDED_FUTURE; } } }
1,410
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/AwaitCloseChannelPoolMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslProvider; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.ProxyConfiguration; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; import software.amazon.awssdk.http.nio.netty.internal.http2.HttpOrHttp2ChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Implementation of {@link SdkChannelPoolMap} that awaits channel pools to be closed upon closing. */ @SdkInternalApi public final class AwaitCloseChannelPoolMap extends SdkChannelPoolMap<URI, SimpleChannelPoolAwareChannelPool> { private static final NettyClientLogger log = NettyClientLogger.getLogger(AwaitCloseChannelPoolMap.class); private static final ChannelPoolHandler NOOP_HANDLER = new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) throws Exception { } @Override public void channelAcquired(Channel ch) throws Exception { } @Override public void channelCreated(Channel ch) throws Exception { } }; // IMPORTANT: If the default bootstrap provider is changed, ensure that the new implementation is compliant with // DNS resolver testing in BootstrapProviderTest, specifically that no caching of hostname lookups is taking place. private static final Function<Builder, BootstrapProvider> DEFAULT_BOOTSTRAP_PROVIDER = b -> new BootstrapProvider(b.sdkEventLoopGroup, b.configuration, b.sdkChannelOptions); private final Map<URI, Boolean> shouldProxyForHostCache = new ConcurrentHashMap<>(); private final NettyConfiguration configuration; private final Protocol protocol; private final long maxStreams; private final Duration healthCheckPingPeriod; private final int initialWindowSize; private final SslProvider sslProvider; private final ProxyConfiguration proxyConfiguration; private final BootstrapProvider bootstrapProvider; private final SslContextProvider sslContextProvider; private final Boolean useNonBlockingDnsResolver; private AwaitCloseChannelPoolMap(Builder builder, Function<Builder, BootstrapProvider> createBootStrapProvider) { this.configuration = builder.configuration; this.protocol = builder.protocol; this.maxStreams = builder.maxStreams; this.healthCheckPingPeriod = builder.healthCheckPingPeriod; this.initialWindowSize = builder.initialWindowSize; this.sslProvider = builder.sslProvider; this.proxyConfiguration = builder.proxyConfiguration; this.bootstrapProvider = createBootStrapProvider.apply(builder); this.sslContextProvider = new SslContextProvider(configuration, protocol, sslProvider); this.useNonBlockingDnsResolver = builder.useNonBlockingDnsResolver; } private AwaitCloseChannelPoolMap(Builder builder) { this(builder, DEFAULT_BOOTSTRAP_PROVIDER); } @SdkTestInternalApi AwaitCloseChannelPoolMap(Builder builder, Map<URI, Boolean> shouldProxyForHostCache, BootstrapProvider bootstrapProvider) { this(builder, bootstrapProvider == null ? DEFAULT_BOOTSTRAP_PROVIDER : b -> bootstrapProvider); if (shouldProxyForHostCache != null) { this.shouldProxyForHostCache.putAll(shouldProxyForHostCache); } } public static Builder builder() { return new Builder(); } @Override protected SimpleChannelPoolAwareChannelPool newPool(URI key) { SslContext sslContext = needSslContext(key) ? sslContextProvider.sslContext() : null; Bootstrap bootstrap = createBootstrap(key); AtomicReference<ChannelPool> channelPoolRef = new AtomicReference<>(); ChannelPipelineInitializer pipelineInitializer = new ChannelPipelineInitializer(protocol, sslContext, sslProvider, maxStreams, initialWindowSize, healthCheckPingPeriod, channelPoolRef, configuration, key); BetterSimpleChannelPool tcpChannelPool; ChannelPool baseChannelPool; if (shouldUseProxyForHost(key)) { tcpChannelPool = new BetterSimpleChannelPool(bootstrap, NOOP_HANDLER); baseChannelPool = new Http1TunnelConnectionPool(bootstrap.config().group().next(), tcpChannelPool, sslContext, proxyAddress(key), proxyConfiguration.username(), proxyConfiguration.password(), key, pipelineInitializer, configuration); } else { tcpChannelPool = new BetterSimpleChannelPool(bootstrap, pipelineInitializer); baseChannelPool = tcpChannelPool; } SdkChannelPool wrappedPool = wrapBaseChannelPool(bootstrap, baseChannelPool); channelPoolRef.set(wrappedPool); return new SimpleChannelPoolAwareChannelPool(wrappedPool, tcpChannelPool); } @Override public void close() { log.trace(null, () -> "Closing channel pools"); // If there is a new pool being added while we are iterating the pools, there might be a // race condition between the close call of the newly acquired pool and eventLoopGroup.shutdown and it // could cause the eventLoopGroup#shutdownGracefully to hang before it times out. // If a new pool is being added while super.close() is running, it might be left open because // the underlying pool map is a ConcurrentHashMap and it doesn't guarantee strong consistency for retrieval // operations. See https://github.com/aws/aws-sdk-java-v2/pull/1200#discussion_r277906715 Collection<SimpleChannelPoolAwareChannelPool> channelPools = pools().values(); super.close(); try { CompletableFuture.allOf(channelPools.stream() .map(pool -> pool.underlyingSimpleChannelPool().closeFuture()) .toArray(CompletableFuture[]::new)) .get(CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException | TimeoutException e) { throw new RuntimeException(e); } } private Bootstrap createBootstrap(URI poolKey) { String host = bootstrapHost(poolKey); int port = bootstrapPort(poolKey); return bootstrapProvider.createBootstrap(host, port, useNonBlockingDnsResolver); } private boolean shouldUseProxyForHost(URI remoteAddr) { if (proxyConfiguration == null) { return false; } return shouldProxyForHostCache.computeIfAbsent(remoteAddr, (uri) -> proxyConfiguration.nonProxyHosts().stream().noneMatch(h -> uri.getHost().matches(h)) ); } private String bootstrapHost(URI remoteHost) { if (shouldUseProxyForHost(remoteHost)) { return proxyConfiguration.host(); } return remoteHost.getHost(); } private int bootstrapPort(URI remoteHost) { if (shouldUseProxyForHost(remoteHost)) { return proxyConfiguration.port(); } return remoteHost.getPort(); } private URI proxyAddress(URI remoteHost) { if (!shouldUseProxyForHost(remoteHost)) { return null; } String scheme = proxyConfiguration.scheme(); if (scheme == null) { scheme = "http"; } try { return new URI(scheme, null, proxyConfiguration.host(), proxyConfiguration.port(), null, null, null); } catch (URISyntaxException e) { throw new RuntimeException("Unable to construct proxy URI", e); } } private SdkChannelPool wrapBaseChannelPool(Bootstrap bootstrap, ChannelPool channelPool) { // Wrap the channel pool such that the ChannelAttributeKey.CLOSE_ON_RELEASE flag is honored. channelPool = new HonorCloseOnReleaseChannelPool(channelPool); // Wrap the channel pool such that HTTP 2 channels won't be released to the underlying pool while they're still in use. SdkChannelPool sdkChannelPool = new HttpOrHttp2ChannelPool(channelPool, bootstrap.config().group(), configuration.maxConnections(), configuration); sdkChannelPool = new ListenerInvokingChannelPool(bootstrap.config().group(), sdkChannelPool, Arrays.asList( // Add a listener that disables auto reads on acquired connections. AutoReadDisableChannelPoolListener.create(), // Add a listener that ensures acquired channels are marked IN_USE and thus not eligible for certain idle timeouts. InUseTrackingChannelPoolListener.create(), // Add a listener that removes request-specific handlers with each request. HandlerRemovingChannelPoolListener.create(), // Add a listener that enables auto reads on released connections. AutoReadEnableChannelPoolListener.create() )); // Wrap the channel pool such that an individual channel can only be released to the underlying pool once. sdkChannelPool = new ReleaseOnceChannelPool(sdkChannelPool); // Wrap the channel pool to guarantee all channels checked out are healthy, and all unhealthy channels checked in are // closed. sdkChannelPool = new HealthCheckedChannelPool(bootstrap.config().group(), configuration, sdkChannelPool); // Wrap the channel pool such that if the Promise given to acquire(Promise) is done when the channel is acquired // from the underlying pool, the channel is closed and released. sdkChannelPool = new CancellableAcquireChannelPool(bootstrap.config().group().next(), sdkChannelPool); return sdkChannelPool; } private boolean needSslContext(URI targetAddress) { URI proxyAddress = proxyAddress(targetAddress); boolean needContext = targetAddress.getScheme().equalsIgnoreCase("https") || proxyAddress != null && proxyAddress.getScheme().equalsIgnoreCase("https"); return needContext; } public static class Builder { private SdkChannelOptions sdkChannelOptions; private SdkEventLoopGroup sdkEventLoopGroup; private NettyConfiguration configuration; private Protocol protocol; private long maxStreams; private int initialWindowSize; private Duration healthCheckPingPeriod; private SslProvider sslProvider; private ProxyConfiguration proxyConfiguration; private Boolean useNonBlockingDnsResolver; private Builder() { } public Builder sdkChannelOptions(SdkChannelOptions sdkChannelOptions) { this.sdkChannelOptions = sdkChannelOptions; return this; } public Builder sdkEventLoopGroup(SdkEventLoopGroup sdkEventLoopGroup) { this.sdkEventLoopGroup = sdkEventLoopGroup; return this; } public Builder configuration(NettyConfiguration configuration) { this.configuration = configuration; return this; } public Builder protocol(Protocol protocol) { this.protocol = protocol; return this; } public Builder maxStreams(long maxStreams) { this.maxStreams = maxStreams; return this; } public Builder initialWindowSize(int initialWindowSize) { this.initialWindowSize = initialWindowSize; return this; } public Builder healthCheckPingPeriod(Duration healthCheckPingPeriod) { this.healthCheckPingPeriod = healthCheckPingPeriod; return this; } public Builder sslProvider(SslProvider sslProvider) { this.sslProvider = sslProvider; return this; } public Builder proxyConfiguration(ProxyConfiguration proxyConfiguration) { this.proxyConfiguration = proxyConfiguration; return this; } public Builder useNonBlockingDnsResolver(Boolean useNonBlockingDnsResolver) { this.useNonBlockingDnsResolver = useNonBlockingDnsResolver; return this; } public AwaitCloseChannelPoolMap build() { return new AwaitCloseChannelPoolMap(this); } } }
1,411
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelPipelineInitializer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import static software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration.HTTP2_CONNECTION_PING_TIMEOUT_SECONDS; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.newSslHandler; import static software.amazon.awssdk.utils.NumericUtils.saturatedCast; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.pool.AbstractChannelPoolHandler; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http2.Http2FrameCodec; import io.netty.handler.codec.http2.Http2FrameCodecBuilder; import io.netty.handler.codec.http2.Http2FrameLogger; import io.netty.handler.codec.http2.Http2MultiplexHandler; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslProvider; import java.net.URI; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2GoAwayEventListener; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2PingHandler; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2SettingsFrameHandler; /** * ChannelPoolHandler to configure the client pipeline. */ @SdkInternalApi public final class ChannelPipelineInitializer extends AbstractChannelPoolHandler { private final Protocol protocol; private final SslContext sslCtx; private final SslProvider sslProvider; private final long clientMaxStreams; private final int clientInitialWindowSize; private final Duration healthCheckPingPeriod; private final AtomicReference<ChannelPool> channelPoolRef; private final NettyConfiguration configuration; private final URI poolKey; public ChannelPipelineInitializer(Protocol protocol, SslContext sslCtx, SslProvider sslProvider, long clientMaxStreams, int clientInitialWindowSize, Duration healthCheckPingPeriod, AtomicReference<ChannelPool> channelPoolRef, NettyConfiguration configuration, URI poolKey) { this.protocol = protocol; this.sslCtx = sslCtx; this.sslProvider = sslProvider; this.clientMaxStreams = clientMaxStreams; this.clientInitialWindowSize = clientInitialWindowSize; this.healthCheckPingPeriod = healthCheckPingPeriod; this.channelPoolRef = channelPoolRef; this.configuration = configuration; this.poolKey = poolKey; } @Override public void channelCreated(Channel ch) { ch.attr(CHANNEL_DIAGNOSTICS).set(new ChannelDiagnostics(ch)); ch.attr(PROTOCOL_FUTURE).set(new CompletableFuture<>()); ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { SslHandler sslHandler = newSslHandler(sslCtx, ch.alloc(), poolKey.getHost(), poolKey.getPort(), configuration.tlsHandshakeTimeout()); pipeline.addLast(sslHandler); pipeline.addLast(SslCloseCompletionEventHandler.getInstance()); // Use unpooled allocator to avoid increased heap memory usage from Netty 4.1.43. // See https://github.com/netty/netty/issues/9768 if (sslProvider == SslProvider.JDK) { ch.config().setOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT); } } if (protocol == Protocol.HTTP2) { configureHttp2(ch, pipeline); } else { configureHttp11(ch, pipeline); } if (configuration.reapIdleConnections()) { pipeline.addLast(new IdleConnectionReaperHandler(configuration.idleTimeoutMillis())); } if (configuration.connectionTtlMillis() > 0) { pipeline.addLast(new OldConnectionReaperHandler(configuration.connectionTtlMillis())); } pipeline.addLast(FutureCancelHandler.getInstance()); // Only add it for h1 channel because it does not apply to // h2 connection channel. It will be attached // to stream channels when they are created. if (protocol == Protocol.HTTP1_1) { pipeline.addLast(UnusedChannelExceptionHandler.getInstance()); } pipeline.addLast(new LoggingHandler(LogLevel.DEBUG)); } private void configureHttp2(Channel ch, ChannelPipeline pipeline) { // Using Http2FrameCodecBuilder and Http2MultiplexHandler based on 4.1.37 release notes // https://netty.io/news/2019/06/28/4-1-37-Final.html Http2FrameCodec codec = Http2FrameCodecBuilder.forClient() .headerSensitivityDetector((name, value) -> lowerCase(name.toString()).equals("authorization")) .initialSettings(Http2Settings.defaultSettings().initialWindowSize(clientInitialWindowSize)) .frameLogger(new Http2FrameLogger(LogLevel.DEBUG)) .build(); // Connection listeners have higher priority than handlers, in the eyes of the Http2FrameCodec. The Http2FrameCodec will // close any connections when a GOAWAY is received, but we'd like to send a "GOAWAY happened" exception instead of just // closing the connection. Because of this, we use a go-away listener instead of a handler, so that we can send the // exception before the Http2FrameCodec closes the connection itself. codec.connection().addListener(new Http2GoAwayEventListener(ch)); pipeline.addLast(codec); ch.attr(HTTP2_CONNECTION).set(codec.connection()); ch.attr(HTTP2_INITIAL_WINDOW_SIZE).set(clientInitialWindowSize); pipeline.addLast(new Http2MultiplexHandler(new NoOpChannelInitializer())); pipeline.addLast(new Http2SettingsFrameHandler(ch, clientMaxStreams, channelPoolRef)); if (healthCheckPingPeriod == null) { pipeline.addLast(new Http2PingHandler(HTTP2_CONNECTION_PING_TIMEOUT_SECONDS * 1_000)); } else if (healthCheckPingPeriod.toMillis() > 0) { pipeline.addLast(new Http2PingHandler(saturatedCast(healthCheckPingPeriod.toMillis()))); } } private void configureHttp11(Channel ch, ChannelPipeline pipeline) { pipeline.addLast(new HttpClientCodec()); ch.attr(PROTOCOL_FUTURE).get().complete(Protocol.HTTP1_1); } private static class NoOpChannelInitializer extends ChannelInitializer<Channel> { @Override protected void initChannel(Channel ch) { } } }
1,412
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/HonorCloseOnReleaseChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Wrap a channel pool so that {@link ChannelAttributeKey#CLOSE_ON_RELEASE} is honored when a channel is released to the * underlying pool. * * When a channel is released and {@link ChannelAttributeKey#CLOSE_ON_RELEASE} is true on the channel, the channel will be closed * before it is released to the underlying pool. */ @SdkInternalApi public class HonorCloseOnReleaseChannelPool implements ChannelPool { private static final NettyClientLogger log = NettyClientLogger.getLogger(HonorCloseOnReleaseChannelPool.class); private final ChannelPool delegatePool; public HonorCloseOnReleaseChannelPool(ChannelPool delegatePool) { this.delegatePool = delegatePool; } @Override public Future<Channel> acquire() { return delegatePool.acquire(); } @Override public Future<Channel> acquire(Promise<Channel> promise) { return delegatePool.acquire(promise); } @Override public Future<Void> release(Channel channel) { return release(channel, channel.eventLoop().newPromise()); } @Override public Future<Void> release(Channel channel, Promise<Void> promise) { doInEventLoop(channel.eventLoop(), () -> { boolean shouldCloseOnRelease = Boolean.TRUE.equals(channel.attr(ChannelAttributeKey.CLOSE_ON_RELEASE).get()); if (shouldCloseOnRelease && channel.isOpen() && !channel.eventLoop().isShuttingDown()) { log.debug(channel, () -> "Closing connection (" + channel.id() + "), instead of releasing it."); channel.close(); } delegatePool.release(channel, promise); }).addListener(f -> { if (!f.isSuccess()) { promise.tryFailure(f.cause()); } }); return promise; } @Override public void close() { delegatePool.close(); } }
1,413
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/RequestAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; @SdkInternalApi public final class RequestAdapter { private static final String HOST = "Host"; private static final List<String> IGNORE_HEADERS = Collections.singletonList(HOST); private final Protocol protocol; public RequestAdapter(Protocol protocol) { this.protocol = Validate.paramNotNull(protocol, "protocol"); } public HttpRequest adapt(SdkHttpRequest sdkRequest) { HttpMethod method = toNettyHttpMethod(sdkRequest.method()); HttpHeaders headers = new DefaultHttpHeaders(); String uri = encodedPathAndQueryParams(sdkRequest); // All requests start out as HTTP/1.1 objects, even if they will // ultimately be sent over HTTP2. Conversion to H2 is handled at a // later stage if necessary; see HttpToHttp2OutboundAdapter. DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers); addHeadersToRequest(request, sdkRequest); return request; } private static HttpMethod toNettyHttpMethod(SdkHttpMethod method) { return HttpMethod.valueOf(method.name()); } private static String encodedPathAndQueryParams(SdkHttpRequest sdkRequest) { String encodedPath = sdkRequest.encodedPath(); if (StringUtils.isBlank(encodedPath)) { encodedPath = "/"; } String encodedQueryParams = sdkRequest.encodedQueryParameters() .map(queryParams -> "?" + queryParams) .orElse(""); return encodedPath + encodedQueryParams; } /** * Configures the headers in the specified Netty HTTP request. */ private void addHeadersToRequest(DefaultHttpRequest httpRequest, SdkHttpRequest request) { httpRequest.headers().add(HOST, getHostHeaderValue(request)); String scheme = request.getUri().getScheme(); if (Protocol.HTTP2 == protocol && !StringUtils.isBlank(scheme)) { httpRequest.headers().add(ExtensionHeaderNames.SCHEME.text(), scheme); } // Copy over any other headers already in our request request.forEachHeader((name, value) -> { // Skip the Host header to avoid sending it twice, which will interfere with some signing schemes. if (!IGNORE_HEADERS.contains(name)) { value.forEach(h -> httpRequest.headers().add(name, h)); } }); } private String getHostHeaderValue(SdkHttpRequest request) { return SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port()) ? request.host() : request.host() + ":" + request.port(); } }
1,414
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/AutoReadDisableChannelPoolListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Disables auto read on in-use channels to allow upper layers to take care of flow control. */ @SdkInternalApi @ChannelHandler.Sharable public final class AutoReadDisableChannelPoolListener implements ListenerInvokingChannelPool.ChannelPoolListener { private static final AutoReadDisableChannelPoolListener INSTANCE = new AutoReadDisableChannelPoolListener(); private AutoReadDisableChannelPoolListener() { } @Override public void channelAcquired(Channel channel) { channel.config().setAutoRead(false); } public static AutoReadDisableChannelPoolListener create() { return INSTANCE; } }
1,415
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ReleaseOnceChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.FixedChannelPool; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.SucceededFuture; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.metrics.MetricCollector; /** * Wrapper around a {@link ChannelPool} to protect it from having the same channel released twice. This can * cause issues in {@link FixedChannelPool} and {@link Http2MultiplexedChannelPool} which has a simple * mechanism to track leased connections. */ @SdkInternalApi public class ReleaseOnceChannelPool implements SdkChannelPool { private static final AttributeKey<AtomicBoolean> IS_RELEASED = NettyUtils.getOrCreateAttributeKey( "software.amazon.awssdk.http.nio.netty.internal.http2.ReleaseOnceChannelPool.isReleased"); private final SdkChannelPool delegate; public ReleaseOnceChannelPool(SdkChannelPool delegate) { this.delegate = delegate; } @Override public Future<Channel> acquire() { return delegate.acquire().addListener(onAcquire()); } @Override public Future<Channel> acquire(Promise<Channel> promise) { return delegate.acquire(promise).addListener(onAcquire()); } private GenericFutureListener<Future<Channel>> onAcquire() { return future -> { if (future.isSuccess()) { future.getNow().attr(IS_RELEASED).set(new AtomicBoolean(false)); } }; } @Override public Future<Void> release(Channel channel) { if (shouldRelease(channel)) { return delegate.release(channel); } else { return new SucceededFuture<>(channel.eventLoop(), null); } } @Override public Future<Void> release(Channel channel, Promise<Void> promise) { if (shouldRelease(channel)) { return delegate.release(channel, promise); } else { return promise.setSuccess(null); } } private boolean shouldRelease(Channel channel) { // IS_RELEASED may be null if this channel was not acquired by this pool. This can happen // for HTTP/2 when we release the parent socket channel return channel.attr(IS_RELEASED).get() == null || channel.attr(IS_RELEASED).get().compareAndSet(false, true); } @Override public void close() { delegate.close(); } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { return delegate.collectChannelPoolMetrics(metrics); } }
1,416
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SslCloseCompletionEventHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.ChannelUtils.getAttribute; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.ssl.SslCloseCompletionEvent; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Handles {@link SslCloseCompletionEvent}s that are sent whenever an SSL channel * goes inactive. This most commonly occurs on a tls_close sent by the server. Channels * in this state can't be reused so they must be closed. */ @SdkInternalApi @ChannelHandler.Sharable public final class SslCloseCompletionEventHandler extends ChannelInboundHandlerAdapter { private static final SslCloseCompletionEventHandler INSTANCE = new SslCloseCompletionEventHandler(); private SslCloseCompletionEventHandler() { } /** * {@inheritDoc} * * Close the channel if the event is {@link SslCloseCompletionEvent} and the channel is unused. * If the channel is being used, it will be closed in {@link ResponseHandler} * */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { boolean channelInUse = getAttribute(ctx.channel(), ChannelAttributeKey.IN_USE).orElse(false); if (!channelInUse && evt instanceof SslCloseCompletionEvent) { ctx.close(); } else { ctx.fireUserEventTriggered(evt); } } public static SslCloseCompletionEventHandler getInstance() { return INSTANCE; } }
1,417
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelAttributeKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.Channel; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2FrameStream; import io.netty.util.AttributeKey; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool; import software.amazon.awssdk.http.nio.netty.internal.http2.PingTracker; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; /** * Keys for attributes attached via {@link io.netty.channel.Channel#attr(AttributeKey)}. */ @SdkInternalApi public final class ChannelAttributeKey { /** * Future that when a protocol (http/1.1 or h2) has been selected. */ public static final AttributeKey<CompletableFuture<Protocol>> PROTOCOL_FUTURE = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.protocolFuture"); /** * Reference to {@link Http2MultiplexedChannelPool} which stores information about leased streams for a multiplexed * connection. */ public static final AttributeKey<Http2MultiplexedChannelPool> HTTP2_MULTIPLEXED_CHANNEL_POOL = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2MultiplexedChannelPool"); public static final AttributeKey<PingTracker> PING_TRACKER = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.h2.pingTracker"); public static final AttributeKey<Http2Connection> HTTP2_CONNECTION = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2Connection"); public static final AttributeKey<Integer> HTTP2_INITIAL_WINDOW_SIZE = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.http2InitialWindowSize"); /** * Value of the MAX_CONCURRENT_STREAMS from the server's SETTING frame. */ public static final AttributeKey<Long> MAX_CONCURRENT_STREAMS = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.maxConcurrentStreams"); /** * The {@link Http2FrameStream} associated with this stream channel. This is added to stream channels when they are created, * before they are fully initialized. */ public static final AttributeKey<Http2FrameStream> HTTP2_FRAME_STREAM = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.http2FrameStream"); public static final AttributeKey<ChannelDiagnostics> CHANNEL_DIAGNOSTICS = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.channelDiagnostics"); /** * {@link AttributeKey} to keep track of whether the streaming is completed and this is set to true when we receive the * * {@link LastHttpContent}. */ public static final AttributeKey<Boolean> STREAMING_COMPLETE_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.streamingComplete"); /** * {@link AttributeKey} to keep track of whether we should close the connection after this request * has completed. */ static final AttributeKey<Boolean> KEEP_ALIVE = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.keepAlive"); /** * Attribute key for {@link RequestContext}. */ static final AttributeKey<RequestContext> REQUEST_CONTEXT_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.requestContext"); static final AttributeKey<Subscriber<? super ByteBuffer>> SUBSCRIBER_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.subscriber"); static final AttributeKey<Boolean> RESPONSE_COMPLETE_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.responseComplete"); static final AttributeKey<Integer> RESPONSE_STATUS_CODE = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.responseStatusCode"); static final AttributeKey<Long> RESPONSE_CONTENT_LENGTH = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.responseContentLength"); static final AttributeKey<Long> RESPONSE_DATA_READ = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.responseDataRead"); static final AttributeKey<CompletableFuture<Void>> EXECUTE_FUTURE_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.executeFuture"); static final AttributeKey<Long> EXECUTION_ID_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.executionId"); /** * Whether the channel is still in use */ static final AttributeKey<Boolean> IN_USE = NettyUtils.getOrCreateAttributeKey("aws.http.nio.netty.async.inUse"); /** * Whether the channel should be closed once it is released. */ static final AttributeKey<Boolean> CLOSE_ON_RELEASE = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.closeOnRelease"); private ChannelAttributeKey() { } /** * Gets the protocol of the channel assuming that it has already been negotiated. * * @param channel Channel to get protocol for. * @return Protocol of channel. */ static Protocol getProtocolNow(Channel channel) { // For HTTP/2 the protocol future will be on the parent socket channel return (channel.parent() == null ? channel : channel.parent()) .attr(ChannelAttributeKey.PROTOCOL_FUTURE).get().join(); } }
1,418
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelDiagnostics.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.Channel; import java.time.Duration; import java.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.ToString; /** * Diagnostic information that may be useful to help with debugging during error scenarios. */ @SdkInternalApi public class ChannelDiagnostics { private final Channel channel; private final Instant channelCreationTime; private int requestCount = 0; private int responseCount = 0; private long idleStart = -1; private long idleStop = -1; public ChannelDiagnostics(Channel channel) { this.channel = channel; this.channelCreationTime = Instant.now(); } public void incrementRequestCount() { ++this.requestCount; } public void incrementResponseCount() { ++responseCount; } public int responseCount() { return responseCount; } public void startIdleTimer() { idleStart = System.nanoTime(); } public void stopIdleTimer() { idleStop = System.nanoTime(); } public Duration lastIdleDuration() { // Channel started, then stopped idling if (idleStart > 0 && idleStop > idleStart) { return Duration.ofNanos(idleStop - idleStart); } // Channel currently idling if (idleStart > 0) { return Duration.ofNanos(System.nanoTime() - idleStart); } return null; } @Override public String toString() { return ToString.builder("ChannelDiagnostics") .add("channel", channel) .add("channelAge", Duration.between(channelCreationTime, Instant.now())) .add("requestCount", requestCount) .add("responseCount", responseCount) .add("lastIdleDuration", lastIdleDuration()) .build(); } }
1,419
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/StaticKeyManagerFactorySpi.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import java.security.KeyStore; import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactorySpi; import javax.net.ssl.ManagerFactoryParameters; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Factory SPI that simply returns a statically provided set of {@link KeyManager}s. */ @SdkInternalApi public final class StaticKeyManagerFactorySpi extends KeyManagerFactorySpi { private final KeyManager[] keyManagers; public StaticKeyManagerFactorySpi(KeyManager[] keyManagers) { Validate.paramNotNull(keyManagers, "keyManagers"); this.keyManagers = Arrays.copyOf(keyManagers, keyManagers.length); } @Override protected void engineInit(KeyStore ks, char[] password) { throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory"); } @Override protected void engineInit(ManagerFactoryParameters spec) { throw new UnsupportedOperationException("engineInit not supported by this KeyManagerFactory"); } @Override protected KeyManager[] engineGetKeyManagers() { return keyManagers; } }
1,420
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/BootstrapProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelOption; import java.net.InetSocketAddress; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.SdkEventLoopGroup; /** * The primary purpose of this Bootstrap provider is to ensure that all Bootstraps created by it are 'unresolved' * InetSocketAddress. This is to prevent Netty from caching the resolved address of a host and then re-using it in * subsequent connection attempts, and instead deferring to the JVM to handle address resolution and caching. */ @SdkInternalApi public class BootstrapProvider { private final SdkEventLoopGroup sdkEventLoopGroup; private final NettyConfiguration nettyConfiguration; private final SdkChannelOptions sdkChannelOptions; BootstrapProvider(SdkEventLoopGroup sdkEventLoopGroup, NettyConfiguration nettyConfiguration, SdkChannelOptions sdkChannelOptions) { this.sdkEventLoopGroup = sdkEventLoopGroup; this.nettyConfiguration = nettyConfiguration; this.sdkChannelOptions = sdkChannelOptions; } /** * Creates a Bootstrap for a specific host and port with an unresolved InetSocketAddress as the remoteAddress. * * @param host The unresolved remote hostname * @param port The remote port * @param useNonBlockingDnsResolver If true, uses the default non-blocking DNS resolver from Netty. Otherwise, the default * JDK blocking DNS resolver will be used. * @return A newly created Bootstrap using the configuration this provider was initialized with, and having an unresolved * remote address. */ public Bootstrap createBootstrap(String host, int port, Boolean useNonBlockingDnsResolver) { Bootstrap bootstrap = new Bootstrap() .group(sdkEventLoopGroup.eventLoopGroup()) .channelFactory(sdkEventLoopGroup.channelFactory()) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfiguration.connectTimeoutMillis()) .option(ChannelOption.SO_KEEPALIVE, nettyConfiguration.tcpKeepAlive()) .remoteAddress(InetSocketAddress.createUnresolved(host, port)); if (Boolean.TRUE.equals(useNonBlockingDnsResolver)) { bootstrap.resolver(DnsResolverLoader.init(sdkEventLoopGroup.datagramChannelFactory())); } sdkChannelOptions.channelOptions().forEach(bootstrap::option); return bootstrap; } }
1,421
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NonManagedEventLoopGroup.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.SUCCEEDED_FUTURE; import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.Future; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Decorator around {@link EventLoopGroup} that prevents it from being shutdown. Used when the customer passes in a * custom {@link EventLoopGroup} that may be shared and thus is not managed by the SDK. */ @SdkInternalApi public final class NonManagedEventLoopGroup extends DelegatingEventLoopGroup { public NonManagedEventLoopGroup(EventLoopGroup delegate) { super(delegate); } @Override public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { return SUCCEEDED_FUTURE; } }
1,422
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ListenerInvokingChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.consumeOrPropagate; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.http2.HttpOrHttp2ChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.metrics.MetricCollector; /** * A {@link SdkChannelPool} that wraps and delegates to another {@link SdkChannelPool} while invoking {@link ChannelPoolListener}s * for important events that occur. * <p> * {@link ChannelPoolListener} is similar to Netty's {@link ChannelPoolHandler} interface, but by invoking them as part of a * {@link SdkChannelPool} wrapper, we are given more control over when they are invoked. For example, {@link * HttpOrHttp2ChannelPool} may choose not to release HTTP/2 stream channels to the lowest-level pool (and instead store the * channels in its own pool), but by instrumenting listeners that sit on top of this layer, we are still given visibility into * these events occurring. */ @SdkInternalApi public final class ListenerInvokingChannelPool implements SdkChannelPool { private final SdkChannelPool delegatePool; private final Supplier<Promise<Channel>> promiseFactory; private final List<ChannelPoolListener> listeners; /** * Listener which is called for various actions performed on a {@link SdkChannelPool}. All listener events are guaranteed to * be invoked as part of the {@link Channel}'s {@link EventLoop}. */ @SdkInternalApi public interface ChannelPoolListener { /** * Called <b>after</b> a {@link Channel} was acquired by calling {@link SdkChannelPool#acquire()} or {@link * SdkChannelPool#acquire(Promise)}. * <p> * This method will be called by the {@link EventLoop} of the {@link Channel}. */ default void channelAcquired(Channel channel) { } /** * Called <b>before</b> a {@link Channel} is released by calling {@link SdkChannelPool#release(Channel)} or {@link * SdkChannelPool#release(Channel, Promise)}. * <p> * This method will be called by the {@link EventLoop} of the {@link Channel}. */ default void channelReleased(Channel channel) { } } public ListenerInvokingChannelPool(EventLoopGroup eventLoopGroup, SdkChannelPool delegatePool, List<ChannelPoolListener> listeners) { this(() -> eventLoopGroup.next().newPromise(), delegatePool, listeners); } public ListenerInvokingChannelPool(Supplier<Promise<Channel>> promiseFactory, SdkChannelPool delegatePool, List<ChannelPoolListener> listeners) { this.delegatePool = delegatePool; this.promiseFactory = promiseFactory; this.listeners = listeners; } @Override public Future<Channel> acquire() { return acquire(promiseFactory.get()); } @Override public Future<Channel> acquire(Promise<Channel> returnFuture) { delegatePool.acquire(promiseFactory.get()) .addListener(consumeOrPropagate(returnFuture, channel -> { NettyUtils.doInEventLoop(channel.eventLoop(), () -> { invokeChannelAcquired(channel); returnFuture.trySuccess(channel); }, returnFuture); })); return returnFuture; } private void invokeChannelAcquired(Channel channel) { listeners.forEach(listener -> listener.channelAcquired(channel)); } @Override public Future<Void> release(Channel channel) { return release(channel, channel.eventLoop().newPromise()); } @Override public Future<Void> release(Channel channel, Promise<Void> returnFuture) { NettyUtils.doInEventLoop(channel.eventLoop(), () -> { invokeChannelReleased(channel); delegatePool.release(channel, returnFuture); }, returnFuture); return returnFuture; } private void invokeChannelReleased(Channel channel) { listeners.forEach(listener -> listener.channelReleased(channel)); } @Override public void close() { delegatePool.close(); } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { return delegatePool.collectChannelPoolMetrics(metrics); } }
1,423
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/Http1TunnelConnectionPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.newSslHandler; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.EventLoop; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.utils.StringUtils; /** * Connection pool that knows how to establish a tunnel using the HTTP CONNECT method. */ @SdkInternalApi public class Http1TunnelConnectionPool implements ChannelPool { static final AttributeKey<Boolean> TUNNEL_ESTABLISHED_KEY = NettyUtils.getOrCreateAttributeKey( "aws.http.nio.netty.async.Http1TunnelConnectionPool.tunnelEstablished"); private static final NettyClientLogger log = NettyClientLogger.getLogger(Http1TunnelConnectionPool.class); private final EventLoop eventLoop; private final ChannelPool delegate; private final SslContext sslContext; private final URI proxyAddress; private final String proxyUser; private final String proxyPassword; private final URI remoteAddress; private final ChannelPoolHandler handler; private final InitHandlerSupplier initHandlerSupplier; private final NettyConfiguration nettyConfiguration; public Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, String proxyUsername, String proxyPassword, URI remoteAddress, ChannelPoolHandler handler, NettyConfiguration nettyConfiguration) { this(eventLoop, delegate, sslContext, proxyAddress, proxyUsername, proxyPassword, remoteAddress, handler, ProxyTunnelInitHandler::new, nettyConfiguration); } public Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, URI remoteAddress, ChannelPoolHandler handler, NettyConfiguration nettyConfiguration) { this(eventLoop, delegate, sslContext, proxyAddress, null, null, remoteAddress, handler, ProxyTunnelInitHandler::new, nettyConfiguration); } @SdkTestInternalApi Http1TunnelConnectionPool(EventLoop eventLoop, ChannelPool delegate, SslContext sslContext, URI proxyAddress, String proxyUser, String proxyPassword, URI remoteAddress, ChannelPoolHandler handler, InitHandlerSupplier initHandlerSupplier, NettyConfiguration nettyConfiguration) { this.eventLoop = eventLoop; this.delegate = delegate; this.sslContext = sslContext; this.proxyAddress = proxyAddress; this.proxyUser = proxyUser; this.proxyPassword = proxyPassword; this.remoteAddress = remoteAddress; this.handler = handler; this.initHandlerSupplier = initHandlerSupplier; this.nettyConfiguration = nettyConfiguration; } @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } @Override public Future<Channel> acquire(Promise<Channel> promise) { delegate.acquire(eventLoop.newPromise()).addListener((Future<Channel> f) -> { if (f.isSuccess()) { setupChannel(f.getNow(), promise); } else { promise.setFailure(f.cause()); } }); return promise; } @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } @Override public Future<Void> release(Channel channel, Promise<Void> promise) { return delegate.release(channel, promise); } @Override public void close() { delegate.close(); } private void setupChannel(Channel ch, Promise<Channel> acquirePromise) { if (isTunnelEstablished(ch)) { log.debug(ch, () -> String.format("Tunnel already established for %s", ch.id().asShortText())); acquirePromise.setSuccess(ch); return; } log.debug(ch, () -> String.format("Tunnel not yet established for channel %s. Establishing tunnel now.", ch.id().asShortText())); Promise<Channel> tunnelEstablishedPromise = eventLoop.newPromise(); SslHandler sslHandler = createSslHandlerIfNeeded(ch.alloc()); if (sslHandler != null) { ch.pipeline().addLast(sslHandler); } ch.pipeline().addLast(initHandlerSupplier.newInitHandler(delegate, proxyUser, proxyPassword, remoteAddress, tunnelEstablishedPromise)); tunnelEstablishedPromise.addListener((Future<Channel> f) -> { if (f.isSuccess()) { Channel tunnel = f.getNow(); handler.channelCreated(tunnel); tunnel.attr(TUNNEL_ESTABLISHED_KEY).set(true); acquirePromise.setSuccess(tunnel); } else { ch.close(); delegate.release(ch); Throwable cause = f.cause(); log.error(ch, () -> String.format("Unable to establish tunnel for channel %s", ch.id().asShortText()), cause); acquirePromise.setFailure(cause); } }); } private SslHandler createSslHandlerIfNeeded(ByteBufAllocator alloc) { if (sslContext == null) { return null; } String scheme = proxyAddress.getScheme(); if (!"https".equals(StringUtils.lowerCase(scheme))) { return null; } return newSslHandler(sslContext, alloc, proxyAddress.getHost(), proxyAddress.getPort(), nettyConfiguration.tlsHandshakeTimeout()); } private static boolean isTunnelEstablished(Channel ch) { Boolean established = ch.attr(TUNNEL_ESTABLISHED_KEY).get(); return Boolean.TRUE.equals(established); } @SdkTestInternalApi @FunctionalInterface interface InitHandlerSupplier { ChannelHandler newInitHandler(ChannelPool sourcePool, String proxyUsername, String proxyPassword, URI remoteAddress, Promise<Channel> tunnelInitFuture); } }
1,424
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/SdkChannelOptions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.ChannelOption; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class SdkChannelOptions { private Map<ChannelOption, Object> options; public SdkChannelOptions() { options = new HashMap<>(); options.put(ChannelOption.TCP_NODELAY, Boolean.TRUE); } public <T> SdkChannelOptions putOption(ChannelOption<T> channelOption, T channelOptionValue) { channelOption.validate(channelOptionValue); options.put(channelOption, channelOptionValue); return this; } public Map<ChannelOption, Object> channelOptions() { return Collections.unmodifiableMap(options); } }
1,425
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/StaticTrustManagerFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.handler.ssl.util.SimpleTrustManagerFactory; import java.security.KeyStore; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class StaticTrustManagerFactory extends SimpleTrustManagerFactory { private final TrustManager[] trustManagers; private StaticTrustManagerFactory(TrustManager[] trustManagers) { this.trustManagers = trustManagers; } @Override protected void engineInit(KeyStore keyStore) { } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) { } @Override protected TrustManager[] engineGetTrustManagers() { return trustManagers; } public static TrustManagerFactory create(TrustManager[] trustManagers) { return new StaticTrustManagerFactory(trustManagers); } }
1,426
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/DnsResolverLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.ChannelFactory; import io.netty.channel.socket.DatagramChannel; import io.netty.resolver.AddressResolverGroup; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.ClassLoaderHelper; /** * Utility class for instantiating netty dns resolvers only if they're available on the class path. */ @SdkProtectedApi public class DnsResolverLoader { private DnsResolverLoader() { } public static AddressResolverGroup<InetSocketAddress> init(ChannelFactory<? extends DatagramChannel> datagramChannelFactory) { try { Class<?> addressResolver = ClassLoaderHelper.loadClass(getAddressResolverGroup(), false, (Class) null); Class<?> dnsNameResolverBuilder = ClassLoaderHelper.loadClass(getDnsNameResolverBuilder(), false, (Class) null); Object dnsResolverObj = dnsNameResolverBuilder.newInstance(); Method method = dnsResolverObj.getClass().getMethod("channelFactory", ChannelFactory.class); method.invoke(dnsResolverObj, datagramChannelFactory); Object e = addressResolver.getConstructor(dnsNameResolverBuilder).newInstance(dnsResolverObj); return (AddressResolverGroup<InetSocketAddress>) e; } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot find module io.netty.resolver.dns " + " To use netty non blocking dns," + " the 'netty-resolver-dns' module from io.netty must be on the class path. ", e); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new IllegalStateException("Failed to create AddressResolverGroup", e); } } private static String getAddressResolverGroup() { return "io.netty.resolver.dns.DnsAddressResolverGroup"; } private static String getDnsNameResolverBuilder() { return "io.netty.resolver.dns.DnsNameResolverBuilder"; } }
1,427
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyRequestMetrics.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.channel.Channel; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2Stream; import io.netty.util.concurrent.Future; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Http2Metric; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.NoOpMetricCollector; /** * Utilities for collecting and publishing request-level metrics. */ @SdkInternalApi public class NettyRequestMetrics { private NettyRequestMetrics() { } /** * Determine whether metrics are enabled, based on the provided metric collector. */ public static boolean metricsAreEnabled(MetricCollector metricCollector) { return metricCollector != null && !(metricCollector instanceof NoOpMetricCollector); } public static void ifMetricsAreEnabled(MetricCollector metrics, Consumer<MetricCollector> metricsConsumer) { if (metricsAreEnabled(metrics)) { metricsConsumer.accept(metrics); } } /** * Publish stream metrics for the provided stream channel to the provided collector. This should only be invoked after * the stream has been initialized. If the stream is not initialized when this is invoked, an exception will be thrown. */ public static void publishHttp2StreamMetrics(MetricCollector metricCollector, Channel channel) { if (!metricsAreEnabled(metricCollector)) { return; } getHttp2Connection(channel).ifPresent(http2Connection -> { writeHttp2RequestMetrics(metricCollector, channel, http2Connection); }); } private static Optional<Http2Connection> getHttp2Connection(Channel channel) { Channel parentChannel = channel.parent(); if (parentChannel == null) { return Optional.empty(); } return Optional.ofNullable(parentChannel.attr(ChannelAttributeKey.HTTP2_CONNECTION).get()); } private static void writeHttp2RequestMetrics(MetricCollector metricCollector, Channel channel, Http2Connection http2Connection) { int streamId = channel.attr(ChannelAttributeKey.HTTP2_FRAME_STREAM).get().id(); Http2Stream stream = http2Connection.stream(streamId); metricCollector.reportMetric(Http2Metric.LOCAL_STREAM_WINDOW_SIZE_IN_BYTES, http2Connection.local().flowController().windowSize(stream)); metricCollector.reportMetric(Http2Metric.REMOTE_STREAM_WINDOW_SIZE_IN_BYTES, http2Connection.remote().flowController().windowSize(stream)); } /** * Measure the time taken for a {@link Future} to complete. Does NOT differentiate between success/failure. */ public static void measureTimeTaken(Future<?> future, Consumer<Duration> onDone) { Instant start = Instant.now(); future.addListener(f -> { Duration elapsed = Duration.between(start, Instant.now()); onDone.accept(elapsed); }); } }
1,428
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/IdleConnectionCountingChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.util.AttributeKey; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.metrics.MetricCollector; /** * A channel pool implementation that tracks the number of "idle" channels in an underlying channel pool. * * <p>Specifically, this pool counts the number of channels acquired and then released from/to the underlying channel pool. It * will monitor for the underlying channels to be closed, and will remove them from the "idle" count. */ @SdkInternalApi public class IdleConnectionCountingChannelPool implements SdkChannelPool { private static final NettyClientLogger log = NettyClientLogger.getLogger(IdleConnectionCountingChannelPool.class); /** * The idle channel state for a specific channel. This should only be accessed from the {@link #executor}. */ private static final AttributeKey<ChannelIdleState> CHANNEL_STATE = NettyUtils.getOrCreateAttributeKey("IdleConnectionCountingChannelPool.CHANNEL_STATE"); /** * The executor in which all updates to {@link #idleConnections} is performed. */ private final EventExecutor executor; /** * The delegate pool to which all acquire and release calls are delegated. */ private final ChannelPool delegatePool; /** * The number of idle connections in the underlying channel pool. This value is only valid if accessed from the * {@link #executor}. */ private int idleConnections = 0; public IdleConnectionCountingChannelPool(EventExecutor executor, ChannelPool delegatePool) { this.executor = executor; this.delegatePool = delegatePool; } @Override public Future<Channel> acquire() { return acquire(executor.newPromise()); } @Override public Future<Channel> acquire(Promise<Channel> promise) { Future<Channel> acquirePromise = delegatePool.acquire(executor.newPromise()); acquirePromise.addListener(f -> { Throwable failure = acquirePromise.cause(); if (failure != null) { promise.setFailure(failure); } else { Channel channel = acquirePromise.getNow(); channelAcquired(channel); promise.setSuccess(channel); } }); return promise; } @Override public Future<Void> release(Channel channel) { return release(channel, new DefaultPromise<>(executor)); } @Override public Future<Void> release(Channel channel, Promise<Void> promise) { channelReleased(channel).addListener(f -> delegatePool.release(channel, promise)); return promise; } @Override public void close() { delegatePool.close(); } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> result = new CompletableFuture<>(); doInEventLoop(executor, () -> { metrics.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, idleConnections); result.complete(null); }).addListener(f -> { if (!f.isSuccess()) { result.completeExceptionally(f.cause()); } }); return result; } /** * Add a listener to the provided channel that will update the idle channel count when the channel is closed. */ private void addUpdateIdleCountOnCloseListener(Channel channel) { channel.closeFuture().addListener(f -> channelClosed(channel)); } /** * Invoked when a channel is acquired, marking it non-idle until it's closed or released. */ private void channelAcquired(Channel channel) { doInEventLoop(executor, () -> { ChannelIdleState channelIdleState = getChannelIdleState(channel); if (channelIdleState == null) { addUpdateIdleCountOnCloseListener(channel); setChannelIdleState(channel, ChannelIdleState.NOT_IDLE); } else { switch (channelIdleState) { case IDLE: decrementIdleConnections(); setChannelIdleState(channel, ChannelIdleState.NOT_IDLE); break; case CLOSED: break; case NOT_IDLE: default: log.warn(channel, () -> "Failed to update idle connection count metric on acquire, because the channel " + "(" + channel + ") was in an unexpected state: " + channelIdleState); } } }); } /** * Invoked when a channel is released, marking it idle until it's acquired. */ private Future<?> channelReleased(Channel channel) { return doInEventLoop(executor, () -> { ChannelIdleState channelIdleState = getChannelIdleState(channel); if (channelIdleState == null) { log.warn(channel, () -> "Failed to update idle connection count metric on release, because the channel (" + channel + ") was in an unexpected state: null"); } else { switch (channelIdleState) { case NOT_IDLE: incrementIdleConnections(); setChannelIdleState(channel, ChannelIdleState.IDLE); break; case CLOSED: break; case IDLE: default: log.warn(channel, () -> "Failed to update idle connection count metric on release, because the channel " + "(" + channel + ") was in an unexpected state: " + channelIdleState); } } }); } /** * Invoked when a channel is closed, ensure it is marked as non-idle. */ private void channelClosed(Channel channel) { doInEventLoop(executor, () -> { ChannelIdleState channelIdleState = getChannelIdleState(channel); setChannelIdleState(channel, ChannelIdleState.CLOSED); if (channelIdleState != null) { switch (channelIdleState) { case IDLE: decrementIdleConnections(); break; case NOT_IDLE: break; default: log.warn(channel, () -> "Failed to update idle connection count metric on close, because the channel (" + channel + ") was in an unexpected state: " + channelIdleState); } } }); } private ChannelIdleState getChannelIdleState(Channel channel) { return channel.attr(CHANNEL_STATE).get(); } private void setChannelIdleState(Channel channel, ChannelIdleState newState) { channel.attr(CHANNEL_STATE).set(newState); } /** * Decrement the idle connection count. This must be invoked from the {@link #executor}. */ private void decrementIdleConnections() { --idleConnections; log.trace(null, () -> "Idle connection count decremented, now " + idleConnections); } /** * Increment the idle connection count. This must be invoked from the {@link #executor}. */ private void incrementIdleConnections() { ++idleConnections; log.trace(null, () -> "Idle connection count incremented, now " + idleConnections); } /** * The idle state of a channel. */ private enum ChannelIdleState { IDLE, NOT_IDLE, CLOSED } }
1,429
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/NettyConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_ACQUIRE_TIMEOUT; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.CONNECTION_TIMEOUT; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_CONNECTIONS; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.MAX_PENDING_CONNECTION_ACQUIRES; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TCP_KEEPALIVE; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; import static software.amazon.awssdk.utils.NumericUtils.saturatedCast; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.TlsKeyManagersProvider; import software.amazon.awssdk.http.TlsTrustManagersProvider; import software.amazon.awssdk.utils.AttributeMap; /** * Internal object for configuring netty. */ @SdkInternalApi public final class NettyConfiguration { public static final int CHANNEL_POOL_CLOSE_TIMEOUT_SECONDS = 5; public static final int EVENTLOOP_SHUTDOWN_QUIET_PERIOD_SECONDS = 2; public static final int EVENTLOOP_SHUTDOWN_TIMEOUT_SECONDS = 15; public static final int EVENTLOOP_SHUTDOWN_FUTURE_TIMEOUT_SECONDS = 16; public static final int HTTP2_CONNECTION_PING_TIMEOUT_SECONDS = 5; private final AttributeMap configuration; public NettyConfiguration(AttributeMap configuration) { this.configuration = configuration; } public <T> T attribute(AttributeMap.Key<T> key) { return configuration.get(key); } public int connectTimeoutMillis() { return saturatedCast(configuration.get(CONNECTION_TIMEOUT).toMillis()); } public int connectionAcquireTimeoutMillis() { return saturatedCast(configuration.get(CONNECTION_ACQUIRE_TIMEOUT).toMillis()); } public int maxConnections() { return configuration.get(MAX_CONNECTIONS); } public int maxPendingConnectionAcquires() { return configuration.get(MAX_PENDING_CONNECTION_ACQUIRES); } public int readTimeoutMillis() { return saturatedCast(configuration.get(SdkHttpConfigurationOption.READ_TIMEOUT).toMillis()); } public int writeTimeoutMillis() { return saturatedCast(configuration.get(SdkHttpConfigurationOption.WRITE_TIMEOUT).toMillis()); } public int idleTimeoutMillis() { return saturatedCast(configuration.get(SdkHttpConfigurationOption.CONNECTION_MAX_IDLE_TIMEOUT).toMillis()); } public int connectionTtlMillis() { return saturatedCast(configuration.get(SdkHttpConfigurationOption.CONNECTION_TIME_TO_LIVE).toMillis()); } public boolean reapIdleConnections() { return configuration.get(SdkHttpConfigurationOption.REAP_IDLE_CONNECTIONS); } public TlsKeyManagersProvider tlsKeyManagersProvider() { return configuration.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER); } public TlsTrustManagersProvider tlsTrustManagersProvider() { return configuration.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER); } public boolean trustAllCertificates() { return configuration.get(TRUST_ALL_CERTIFICATES); } public boolean tcpKeepAlive() { return configuration.get(TCP_KEEPALIVE); } public Duration tlsHandshakeTimeout() { return configuration.get(SdkHttpConfigurationOption.TLS_NEGOTIATION_TIMEOUT); } }
1,430
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/OrderedWriteChannelHandlerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; /** * An implementation of {@link ChannelHandlerContext} that ensures all writes are performed in the order they are invoked. * * This works around https://github.com/netty/netty/issues/7783 where writes by an event loop 'skip ahead' of writes off of the * event loop. */ @SdkInternalApi public class OrderedWriteChannelHandlerContext extends DelegatingChannelHandlerContext { private OrderedWriteChannelHandlerContext(ChannelHandlerContext delegate) { super(delegate); } public static ChannelHandlerContext wrap(ChannelHandlerContext ctx) { return new OrderedWriteChannelHandlerContext(ctx); } @Override public ChannelFuture write(Object msg) { return doInOrder(promise -> super.write(msg, promise)); } @Override public ChannelFuture write(Object msg, ChannelPromise promise) { doInOrder(() -> super.write(msg, promise)); return promise; } @Override public ChannelFuture writeAndFlush(Object msg) { return doInOrder(promise -> { super.writeAndFlush(msg, promise); }); } @Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { doInOrder(() -> { super.writeAndFlush(msg, promise); }); return promise; } private ChannelFuture doInOrder(Consumer<ChannelPromise> task) { ChannelPromise promise = newPromise(); if (!channel().eventLoop().inEventLoop()) { task.accept(promise); } else { // If we're in the event loop, queue a task to perform the write, so that it occurs after writes that were scheduled // off of the event loop. channel().eventLoop().execute(() -> task.accept(promise)); } return promise; } private void doInOrder(Runnable task) { if (!channel().eventLoop().inEventLoop()) { task.run(); } else { // If we're in the event loop, queue a task to perform the write, so that it occurs after writes that were scheduled // off of the event loop. channel().eventLoop().execute(task); } } }
1,431
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ExceptionHandlingUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import java.util.concurrent.Callable; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class ExceptionHandlingUtils { private ExceptionHandlingUtils() { } /** * Runs a task within try-catch block. All exceptions thrown from the execution * will be sent to errorNotifier. * * <p> * This is useful for single-line executable code to avoid try-catch code clutter. * * @param executable the task to run * @param errorNotifier error notifier */ public static void tryCatch(Runnable executable, Consumer<Throwable> errorNotifier) { try { executable.run(); } catch (Throwable throwable) { errorNotifier.accept(throwable); } } /** * Runs a task within try-catch-finally block. All exceptions thrown from the execution * will be sent to errorNotifier. * * <p> * This is useful for single-line executable code to avoid try-catch code clutter. * * @param executable the task to run * @param errorNotifier the error notifier * @param cleanupExecutable the cleanup executable * @param <T> the type of the object to be returned * @return the object if succeeds */ public static <T> T tryCatchFinally(Callable<T> executable, Consumer<Throwable> errorNotifier, Runnable cleanupExecutable) { try { return executable.call(); } catch (Throwable throwable) { errorNotifier.accept(throwable); } finally { cleanupExecutable.run(); } return null; } }
1,432
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/DelegatingChannelHandlerContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.concurrent.EventExecutor; import java.net.SocketAddress; import software.amazon.awssdk.annotations.SdkInternalApi; /** * An abstract implementation of {@link ChannelHandlerContext} that delegates to another * context for non-overridden methods. */ @SdkInternalApi public abstract class DelegatingChannelHandlerContext implements ChannelHandlerContext { private final ChannelHandlerContext delegate; public DelegatingChannelHandlerContext(ChannelHandlerContext delegate) { this.delegate = delegate; } @Override public Channel channel() { return delegate.channel(); } @Override public EventExecutor executor() { return delegate.executor(); } @Override public String name() { return delegate.name(); } @Override public ChannelHandler handler() { return delegate.handler(); } @Override public boolean isRemoved() { return delegate.isRemoved(); } @Override public ChannelHandlerContext fireChannelRegistered() { return delegate.fireChannelRegistered(); } @Override public ChannelHandlerContext fireChannelUnregistered() { return delegate.fireChannelUnregistered(); } @Override public ChannelHandlerContext fireChannelActive() { return delegate.fireChannelActive(); } @Override public ChannelHandlerContext fireChannelInactive() { return delegate.fireChannelInactive(); } @Override public ChannelHandlerContext fireExceptionCaught(Throwable cause) { return delegate.fireExceptionCaught(cause); } @Override public ChannelHandlerContext fireUserEventTriggered(Object evt) { return delegate.fireUserEventTriggered(evt); } @Override public ChannelHandlerContext fireChannelRead(Object msg) { return delegate.fireChannelRead(msg); } @Override public ChannelHandlerContext fireChannelReadComplete() { return delegate.fireChannelReadComplete(); } @Override public ChannelHandlerContext fireChannelWritabilityChanged() { return delegate.fireChannelWritabilityChanged(); } @Override public ChannelFuture bind(SocketAddress localAddress) { return delegate.bind(localAddress); } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return delegate.connect(remoteAddress); } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { return delegate.connect(remoteAddress, localAddress); } @Override public ChannelFuture disconnect() { return delegate.disconnect(); } @Override public ChannelFuture close() { return delegate.close(); } @Override public ChannelFuture deregister() { return delegate.deregister(); } @Override public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { return delegate.bind(localAddress, promise); } @Override public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { return delegate.connect(remoteAddress, promise); } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { return delegate.connect(remoteAddress, localAddress, promise); } @Override public ChannelFuture disconnect(ChannelPromise promise) { return delegate.disconnect(promise); } @Override public ChannelFuture close(ChannelPromise promise) { return delegate.close(promise); } @Override public ChannelFuture deregister(ChannelPromise promise) { return delegate.deregister(promise); } @Override public ChannelHandlerContext read() { return delegate.read(); } @Override public ChannelFuture write(Object msg) { return delegate.write(msg); } @Override public ChannelFuture write(Object msg, ChannelPromise promise) { return delegate.write(msg, promise); } @Override public ChannelHandlerContext flush() { return delegate.flush(); } @Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { return delegate.writeAndFlush(msg, promise); } @Override public ChannelFuture writeAndFlush(Object msg) { return delegate.writeAndFlush(msg); } @Override public ChannelPromise newPromise() { return delegate.newPromise(); } @Override public ChannelProgressivePromise newProgressivePromise() { return delegate.newProgressivePromise(); } @Override public ChannelFuture newSucceededFuture() { return delegate.newSucceededFuture(); } @Override public ChannelFuture newFailedFuture(Throwable cause) { return delegate.newFailedFuture(cause); } @Override public ChannelPromise voidPromise() { return delegate.voidPromise(); } @Override public ChannelPipeline pipeline() { return delegate.pipeline(); } @Override public ByteBufAllocator alloc() { return delegate.alloc(); } @Override public <T> Attribute<T> attr(AttributeKey<T> key) { return delegate.attr(key); } @Override public <T> boolean hasAttr(AttributeKey<T> key) { return delegate.hasAttr(key); } }
1,433
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/BetterFixedChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import io.netty.channel.Channel; import io.netty.channel.pool.ChannelPool; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.ThrowableUtil; import java.nio.channels.ClosedChannelException; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool; import software.amazon.awssdk.metrics.MetricCollector; /** * {@link ChannelPool} implementation that takes another {@link ChannelPool} implementation and enforce a maximum * number of concurrent connections. */ //TODO: Contribute me back to Netty public class BetterFixedChannelPool implements SdkChannelPool { private static final IllegalStateException FULL_EXCEPTION = ThrowableUtil.unknownStackTrace( new IllegalStateException("Too many outstanding acquire operations"), BetterFixedChannelPool.class, "acquire0(...)"); private static final TimeoutException TIMEOUT_EXCEPTION = ThrowableUtil.unknownStackTrace( new TimeoutException("Acquire operation took longer than configured maximum time"), BetterFixedChannelPool.class, "<init>(...)"); static final IllegalStateException POOL_CLOSED_ON_RELEASE_EXCEPTION = ThrowableUtil.unknownStackTrace( new IllegalStateException("BetterFixedChannelPooled was closed"), BetterFixedChannelPool.class, "release(...)"); static final IllegalStateException POOL_CLOSED_ON_ACQUIRE_EXCEPTION = ThrowableUtil.unknownStackTrace( new IllegalStateException("BetterFixedChannelPooled was closed"), BetterFixedChannelPool.class, "acquire0(...)"); public enum AcquireTimeoutAction { /** * Create a new connection when the timeout is detected. */ NEW, /** * Fail the {@link Future} of the acquire call with a {@link TimeoutException}. */ FAIL } private final EventExecutor executor; private final long acquireTimeoutNanos; private final Runnable timeoutTask; private final SdkChannelPool delegateChannelPool; // There is no need to worry about synchronization as everything that modified the queue or counts is done // by the above EventExecutor. private final Queue<AcquireTask> pendingAcquireQueue = new ArrayDeque<>(); private final int maxConnections; private final int maxPendingAcquires; private int acquiredChannelCount; private int pendingAcquireCount; private boolean closed; private BetterFixedChannelPool(Builder builder) { if (builder.maxConnections < 1) { throw new IllegalArgumentException("maxConnections: " + builder.maxConnections + " (expected: >= 1)"); } if (builder.maxPendingAcquires < 1) { throw new IllegalArgumentException("maxPendingAcquires: " + builder.maxPendingAcquires + " (expected: >= 1)"); } this.delegateChannelPool = builder.channelPool; this.executor = builder.executor; if (builder.action == null && builder.acquireTimeoutMillis == -1) { timeoutTask = null; acquireTimeoutNanos = -1; } else if (builder.action == null && builder.acquireTimeoutMillis != -1) { throw new NullPointerException("action"); } else if (builder.action != null && builder.acquireTimeoutMillis < 0) { throw new IllegalArgumentException("acquireTimeoutMillis: " + builder.acquireTimeoutMillis + " (expected: >= 0)"); } else { acquireTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(builder.acquireTimeoutMillis); switch (builder.action) { case FAIL: timeoutTask = new TimeoutTask() { @Override public void onTimeout(AcquireTask task) { // Fail the promise as we timed out. task.promise.setFailure(TIMEOUT_EXCEPTION); } }; break; case NEW: timeoutTask = new TimeoutTask() { @Override public void onTimeout(AcquireTask task) { // Increment the acquire count and delegate to super to actually acquire a Channel which will // create a new connection. task.acquired(); delegateChannelPool.acquire(task.promise); } }; break; default: throw new Error(); } } this.maxConnections = builder.maxConnections; this.maxPendingAcquires = builder.maxPendingAcquires; } @Override public Future<Channel> acquire() { return acquire(new DefaultPromise<>(executor)); } @Override public Future<Channel> acquire(final Promise<Channel> promise) { try { if (executor.inEventLoop()) { acquire0(promise); } else { executor.execute(() -> acquire0(promise)); } } catch (Throwable cause) { promise.setFailure(cause); } return promise; } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> delegateMetricResult = delegateChannelPool.collectChannelPoolMetrics(metrics); CompletableFuture<Void> result = new CompletableFuture<>(); doInEventLoop(executor, () -> { try { metrics.reportMetric(HttpMetric.MAX_CONCURRENCY, this.maxConnections); metrics.reportMetric(HttpMetric.PENDING_CONCURRENCY_ACQUIRES, this.pendingAcquireCount); metrics.reportMetric(HttpMetric.LEASED_CONCURRENCY, this.acquiredChannelCount); result.complete(null); } catch (Throwable t) { result.completeExceptionally(t); } }); return CompletableFuture.allOf(result, delegateMetricResult); } private void acquire0(final Promise<Channel> promise) { assert executor.inEventLoop(); if (closed) { promise.setFailure(POOL_CLOSED_ON_ACQUIRE_EXCEPTION); return; } if (acquiredChannelCount < maxConnections) { assert acquiredChannelCount >= 0; // We need to create a new promise as we need to ensure the AcquireListener runs in the correct // EventLoop Promise<Channel> p = executor.newPromise(); AcquireListener l = new AcquireListener(promise); l.acquired(); p.addListener(l); delegateChannelPool.acquire(p); } else { if (pendingAcquireCount >= maxPendingAcquires) { promise.setFailure(FULL_EXCEPTION); } else { AcquireTask task = new AcquireTask(promise); if (pendingAcquireQueue.offer(task)) { ++pendingAcquireCount; if (timeoutTask != null) { task.timeoutFuture = executor.schedule(timeoutTask, acquireTimeoutNanos, TimeUnit.NANOSECONDS); } } else { promise.setFailure(FULL_EXCEPTION); } } assert pendingAcquireCount > 0; } } @Override public Future<Void> release(Channel channel) { return release(channel, new DefaultPromise<>(executor)); } @Override public Future<Void> release(final Channel channel, final Promise<Void> promise) { ObjectUtil.checkNotNull(promise, "promise"); Promise<Void> p = executor.newPromise(); delegateChannelPool.release(channel, p.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { assert executor.inEventLoop(); if (closed) { // Since the pool is closed, we have no choice but to close the channel channel.close(); promise.setFailure(POOL_CLOSED_ON_RELEASE_EXCEPTION); return; } if (future.isSuccess()) { decrementAndRunTaskQueue(); promise.setSuccess(null); } else { Throwable cause = future.cause(); // Check if the exception was not because of we passed the Channel to the wrong pool. if (!(cause instanceof IllegalArgumentException)) { decrementAndRunTaskQueue(); } promise.setFailure(future.cause()); } } })); return promise; } private void decrementAndRunTaskQueue() { --acquiredChannelCount; // We should never have a negative value. assert acquiredChannelCount >= 0; // Run the pending acquire tasks before notify the original promise so if the user would // try to acquire again from the ChannelFutureListener and the pendingAcquireCount is >= // maxPendingAcquires we may be able to run some pending tasks first and so allow to add // more. runTaskQueue(); } private void runTaskQueue() { while (acquiredChannelCount < maxConnections) { AcquireTask task = pendingAcquireQueue.poll(); if (task == null) { break; } // Cancel the timeout if one was scheduled ScheduledFuture<?> timeoutFuture = task.timeoutFuture; if (timeoutFuture != null) { timeoutFuture.cancel(false); } --pendingAcquireCount; task.acquired(); delegateChannelPool.acquire(task.promise); } // We should never have a negative value. assert pendingAcquireCount >= 0; assert acquiredChannelCount >= 0; } // AcquireTask extends AcquireListener to reduce object creations and so GC pressure private final class AcquireTask extends AcquireListener { final Promise<Channel> promise; final long expireNanoTime = System.nanoTime() + acquireTimeoutNanos; ScheduledFuture<?> timeoutFuture; public AcquireTask(Promise<Channel> promise) { super(promise); // We need to create a new promise as we need to ensure the AcquireListener runs in the correct // EventLoop. this.promise = executor.<Channel>newPromise().addListener(this); } } private abstract class TimeoutTask implements Runnable { @Override public final void run() { assert executor.inEventLoop(); long nanoTime = System.nanoTime(); for (; ; ) { AcquireTask task = pendingAcquireQueue.peek(); // Compare nanoTime as descripted in the javadocs of System.nanoTime() // // See https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime() // See https://github.com/netty/netty/issues/3705 if (task == null || nanoTime - task.expireNanoTime < 0) { break; } pendingAcquireQueue.remove(); --pendingAcquireCount; onTimeout(task); } } public abstract void onTimeout(AcquireTask task); } private class AcquireListener implements FutureListener<Channel> { private final Promise<Channel> originalPromise; protected boolean acquired; AcquireListener(Promise<Channel> originalPromise) { this.originalPromise = originalPromise; } @Override public void operationComplete(Future<Channel> future) throws Exception { assert executor.inEventLoop(); if (closed) { if (future.isSuccess()) { // Since the pool is closed, we have no choice but to close the channel future.getNow().close(); } originalPromise.setFailure(POOL_CLOSED_ON_ACQUIRE_EXCEPTION); return; } if (future.isSuccess()) { originalPromise.setSuccess(future.getNow()); } else { if (acquired) { decrementAndRunTaskQueue(); } else { runTaskQueue(); } originalPromise.setFailure(future.cause()); } } public void acquired() { if (acquired) { return; } acquiredChannelCount++; acquired = true; } } @Override public void close() { if (executor.inEventLoop()) { close0(); } else { executor.submit(() -> close0()).awaitUninterruptibly(); } } private void close0() { if (!closed) { closed = true; for (;;) { AcquireTask task = pendingAcquireQueue.poll(); if (task == null) { break; } ScheduledFuture<?> f = task.timeoutFuture; if (f != null) { f.cancel(false); } task.promise.setFailure(new ClosedChannelException()); } acquiredChannelCount = 0; pendingAcquireCount = 0; // Ensure we dispatch this on another Thread as close0 will be called from the EventExecutor and we need // to ensure we will not block in a EventExecutor. GlobalEventExecutor.INSTANCE.execute(() -> delegateChannelPool.close()); } } public static Builder builder() { return new Builder(); } public static final class Builder { private SdkChannelPool channelPool; private EventExecutor executor; private AcquireTimeoutAction action; private long acquireTimeoutMillis; private int maxConnections; private int maxPendingAcquires; private Builder() { } public Builder channelPool(SdkChannelPool channelPool) { this.channelPool = channelPool; return this; } public Builder executor(EventExecutor executor) { this.executor = executor; return this; } public Builder acquireTimeoutAction(AcquireTimeoutAction action) { this.action = action; return this; } public Builder acquireTimeoutMillis(long acquireTimeoutMillis) { this.acquireTimeoutMillis = acquireTimeoutMillis; return this; } public Builder maxConnections(int maxConnections) { this.maxConnections = maxConnections; return this; } public Builder maxPendingAcquires(int maxPendingAcquires) { this.maxPendingAcquires = maxPendingAcquires; return this; } public BetterFixedChannelPool build() { return new BetterFixedChannelPool(this); } } }
1,434
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyClientLogger.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import io.netty.channel.Channel; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * Logger facade similar to {@link software.amazon.awssdk.utils.Logger}, that also includes channel information in the message * when provided. When the logger has at least DEBUG level enabled, the logger uses {@link Channel#toString()} to provide the * complete information about the channel. If only less verbose levels are available, then only the channel's ID is logged. * <p> * Having the channel information associated with the log message whenever available makes correlating messages that are all * logged within the context of that channel possible; this is impossible to do otherwise because there is a 1:M mapping from * event loops to channels. * <p> * <b>NOTE:</b> The absence of overrides that don't take a {@code Channel} parameter is deliberate. This is done to lessen the * chances that a {code Channel} is omitted from the log by accident. */ @SdkInternalApi public final class NettyClientLogger { private final Logger delegateLogger; @SdkTestInternalApi NettyClientLogger(Logger delegateLogger) { this.delegateLogger = delegateLogger; } public static NettyClientLogger getLogger(Class<?> clzz) { Logger delegate = LoggerFactory.getLogger(clzz); return new NettyClientLogger(delegate); } /** * Log a DEBUG level message including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message */ public void debug(Channel channel, Supplier<String> msgSupplier) { debug(channel, msgSupplier, null); } /** * Log a DEBUG level message with the given exception and including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message * @param t The throwable to log */ public void debug(Channel channel, Supplier<String> msgSupplier, Throwable t) { if (!delegateLogger.isDebugEnabled()) { return; } String finalMessage = prependChannelInfo(msgSupplier, channel); delegateLogger.debug(finalMessage, t); } /** * Log a WARN level message and including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message */ public void warn(Channel channel, Supplier<String> msgSupplier) { warn(channel, msgSupplier, null); } /** * Log a ERROR level message with the given exception and including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message * @param t The throwable to log */ public void error(Channel channel, Supplier<String> msgSupplier, Throwable t) { if (!delegateLogger.isErrorEnabled()) { return; } String finalMessage = prependChannelInfo(msgSupplier, channel); delegateLogger.error(finalMessage, t); } /** * Log a ERROR level message and including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message */ public void error(Channel channel, Supplier<String> msgSupplier) { warn(channel, msgSupplier, null); } /** * Log a WARN level message with the given exception and including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message * @param t The throwable to log */ public void warn(Channel channel, Supplier<String> msgSupplier, Throwable t) { if (!delegateLogger.isWarnEnabled()) { return; } String finalMessage = prependChannelInfo(msgSupplier, channel); delegateLogger.warn(finalMessage, t); } /** * Log a TRACE level message including the channel information. * * @param channel The channel for this message is being logged * @param msgSupplier Supplier for the log message */ public void trace(Channel channel, Supplier<String> msgSupplier) { if (!delegateLogger.isTraceEnabled()) { return; } String finalMessage = prependChannelInfo(msgSupplier, channel); delegateLogger.trace(finalMessage); } private String prependChannelInfo(Supplier<String> msgSupplier, Channel channel) { if (channel == null) { return msgSupplier.get(); } String id; if (!delegateLogger.isDebugEnabled()) { id = channel.id().asShortText(); } else { id = channel.toString(); } return String.format("[Channel: %s] %s", id, msgSupplier.get()); } }
1,435
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import io.netty.channel.Channel; import io.netty.channel.ChannelFactory; import io.netty.channel.EventLoopGroup; import io.netty.channel.ReflectiveChannelFactory; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.DelegatingEventLoopGroup; @SdkInternalApi public final class ChannelResolver { private static final Map<String, String> KNOWN_EL_GROUPS_SOCKET_CHANNELS = new HashMap<>(); private static final Map<String, String> KNOWN_EL_GROUPS_DATAGRAM_CHANNELS = new HashMap<>(); static { KNOWN_EL_GROUPS_SOCKET_CHANNELS.put("io.netty.channel.kqueue.KQueueEventLoopGroup", "io.netty.channel.kqueue.KQueueSocketChannel"); KNOWN_EL_GROUPS_SOCKET_CHANNELS.put("io.netty.channel.oio.OioEventLoopGroup", "io.netty.channel.socket.oio.OioSocketChannel"); KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.put("io.netty.channel.kqueue.KQueueEventLoopGroup", "io.netty.channel.kqueue.KQueueDatagramChannel"); KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.put("io.netty.channel.oio.OioEventLoopGroup", "io.netty.channel.socket.oio.OioDatagramChannel"); } private ChannelResolver() { } /** * Attempts to determine the {@link ChannelFactory} class that corresponds to the given * event loop group. * * @param eventLoopGroup the event loop group to determine the {@link ChannelFactory} for * @return A {@link ChannelFactory} instance for the given event loop group. */ @SuppressWarnings("unchecked") public static ChannelFactory<? extends Channel> resolveSocketChannelFactory(EventLoopGroup eventLoopGroup) { if (eventLoopGroup instanceof DelegatingEventLoopGroup) { return resolveSocketChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate()); } if (eventLoopGroup instanceof NioEventLoopGroup) { return NioSocketChannel::new; } if (eventLoopGroup instanceof EpollEventLoopGroup) { return EpollSocketChannel::new; } String socketFqcn = KNOWN_EL_GROUPS_SOCKET_CHANNELS.get(eventLoopGroup.getClass().getName()); if (socketFqcn == null) { throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass()); } return invokeSafely(() -> new ReflectiveChannelFactory(Class.forName(socketFqcn))); } /** * Attempts to determine the {@link ChannelFactory} class for datagram channels that corresponds to the given * event loop group. * * @param eventLoopGroup the event loop group to determine the {@link ChannelFactory} for * @return A {@link ChannelFactory} instance for the given event loop group. */ @SuppressWarnings("unchecked") public static ChannelFactory<? extends DatagramChannel> resolveDatagramChannelFactory(EventLoopGroup eventLoopGroup) { if (eventLoopGroup instanceof DelegatingEventLoopGroup) { return resolveDatagramChannelFactory(((DelegatingEventLoopGroup) eventLoopGroup).getDelegate()); } if (eventLoopGroup instanceof NioEventLoopGroup) { return NioDatagramChannel::new; } if (eventLoopGroup instanceof EpollEventLoopGroup) { return EpollDatagramChannel::new; } String datagramFqcn = KNOWN_EL_GROUPS_DATAGRAM_CHANNELS.get(eventLoopGroup.getClass().getName()); if (datagramFqcn == null) { throw new IllegalArgumentException("Unknown event loop group : " + eventLoopGroup.getClass()); } return invokeSafely(() -> new ReflectiveChannelFactory(Class.forName(datagramFqcn))); } }
1,436
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/NettyUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.CHANNEL_DIAGNOSTICS; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.ReadTimeoutException; import io.netty.handler.timeout.WriteTimeoutException; import io.netty.util.AttributeKey; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.SucceededFuture; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.ChannelDiagnostics; import software.amazon.awssdk.utils.FunctionalUtils; import software.amazon.awssdk.utils.Logger; @SdkInternalApi public final class NettyUtils { /** * Completed succeed future. */ public static final SucceededFuture<?> SUCCEEDED_FUTURE = new SucceededFuture<>(null, null); public static final String CLOSED_CHANNEL_ERROR_MESSAGE = "The connection was closed during the request. The request will " + "usually succeed on a retry, but if it does not: consider " + "disabling any proxies you have configured, enabling debug " + "logging, or performing a TCP dump to identify the root cause. " + "If this is a streaming operation, validate that data is being " + "read or written in a timely manner."; private static final Logger log = Logger.loggerFor(NettyUtils.class); private NettyUtils() { } public static Throwable decorateException(Channel channel, Throwable originalCause) { if (isAcquireTimeoutException(originalCause)) { return new Throwable(getMessageForAcquireTimeoutException(), originalCause); } else if (isTooManyPendingAcquiresException(originalCause)) { return new Throwable(getMessageForTooManyAcquireOperationsError(), originalCause); } else if (originalCause instanceof ReadTimeoutException) { return new IOException("Read timed out", originalCause); } else if (originalCause instanceof WriteTimeoutException) { return new IOException("Write timed out", originalCause); } else if (originalCause instanceof ClosedChannelException || isConnectionResetException(originalCause)) { return new IOException(NettyUtils.closedChannelMessage(channel), originalCause); } return originalCause; } private static boolean isConnectionResetException(Throwable originalCause) { String message = originalCause.getMessage(); return originalCause instanceof IOException && message != null && message.contains("Connection reset by peer"); } private static boolean isAcquireTimeoutException(Throwable originalCause) { String message = originalCause.getMessage(); return originalCause instanceof TimeoutException && message != null && message.contains("Acquire operation took longer"); } private static boolean isTooManyPendingAcquiresException(Throwable originalCause) { String message = originalCause.getMessage(); return originalCause instanceof IllegalStateException && message != null && message.contains("Too many outstanding acquire operations"); } private static String getMessageForAcquireTimeoutException() { return "Acquire operation took longer than the configured maximum time. This indicates that a request cannot get a " + "connection from the pool within the specified maximum time. This can be due to high request rate.\n" + "Consider taking any of the following actions to mitigate the issue: increase max connections, " + "increase acquire timeout, or slowing the request rate.\n" + "Increasing the max connections can increase client throughput (unless the network interface is already " + "fully utilized), but can eventually start to hit operation system limitations on the number of file " + "descriptors used by the process. If you already are fully utilizing your network interface or cannot " + "further increase your connection count, increasing the acquire timeout gives extra time for requests to " + "acquire a connection before timing out. If the connections doesn't free up, the subsequent requests " + "will still timeout.\n" + "If the above mechanisms are not able to fix the issue, try smoothing out your requests so that large " + "traffic bursts cannot overload the client, being more efficient with the number of times you need to " + "call AWS, or by increasing the number of hosts sending requests."; } private static String getMessageForTooManyAcquireOperationsError() { return "Maximum pending connection acquisitions exceeded. The request rate is too high for the client to keep up.\n" + "Consider taking any of the following actions to mitigate the issue: increase max connections, " + "increase max pending acquire count, decrease connection acquisition timeout, or " + "slow the request rate.\n" + "Increasing the max connections can increase client throughput (unless the network interface is already " + "fully utilized), but can eventually start to hit operation system limitations on the number of file " + "descriptors used by the process. If you already are fully utilizing your network interface or cannot " + "further increase your connection count, increasing the pending acquire count allows extra requests to be " + "buffered by the client, but can cause additional request latency and higher memory usage. If your request" + " latency or memory usage is already too high, decreasing the lease timeout will allow requests to fail " + "more quickly, reducing the number of pending connection acquisitions, but likely won't decrease the total " + "number of failed requests.\n" + "If the above mechanisms are not able to fix the issue, try smoothing out your requests so that large " + "traffic bursts cannot overload the client, being more efficient with the number of times you need to call " + "AWS, or by increasing the number of hosts sending requests."; } public static String closedChannelMessage(Channel channel) { ChannelDiagnostics channelDiagnostics = channel != null && channel.attr(CHANNEL_DIAGNOSTICS) != null ? channel.attr(CHANNEL_DIAGNOSTICS).get() : null; ChannelDiagnostics parentChannelDiagnostics = channel != null && channel.parent() != null && channel.parent().attr(CHANNEL_DIAGNOSTICS) != null ? channel.parent().attr(CHANNEL_DIAGNOSTICS).get() : null; StringBuilder error = new StringBuilder(); error.append(CLOSED_CHANNEL_ERROR_MESSAGE); if (channelDiagnostics != null) { error.append(" Channel Information: ").append(channelDiagnostics); if (parentChannelDiagnostics != null) { error.append(" Parent Channel Information: ").append(parentChannelDiagnostics); } } return error.toString(); } /** * Creates a {@link BiConsumer} that notifies the promise of any failures either via the {@link Throwable} passed into the * BiConsumer of as a result of running the successFunction. * * @param successFunction Function called to process the successful result and map it into the result to notify the promise * with. * @param promise Promise to notify of success or failure. * @param <SuccessT> Success type. * @param <PromiseT> Type being fulfilled by the promise. * @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method. */ public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> promiseNotifyingBiConsumer( Function<SuccessT, PromiseT> successFunction, Promise<PromiseT> promise) { return (success, fail) -> { if (fail != null) { promise.setFailure(fail); } else { try { promise.setSuccess(successFunction.apply(success)); } catch (Throwable e) { promise.setFailure(e); } } }; } /** * Creates a {@link BiConsumer} that notifies the promise of any failures either via the throwable passed into the BiConsumer * or as a result of running the successConsumer. This assumes that the successConsumer will notify the promise when it * completes successfully. * * @param successConsumer BiConsumer to call if the result is successful. Promise is also passed and must be notified on * success. * @param promise Promise to notify. * @param <SuccessT> Success type. * @param <PromiseT> Type being fulfilled by the Promise. * @return BiConsumer that can be used in a {@link CompletableFuture#whenComplete(BiConsumer)} method. */ public static <SuccessT, PromiseT> BiConsumer<SuccessT, ? super Throwable> asyncPromiseNotifyingBiConsumer( BiConsumer<SuccessT, Promise<PromiseT>> successConsumer, Promise<PromiseT> promise) { return (success, fail) -> { if (fail != null) { promise.setFailure(fail); } else { try { successConsumer.accept(success, promise); } catch (Throwable e) { // If the successConsumer fails synchronously then we can notify the promise. If it fails asynchronously // it's up to the successConsumer to notify. promise.setFailure(e); } } }; } /** * Create a {@link GenericFutureListener} that will notify the provided {@link Promise} on success and failure. * * @param channelPromise Promise to notify. * @return GenericFutureListener */ public static <T> GenericFutureListener<Future<T>> promiseNotifyingListener(Promise<T> channelPromise) { return future -> { if (future.isSuccess()) { channelPromise.setSuccess(future.getNow()); } else { channelPromise.setFailure(future.cause()); } }; } /** * Runs a task in the given {@link EventExecutor}. Runs immediately if the current thread is in the * eventExecutor. * * @param eventExecutor Executor to run task in. * @param runnable Task to run. * * @return The {@code Future} from from the executor. */ public static Future<?> doInEventLoop(EventExecutor eventExecutor, Runnable runnable) { if (eventExecutor.inEventLoop()) { try { runnable.run(); return eventExecutor.newSucceededFuture(null); } catch (Throwable t) { return eventExecutor.newFailedFuture(t); } } return eventExecutor.submit(runnable); } /** * Runs a task in the given {@link EventExecutor}. Runs immediately if the current thread is in the * eventExecutor. Notifies the given {@link Promise} if a failure occurs. * * @param eventExecutor Executor to run task in. * @param runnable Task to run. * @param promise Promise to notify if failure occurs. */ public static void doInEventLoop(EventExecutor eventExecutor, Runnable runnable, Promise<?> promise) { try { if (eventExecutor.inEventLoop()) { runnable.run(); } else { eventExecutor.submit(() -> { try { runnable.run(); } catch (Throwable e) { promise.setFailure(e); } }); } } catch (Throwable e) { promise.setFailure(e); } } public static void warnIfNotInEventLoop(EventLoop loop) { assert loop.inEventLoop(); if (!loop.inEventLoop()) { Exception exception = new IllegalStateException("Execution is not in the expected event loop. Please report this issue to the " + "AWS SDK for Java team on GitHub, because it could result in race conditions."); log.warn(() -> "Execution is happening outside of the expected event loop.", exception); } } /** * @return an {@code AttributeKey} for {@code attr}. This returns an existing instance if it was previously created. */ public static <T> AttributeKey<T> getOrCreateAttributeKey(String attr) { if (AttributeKey.exists(attr)) { return AttributeKey.valueOf(attr); } //CHECKSTYLE:OFF - This is the only place allowed to call AttributeKey.newInstance() return AttributeKey.newInstance(attr); //CHECKSTYLE:ON } /** * @return a new {@link SslHandler} with ssl engine configured */ public static SslHandler newSslHandler(SslContext sslContext, ByteBufAllocator alloc, String peerHost, int peerPort, Duration handshakeTimeout) { // Need to provide host and port to enable SNI // https://github.com/netty/netty/issues/3801#issuecomment-104274440 SslHandler sslHandler = sslContext.newHandler(alloc, peerHost, peerPort); sslHandler.setHandshakeTimeout(handshakeTimeout.toMillis(), TimeUnit.MILLISECONDS); configureSslEngine(sslHandler.engine()); return sslHandler; } /** * Enable Hostname verification. * * See https://netty.io/4.0/api/io/netty/handler/ssl/SslContext.html#newHandler-io.netty.buffer.ByteBufAllocator-java.lang * .String-int- * * @param sslEngine the sslEngine to configure */ private static void configureSslEngine(SSLEngine sslEngine) { SSLParameters sslParameters = sslEngine.getSSLParameters(); sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParameters); } /** * Create a {@link GenericFutureListener} that will propagate any failures or cancellations to the provided {@link Promise}, * or invoke the provided {@link Consumer} with the result of a successful operation completion. This is useful for chaining * together multiple futures that may depend upon each other but that may not have the same return type. * <p> * Note that if you do not need the value returned by a successful completion (or if it returns {@link Void}) you may use * {@link #runOrPropagate(Promise, Runnable)} instead. * * @param destination the Promise to notify upon failure or cancellation * @param onSuccess the Consumer to invoke upon success */ public static <T> GenericFutureListener<Future<T>> consumeOrPropagate(Promise<?> destination, Consumer<T> onSuccess) { return f -> { if (f.isSuccess()) { try { T result = f.getNow(); onSuccess.accept(result); } catch (Throwable t) { destination.tryFailure(t); } } else if (f.isCancelled()) { destination.cancel(false); } else { destination.tryFailure(f.cause()); } }; } /** * Create a {@link GenericFutureListener} that will propagate any failures or cancellations to the provided {@link Promise}, * or invoke the provided {@link Runnable} upon successful operation completion. This is useful for chaining together multiple * futures that may depend upon each other but that may not have the same return type. * * @param destination the Promise to notify upon failure or cancellation * @param onSuccess the Runnable to invoke upon success */ public static <T> GenericFutureListener<Future<T>> runOrPropagate(Promise<?> destination, Runnable onSuccess) { return f -> { if (f.isSuccess()) { try { onSuccess.run(); } catch (Throwable t) { destination.tryFailure(t); } } else if (f.isCancelled()) { destination.cancel(false); } else { destination.tryFailure(f.cause()); } }; } public static void runAndLogError(NettyClientLogger log, String errorMsg, FunctionalUtils.UnsafeRunnable runnable) { try { runnable.run(); } catch (Exception e) { log.error(null, () -> errorMsg, e); } } }
1,437
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/utils/ChannelUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.utils; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import java.util.NoSuchElementException; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class ChannelUtils { private ChannelUtils() { } /** * Removes handlers of the given class types from the pipeline. * * @param pipeline the pipeline to remove handlers from * @param handlers handlers to remove, identified by class */ @SafeVarargs public static void removeIfExists(ChannelPipeline pipeline, Class<? extends ChannelHandler>... handlers) { for (Class<? extends ChannelHandler> handler : handlers) { if (pipeline.get(handler) != null) { try { pipeline.remove(handler); } catch (NoSuchElementException exception) { // There could still be race condition when channel gets // closed right after removeIfExists is invoked. Ignoring // NoSuchElementException for that edge case. } } } } /** * Retrieve optional attribute of the channel * * @param channel the channel * @param key the key of the attribute * @param <T> the type of the attribute value * @return optional attribute */ public static <T> Optional<T> getAttribute(Channel channel, AttributeKey<T> key) { return Optional.ofNullable(channel.attr(key)) .map(Attribute::get); } }
1,438
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2MultiplexedChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import static java.util.stream.Collectors.toList; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_CONNECTION; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_INITIAL_WINDOW_SIZE; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http2.Http2Connection; import io.netty.handler.codec.http2.Http2Exception; import io.netty.handler.codec.http2.Http2LocalFlowController; import io.netty.handler.codec.http2.Http2Stream; import io.netty.handler.codec.http2.Http2StreamChannelBootstrap; import io.netty.util.AttributeKey; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.PromiseCombiner; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.Validate; /** * {@link ChannelPool} implementation that handles multiplexed streams. Child channels are created * for each HTTP/2 stream using {@link Http2StreamChannelBootstrap} with the parent channel being * the actual socket channel. This implementation assumes that all connections have the same setting * for MAX_CONCURRENT_STREAMS. Concurrent requests are load balanced across all available connections, * when the max concurrency for a connection is reached then a new connection will be opened. * * <p> * <b>Note:</b> This enforces no max concurrency. Relies on being wrapped with a {@link BetterFixedChannelPool} * to enforce max concurrency which gives a bunch of other good features like timeouts, max pending acquires, etc. * </p> */ @SdkInternalApi public class Http2MultiplexedChannelPool implements SdkChannelPool { private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2MultiplexedChannelPool.class); /** * Reference to the {@link MultiplexedChannelRecord} on a channel. */ private static final AttributeKey<MultiplexedChannelRecord> MULTIPLEXED_CHANNEL = NettyUtils.getOrCreateAttributeKey( "software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool.MULTIPLEXED_CHANNEL"); /** * Whether a parent channel has been released yet. This guards against double-releasing to the delegate connection pool. */ private static final AttributeKey<Boolean> RELEASED = NettyUtils.getOrCreateAttributeKey( "software.amazon.awssdk.http.nio.netty.internal.http2.Http2MultiplexedChannelPool.RELEASED"); private final ChannelPool connectionPool; private final EventLoopGroup eventLoopGroup; private final Set<MultiplexedChannelRecord> connections; private final Duration idleConnectionTimeout; private AtomicBoolean closed = new AtomicBoolean(false); /** * @param connectionPool Connection pool for parent channels (i.e. the socket channel). */ Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Duration idleConnectionTimeout) { this.connectionPool = connectionPool; this.eventLoopGroup = eventLoopGroup; this.connections = ConcurrentHashMap.newKeySet(); this.idleConnectionTimeout = idleConnectionTimeout; } @SdkTestInternalApi Http2MultiplexedChannelPool(ChannelPool connectionPool, EventLoopGroup eventLoopGroup, Set<MultiplexedChannelRecord> connections, Duration idleConnectionTimeout) { this(connectionPool, eventLoopGroup, idleConnectionTimeout); this.connections.addAll(connections); } @Override public Future<Channel> acquire() { return acquire(eventLoopGroup.next().newPromise()); } @Override public Future<Channel> acquire(Promise<Channel> promise) { if (closed.get()) { return promise.setFailure(new IOException("Channel pool is closed!")); } for (MultiplexedChannelRecord multiplexedChannel : connections) { if (acquireStreamOnInitializedConnection(multiplexedChannel, promise)) { return promise; } } // No available streams on existing connections, establish new connection and add it to list acquireStreamOnNewConnection(promise); return promise; } private void acquireStreamOnNewConnection(Promise<Channel> promise) { Future<Channel> newConnectionAcquire = connectionPool.acquire(); newConnectionAcquire.addListener(f -> { if (!newConnectionAcquire.isSuccess()) { promise.setFailure(newConnectionAcquire.cause()); return; } Channel parentChannel = newConnectionAcquire.getNow(); try { parentChannel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(this); // When the protocol future is completed on the new connection, we're ready for new streams to be added to it. parentChannel.attr(PROTOCOL_FUTURE).get() .thenAccept(protocol -> acquireStreamOnFreshConnection(promise, parentChannel, protocol)) .exceptionally(throwable -> failAndCloseParent(promise, parentChannel, throwable)); } catch (Throwable e) { failAndCloseParent(promise, parentChannel, e); } }); } private void acquireStreamOnFreshConnection(Promise<Channel> promise, Channel parentChannel, Protocol protocol) { try { Long maxStreams = parentChannel.attr(MAX_CONCURRENT_STREAMS).get(); Validate.isTrue(protocol == Protocol.HTTP2, "Protocol negotiated on connection (%s) was expected to be HTTP/2, but it " + "was %s.", parentChannel, Protocol.HTTP1_1); Validate.isTrue(maxStreams != null, "HTTP/2 was negotiated on the connection (%s), but the maximum number of " + "streams was not initialized.", parentChannel); Validate.isTrue(maxStreams > 0, "Maximum streams were not positive on channel (%s).", parentChannel); MultiplexedChannelRecord multiplexedChannel = new MultiplexedChannelRecord(parentChannel, maxStreams, idleConnectionTimeout); parentChannel.attr(MULTIPLEXED_CHANNEL).set(multiplexedChannel); Promise<Channel> streamPromise = parentChannel.eventLoop().newPromise(); if (!acquireStreamOnInitializedConnection(multiplexedChannel, streamPromise)) { failAndCloseParent(promise, parentChannel, new IOException("Connection was closed while creating a new stream.")); return; } streamPromise.addListener(f -> { if (!streamPromise.isSuccess()) { promise.setFailure(streamPromise.cause()); return; } Channel stream = streamPromise.getNow(); cacheConnectionForFutureStreams(stream, multiplexedChannel, promise); }); } catch (Throwable e) { failAndCloseParent(promise, parentChannel, e); } } private void cacheConnectionForFutureStreams(Channel stream, MultiplexedChannelRecord multiplexedChannel, Promise<Channel> promise) { Channel parentChannel = stream.parent(); // Before we cache the connection, make sure that exceptions on the connection will remove it from the cache. parentChannel.pipeline().addLast(ReleaseOnExceptionHandler.INSTANCE); connections.add(multiplexedChannel); if (closed.get()) { // Whoops, we were closed while we were setting up. Make sure everything here is cleaned up properly. failAndCloseParent(promise, parentChannel, new IOException("Connection pool was closed while creating a new stream.")); return; } promise.setSuccess(stream); } /** * By default, connection window size is a constant value: * connectionWindowSize = 65535 + (configureInitialWindowSize - 65535) * 2. * See https://github.com/netty/netty/blob/5c458c9a98d4d3d0345e58495e017175156d624f/codec-http2/src/main/java/io/netty * /handler/codec/http2/Http2FrameCodec.java#L255 * We should expand connection window so that the window size proportional to the number of concurrent streams within the * connection. * Note that when {@code WINDOW_UPDATE} will be sent depends on the processedWindow in DefaultHttp2LocalFlowController. */ private void tryExpandConnectionWindow(Channel parentChannel) { doInEventLoop(parentChannel.eventLoop(), () -> { Http2Connection http2Connection = parentChannel.attr(HTTP2_CONNECTION).get(); Integer initialWindowSize = parentChannel.attr(HTTP2_INITIAL_WINDOW_SIZE).get(); Validate.notNull(http2Connection, "http2Connection should not be null on channel " + parentChannel); Validate.notNull(http2Connection, "initialWindowSize should not be null on channel " + parentChannel); Http2Stream connectionStream = http2Connection.connectionStream(); log.debug(parentChannel, () -> "Expanding connection window size for " + parentChannel + " by " + initialWindowSize); try { Http2LocalFlowController localFlowController = http2Connection.local().flowController(); localFlowController.incrementWindowSize(connectionStream, initialWindowSize); } catch (Http2Exception e) { log.warn(parentChannel, () -> "Failed to increment windowSize of connection " + parentChannel, e); } }); } private Void failAndCloseParent(Promise<Channel> promise, Channel parentChannel, Throwable exception) { log.debug(parentChannel, () -> "Channel acquiring failed, closing connection " + parentChannel, exception); promise.setFailure(exception); closeAndReleaseParent(parentChannel); return null; } /** * Acquire a stream on a connection that has already been initialized. This will return false if the connection cannot have * any more streams allocated, and true if the stream can be allocated. * * This will NEVER complete the provided future when the return value is false. This will ALWAYS complete the provided * future when the return value is true. */ private boolean acquireStreamOnInitializedConnection(MultiplexedChannelRecord channelRecord, Promise<Channel> promise) { Promise<Channel> acquirePromise = channelRecord.getConnection().eventLoop().newPromise(); if (!channelRecord.acquireStream(acquirePromise)) { return false; } acquirePromise.addListener(f -> { try { if (!acquirePromise.isSuccess()) { promise.setFailure(acquirePromise.cause()); return; } Channel channel = acquirePromise.getNow(); channel.attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).set(this); channel.attr(MULTIPLEXED_CHANNEL).set(channelRecord); promise.setSuccess(channel); tryExpandConnectionWindow(channel.parent()); } catch (Exception e) { promise.setFailure(e); } }); return true; } @Override public Future<Void> release(Channel childChannel) { return release(childChannel, childChannel.eventLoop().newPromise()); } @Override public Future<Void> release(Channel childChannel, Promise<Void> promise) { if (childChannel.parent() == null) { // This isn't a child channel. Oddly enough, this is "expected" and is handled properly by the // BetterFixedChannelPool AS LONG AS we return an IllegalArgumentException via the promise. closeAndReleaseParent(childChannel); return promise.setFailure(new IllegalArgumentException("Channel (" + childChannel + ") is not a child channel.")); } Channel parentChannel = childChannel.parent(); MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); if (multiplexedChannel == null) { // This is a child channel, but there is no attached multiplexed channel, which there should be if it was from // this pool. Close it and log an error. Exception exception = new IOException("Channel (" + childChannel + ") is not associated with any channel records. " + "It will be closed, but cannot be released within this pool."); log.error(childChannel, exception::getMessage); childChannel.close(); return promise.setFailure(exception); } multiplexedChannel.closeAndReleaseChild(childChannel); if (multiplexedChannel.canBeClosedAndReleased()) { // We just closed the last stream in a connection that has reached the end of its life. return closeAndReleaseParent(parentChannel, null, promise); } return promise.setSuccess(null); } private Future<Void> closeAndReleaseParent(Channel parentChannel) { return closeAndReleaseParent(parentChannel, null, parentChannel.eventLoop().newPromise()); } private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause) { return closeAndReleaseParent(parentChannel, cause, parentChannel.eventLoop().newPromise()); } private Future<Void> closeAndReleaseParent(Channel parentChannel, Throwable cause, Promise<Void> resultPromise) { if (parentChannel.parent() != null) { // This isn't a parent channel. Notify it that something is wrong. Exception exception = new IOException("Channel (" + parentChannel + ") is not a parent channel. It will be closed, " + "but cannot be released within this pool."); log.error(parentChannel, exception::getMessage); parentChannel.close(); return resultPromise.setFailure(exception); } MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); // We may not have a multiplexed channel if the parent channel hasn't been fully initialized. if (multiplexedChannel != null) { if (cause == null) { multiplexedChannel.closeChildChannels(); } else { multiplexedChannel.closeChildChannels(cause); } connections.remove(multiplexedChannel); } parentChannel.close(); if (parentChannel.attr(RELEASED).getAndSet(Boolean.TRUE) == null) { return connectionPool.release(parentChannel, resultPromise); } return resultPromise.setSuccess(null); } void handleGoAway(Channel parentChannel, int lastStreamId, GoAwayException exception) { log.debug(parentChannel, () -> "Received GOAWAY on " + parentChannel + " with lastStreamId of " + lastStreamId); try { MultiplexedChannelRecord multiplexedChannel = parentChannel.attr(MULTIPLEXED_CHANNEL).get(); if (multiplexedChannel != null) { multiplexedChannel.handleGoAway(lastStreamId, exception); } else { // If we don't have a multiplexed channel, the parent channel hasn't been fully initialized. Close it now. closeAndReleaseParent(parentChannel, exception); } } catch (Exception e) { log.error(parentChannel, () -> "Failed to handle GOAWAY frame on channel " + parentChannel, e); } } @Override public void close() { if (closed.compareAndSet(false, true)) { Future<?> closeCompleteFuture = doClose(); try { if (!closeCompleteFuture.await(10, TimeUnit.SECONDS)) { throw new RuntimeException("Event loop didn't close after 10 seconds."); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } Throwable exception = closeCompleteFuture.cause(); if (exception != null) { throw new RuntimeException("Failed to close channel pool.", exception); } } } private Future<?> doClose() { EventLoop closeEventLoop = eventLoopGroup.next(); Promise<?> closeFinishedPromise = closeEventLoop.newPromise(); doInEventLoop(closeEventLoop, () -> { Promise<Void> releaseAllChannelsPromise = closeEventLoop.newPromise(); PromiseCombiner promiseCombiner = new PromiseCombiner(closeEventLoop); // Create a copy of the connections to remove while we close them, in case closing updates the original list. List<MultiplexedChannelRecord> channelsToRemove = new ArrayList<>(connections); for (MultiplexedChannelRecord channel : channelsToRemove) { promiseCombiner.add(closeAndReleaseParent(channel.getConnection())); } promiseCombiner.finish(releaseAllChannelsPromise); releaseAllChannelsPromise.addListener(f -> { connectionPool.close(); closeFinishedPromise.setSuccess(null); }); }); return closeFinishedPromise; } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> result = new CompletableFuture<>(); CompletableFuture<MultiplexedChannelRecord.Metrics> summedMetrics = new CompletableFuture<>(); List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics = connections.stream() .map(MultiplexedChannelRecord::getMetrics) .collect(toList()); accumulateMetrics(summedMetrics, channelMetrics); summedMetrics.whenComplete((m, t) -> { if (t != null) { result.completeExceptionally(t); } else { try { metrics.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, Math.toIntExact(m.getAvailableStreams())); result.complete(null); } catch (Exception e) { result.completeExceptionally(e); } } }); return result; } private void accumulateMetrics(CompletableFuture<MultiplexedChannelRecord.Metrics> result, List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics) { accumulateMetrics(result, channelMetrics, new MultiplexedChannelRecord.Metrics(), 0); } private void accumulateMetrics(CompletableFuture<MultiplexedChannelRecord.Metrics> result, List<CompletableFuture<MultiplexedChannelRecord.Metrics>> channelMetrics, MultiplexedChannelRecord.Metrics resultAccumulator, int index) { if (index >= channelMetrics.size()) { result.complete(resultAccumulator); return; } channelMetrics.get(index).whenComplete((m, t) -> { if (t != null) { result.completeExceptionally(t); } else { resultAccumulator.add(m); accumulateMetrics(result, channelMetrics, resultAccumulator, index + 1); } }); } @Sharable private static final class ReleaseOnExceptionHandler extends ChannelDuplexHandler { private static final ReleaseOnExceptionHandler INSTANCE = new ReleaseOnExceptionHandler(); @Override public void channelInactive(ChannelHandlerContext ctx) { closeAndReleaseParent(ctx, new ClosedChannelException()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof Http2ConnectionTerminatingException) { closeConnectionToNewRequests(ctx, cause); } else { closeAndReleaseParent(ctx, cause); } } void closeConnectionToNewRequests(ChannelHandlerContext ctx, Throwable cause) { MultiplexedChannelRecord multiplexedChannel = ctx.channel().attr(MULTIPLEXED_CHANNEL).get(); if (multiplexedChannel != null) { multiplexedChannel.closeToNewStreams(); } else { closeAndReleaseParent(ctx, cause); } } private void closeAndReleaseParent(ChannelHandlerContext ctx, Throwable cause) { Http2MultiplexedChannelPool pool = ctx.channel().attr(HTTP2_MULTIPLEXED_CHANNEL_POOL).get(); pool.closeAndReleaseParent(ctx.channel(), cause); } } }
1,439
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/PingFailedException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class PingFailedException extends IOException { PingFailedException(String msg) { super(msg); } PingFailedException(String message, Throwable cause) { super(message, cause); } }
1,440
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/GoAwayException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Exception thrown when a GOAWAY frame is sent by the service. */ @SdkInternalApi public class GoAwayException extends IOException { private final String message; GoAwayException(long errorCode, String debugData) { this.message = String.format("GOAWAY received from service, requesting this stream be closed. " + "Error Code = %d, Debug Data = %s", errorCode, debugData); } @Override public String getMessage() { return message; } }
1,441
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ResetSendingSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2Error; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.async.DelegatingSubscription; /** * Wrapper around a {@link Subscription} to send a RST_STREAM frame on cancel. */ @SdkInternalApi public class Http2ResetSendingSubscription extends DelegatingSubscription { private final ChannelHandlerContext ctx; public Http2ResetSendingSubscription(ChannelHandlerContext ctx, Subscription delegate) { super(delegate); this.ctx = ctx; } @Override public void cancel() { ctx.write(new DefaultHttp2ResetFrame(Http2Error.CANCEL)); super.cancel(); } }
1,442
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/PingTracker.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.util.concurrent.ScheduledFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Tracking the status after sending out the PING frame */ @SdkInternalApi public final class PingTracker { private final Supplier<ScheduledFuture<?>> timerFutureSupplier; private ScheduledFuture<?> pingTimerFuture; PingTracker(Supplier<ScheduledFuture<?>> timerFutureSupplier) { this.timerFutureSupplier = timerFutureSupplier; } public void start() { pingTimerFuture = timerFutureSupplier.get(); } public void cancel() { if (pingTimerFuture != null) { pingTimerFuture.cancel(false); } } }
1,443
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2PingHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import static java.util.concurrent.TimeUnit.MILLISECONDS; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http2.DefaultHttp2PingFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.util.concurrent.ScheduledFuture; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; import software.amazon.awssdk.utils.Validate; /** * Attached to a {@link Channel} to periodically check the health of HTTP2 connections via PING frames. * * If a channel is found to be unhealthy, this will invoke {@link ChannelPipeline#fireExceptionCaught(Throwable)}. */ @SdkInternalApi public class Http2PingHandler extends SimpleChannelInboundHandler<Http2PingFrame> { private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2PingHandler.class); private static final Http2PingFrame DEFAULT_PING_FRAME = new DefaultHttp2PingFrame(0); private final long pingTimeoutMillis; private ScheduledFuture<?> periodicPing; private long lastPingSendTime = 0; private long lastPingAckTime = 0; public Http2PingHandler(int pingTimeoutMillis) { this.pingTimeoutMillis = pingTimeoutMillis; } @Override public void handlerAdded(ChannelHandlerContext ctx) { CompletableFuture<Protocol> protocolFuture = ctx.channel().attr(ChannelAttributeKey.PROTOCOL_FUTURE).get(); Validate.validState(protocolFuture != null, "Protocol future must be initialized before handler is added."); protocolFuture.thenAccept(p -> start(p, ctx)); } private void start(Protocol protocol, ChannelHandlerContext ctx) { if (protocol == Protocol.HTTP2 && periodicPing == null) { periodicPing = ctx.channel() .eventLoop() .scheduleAtFixedRate(() -> doPeriodicPing(ctx.channel()), 0, pingTimeoutMillis, MILLISECONDS); } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { stop(); } @Override public void channelInactive(ChannelHandlerContext ctx) { stop(); ctx.fireChannelInactive(); } @Override protected void channelRead0(ChannelHandlerContext ctx, Http2PingFrame frame) { if (frame.ack()) { log.debug(ctx.channel(), () -> "Received PING ACK from channel " + ctx.channel()); lastPingAckTime = System.currentTimeMillis(); } else { ctx.fireChannelRead(frame); } } private void doPeriodicPing(Channel channel) { if (lastPingAckTime <= lastPingSendTime - pingTimeoutMillis) { long timeSinceLastPingSend = System.currentTimeMillis() - lastPingSendTime; channelIsUnhealthy(channel, new PingFailedException("Server did not respond to PING after " + timeSinceLastPingSend + "ms (limit: " + pingTimeoutMillis + "ms)")); } else { sendPing(channel); } } private void sendPing(Channel channel) { channel.writeAndFlush(DEFAULT_PING_FRAME).addListener(res -> { if (!res.isSuccess()) { log.debug(channel, () -> "Failed to write and flush PING frame to connection", res.cause()); channelIsUnhealthy(channel, new PingFailedException("Failed to send PING to the service", res.cause())); } else { lastPingSendTime = System.currentTimeMillis(); } }); } private void channelIsUnhealthy(Channel channel, PingFailedException exception) { stop(); channel.pipeline().fireExceptionCaught(exception); } private void stop() { if (periodicPing != null) { periodicPing.cancel(false); periodicPing = null; } } }
1,444
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2StreamExceptionHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.TimeoutException; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Exception Handler for errors on the Http2 streams. */ @ChannelHandler.Sharable @SdkInternalApi public final class Http2StreamExceptionHandler extends ChannelInboundHandlerAdapter { private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2StreamExceptionHandler.class); private static final Http2StreamExceptionHandler INSTANCE = new Http2StreamExceptionHandler(); private Http2StreamExceptionHandler() { } public static Http2StreamExceptionHandler create() { return INSTANCE; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (isIoError(cause) && ctx.channel().parent() != null) { Channel parent = ctx.channel().parent(); log.debug(parent, () -> "An I/O error occurred on an Http2 stream, notifying the connection channel " + parent); parent.pipeline().fireExceptionCaught(new Http2ConnectionTerminatingException("An I/O error occurred on an " + "associated Http2 " + "stream " + ctx.channel())); } ctx.fireExceptionCaught(cause); } private boolean isIoError(Throwable cause) { return cause instanceof TimeoutException || cause instanceof IOException; } }
1,445
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/MultiplexedChannelRecord.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.warnIfNotInEventLoop; import io.netty.channel.Channel; import io.netty.channel.ChannelId; import io.netty.channel.ChannelOutboundInvoker; import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.codec.http2.Http2StreamChannelBootstrap; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import io.netty.util.concurrent.ScheduledFuture; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.http.nio.netty.internal.ChannelDiagnostics; import software.amazon.awssdk.http.nio.netty.internal.UnusedChannelExceptionHandler; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Contains a {@link Future} for the actual socket channel and tracks available * streams based on the MAX_CONCURRENT_STREAMS setting for the connection. */ @SdkInternalApi public class MultiplexedChannelRecord { private static final NettyClientLogger log = NettyClientLogger.getLogger(MultiplexedChannelRecord.class); private final Channel connection; private final long maxConcurrencyPerConnection; private final Long allowedIdleConnectionTimeMillis; private final AtomicLong availableChildChannels; private volatile long lastReserveAttemptTimeMillis; // Only read or write in the connection.eventLoop() private final Map<ChannelId, Http2StreamChannel> childChannels = new HashMap<>(); private ScheduledFuture<?> closeIfIdleTask; // Only write in the connection.eventLoop() private volatile RecordState state = RecordState.OPEN; private volatile int lastStreamId; MultiplexedChannelRecord(Channel connection, long maxConcurrencyPerConnection, Duration allowedIdleConnectionTime) { this.connection = connection; this.maxConcurrencyPerConnection = maxConcurrencyPerConnection; this.availableChildChannels = new AtomicLong(maxConcurrencyPerConnection); this.allowedIdleConnectionTimeMillis = allowedIdleConnectionTime == null ? null : allowedIdleConnectionTime.toMillis(); } boolean acquireStream(Promise<Channel> promise) { if (claimStream()) { releaseClaimOnFailure(promise); acquireClaimedStream(promise); return true; } return false; } void acquireClaimedStream(Promise<Channel> promise) { doInEventLoop(connection.eventLoop(), () -> { if (state != RecordState.OPEN) { String message; // GOAWAY if (state == RecordState.CLOSED_TO_NEW) { message = String.format("Connection %s received GOAWAY with Last Stream ID %d. Unable to open new " + "streams on this connection.", connection, lastStreamId); } else { message = String.format("Connection %s was closed while acquiring new stream.", connection); } log.warn(connection, () -> message); promise.setFailure(new IOException(message)); return; } Future<Http2StreamChannel> streamFuture = new Http2StreamChannelBootstrap(connection).open(); streamFuture.addListener((GenericFutureListener<Future<Http2StreamChannel>>) future -> { warnIfNotInEventLoop(connection.eventLoop()); if (!future.isSuccess()) { promise.setFailure(future.cause()); return; } Http2StreamChannel channel = future.getNow(); channel.pipeline().addLast(UnusedChannelExceptionHandler.getInstance()); channel.attr(ChannelAttributeKey.HTTP2_FRAME_STREAM).set(channel.stream()); channel.attr(ChannelAttributeKey.CHANNEL_DIAGNOSTICS).set(new ChannelDiagnostics(channel)); childChannels.put(channel.id(), channel); promise.setSuccess(channel); if (closeIfIdleTask == null && allowedIdleConnectionTimeMillis != null) { enableCloseIfIdleTask(); } }); }, promise); } private void enableCloseIfIdleTask() { warnIfNotInEventLoop(connection.eventLoop()); // Don't poll more frequently than 1 second. Being overly-conservative is okay. Blowing up our CPU is not. long taskFrequencyMillis = Math.max(allowedIdleConnectionTimeMillis, 1_000); closeIfIdleTask = connection.eventLoop().scheduleAtFixedRate(this::closeIfIdle, taskFrequencyMillis, taskFrequencyMillis, TimeUnit.MILLISECONDS); connection.closeFuture().addListener(f -> closeIfIdleTask.cancel(false)); } private void releaseClaimOnFailure(Promise<Channel> promise) { try { promise.addListener(f -> { if (!promise.isSuccess()) { releaseClaim(); } }); } catch (Throwable e) { releaseClaim(); throw e; } } private void releaseClaim() { if (availableChildChannels.incrementAndGet() > maxConcurrencyPerConnection) { assert false; log.warn(connection, () -> "Child channel count was caught attempting to be increased over max concurrency. " + "Please report this issue to the AWS SDK for Java team."); availableChildChannels.decrementAndGet(); } } /** * Handle a {@link Http2GoAwayFrame} on this connection, preventing new streams from being created on it, and closing any * streams newer than the last-stream-id on the go-away frame. */ void handleGoAway(int lastStreamId, GoAwayException exception) { doInEventLoop(connection.eventLoop(), () -> { this.lastStreamId = lastStreamId; if (state == RecordState.CLOSED) { return; } if (state == RecordState.OPEN) { state = RecordState.CLOSED_TO_NEW; } // Create a copy of the children to close, because fireExceptionCaught may remove from the childChannels. List<Http2StreamChannel> childrenToClose = new ArrayList<>(childChannels.values()); childrenToClose.stream() .filter(cc -> cc.stream().id() > lastStreamId) .forEach(cc -> cc.pipeline().fireExceptionCaught(exception)); }); } /** * Prevent new streams from being acquired from the existing connection. */ void closeToNewStreams() { doInEventLoop(connection.eventLoop(), () -> { if (state == RecordState.OPEN) { state = RecordState.CLOSED_TO_NEW; } }); } /** * Close all registered child channels, and prohibit new streams from being created on this connection. */ void closeChildChannels() { closeAndExecuteOnChildChannels(ChannelOutboundInvoker::close); } /** * Delivers the exception to all registered child channels, and prohibits new streams being created on this connection. */ void closeChildChannels(Throwable t) { closeAndExecuteOnChildChannels(ch -> ch.pipeline().fireExceptionCaught(decorateConnectionException(t))); } private Throwable decorateConnectionException(Throwable t) { String message = String.format("An error occurred on the connection: %s, [channel: %s]. All streams will be closed", t, connection.id()); if (t instanceof IOException) { return new IOException(message, t); } return new Throwable(message, t); } private void closeAndExecuteOnChildChannels(Consumer<Channel> childChannelConsumer) { doInEventLoop(connection.eventLoop(), () -> { if (state == RecordState.CLOSED) { return; } state = RecordState.CLOSED; // Create a copy of the children, because they may be modified by the consumer. List<Http2StreamChannel> childrenToClose = new ArrayList<>(childChannels.values()); for (Channel childChannel : childrenToClose) { childChannelConsumer.accept(childChannel); } }); } void closeAndReleaseChild(Channel childChannel) { childChannel.close(); doInEventLoop(connection.eventLoop(), () -> { childChannels.remove(childChannel.id()); releaseClaim(); }); } private void closeIfIdle() { warnIfNotInEventLoop(connection.eventLoop()); // Don't close if we have child channels. if (!childChannels.isEmpty()) { return; } // Don't close if there have been any reserves attempted since the idle connection time. long nonVolatileLastReserveAttemptTimeMillis = lastReserveAttemptTimeMillis; if (nonVolatileLastReserveAttemptTimeMillis > System.currentTimeMillis() - allowedIdleConnectionTimeMillis) { return; } // Cut off new streams from being acquired from this connection by setting the number of available channels to 0. // This write may fail if a reservation has happened since we checked the lastReserveAttemptTime. if (!availableChildChannels.compareAndSet(maxConcurrencyPerConnection, 0)) { return; } // If we've been closed, no need to shut down. if (state != RecordState.OPEN) { return; } log.debug(connection, () -> "Connection " + connection + " has been idle for " + (System.currentTimeMillis() - nonVolatileLastReserveAttemptTimeMillis) + "ms and will be shut down."); // Mark ourselves as closed state = RecordState.CLOSED; // Start the shutdown process by closing the connection (which should be noticed by the connection pool) connection.close(); } public Channel getConnection() { return connection; } private boolean claimStream() { lastReserveAttemptTimeMillis = System.currentTimeMillis(); for (int attempt = 0; attempt < 5; ++attempt) { if (state != RecordState.OPEN) { return false; } long currentlyAvailable = availableChildChannels.get(); if (currentlyAvailable <= 0) { return false; } if (availableChildChannels.compareAndSet(currentlyAvailable, currentlyAvailable - 1)) { return true; } } return false; } boolean canBeClosedAndReleased() { return state != RecordState.OPEN && availableChildChannels.get() == maxConcurrencyPerConnection; } CompletableFuture<Metrics> getMetrics() { CompletableFuture<Metrics> result = new CompletableFuture<>(); doInEventLoop(connection.eventLoop(), () -> { int streamCount = childChannels.size(); result.complete(new Metrics().setAvailableStreams(maxConcurrencyPerConnection - streamCount)); }); return result; } private enum RecordState { /** * The connection is open and new streams may be acquired from it, if they are available. */ OPEN, /** * The connection is open, but new streams may not be acquired from it. This occurs when a connection is being * shut down (e.g. after it has received a GOAWAY frame), but all streams haven't been closed yet. */ CLOSED_TO_NEW, /** * The connection is closed and new streams may not be acquired from it. */ CLOSED } public static class Metrics { private long availableStreams = 0; public long getAvailableStreams() { return availableStreams; } public Metrics setAvailableStreams(long availableStreams) { this.availableStreams = availableStreams; return this; } public void add(Metrics rhs) { this.availableStreams += rhs.availableStreams; } } }
1,446
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpOrHttp2ChannelPool.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.doInEventLoop; import static software.amazon.awssdk.http.nio.netty.internal.utils.NettyUtils.runOrPropagate; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import java.time.Duration; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.nio.netty.internal.IdleConnectionCountingChannelPool; import software.amazon.awssdk.http.nio.netty.internal.NettyConfiguration; import software.amazon.awssdk.http.nio.netty.internal.SdkChannelPool; import software.amazon.awssdk.http.nio.netty.internal.utils.BetterFixedChannelPool; import software.amazon.awssdk.metrics.MetricCollector; /** * Channel pool that establishes an initial connection to determine protocol. Delegates * to appropriate channel pool implementation depending on the protocol. This assumes that * all connections will be negotiated with the same protocol. */ @SdkInternalApi public class HttpOrHttp2ChannelPool implements SdkChannelPool { private final ChannelPool delegatePool; private final int maxConcurrency; private final EventLoopGroup eventLoopGroup; private final EventLoop eventLoop; private final NettyConfiguration configuration; private boolean protocolImplPromiseInitializationStarted = false; private Promise<ChannelPool> protocolImplPromise; private BetterFixedChannelPool protocolImpl; private boolean closed; public HttpOrHttp2ChannelPool(ChannelPool delegatePool, EventLoopGroup group, int maxConcurrency, NettyConfiguration configuration) { this.delegatePool = delegatePool; this.maxConcurrency = maxConcurrency; this.eventLoopGroup = group; this.eventLoop = group.next(); this.configuration = configuration; this.protocolImplPromise = eventLoop.newPromise(); } @Override public Future<Channel> acquire() { return acquire(eventLoop.newPromise()); } @Override public Future<Channel> acquire(Promise<Channel> promise) { doInEventLoop(eventLoop, () -> acquire0(promise), promise); return promise; } private void acquire0(Promise<Channel> promise) { if (closed) { promise.setFailure(new IllegalStateException("Channel pool is closed!")); return; } if (protocolImpl != null) { protocolImpl.acquire(promise); return; } if (!protocolImplPromiseInitializationStarted) { initializeProtocol(); } protocolImplPromise.addListener((GenericFutureListener<Future<ChannelPool>>) future -> { if (future.isSuccess()) { future.getNow().acquire(promise); } else { // Couldn't negotiate protocol, fail this acquire. promise.setFailure(future.cause()); } }); } /** * Establishes a single connection to initialize the protocol and choose the appropriate {@link ChannelPool} implementation * for {@link #protocolImpl}. */ private void initializeProtocol() { protocolImplPromiseInitializationStarted = true; delegatePool.acquire().addListener((GenericFutureListener<Future<Channel>>) future -> { if (future.isSuccess()) { Channel newChannel = future.getNow(); newChannel.attr(PROTOCOL_FUTURE).get().whenComplete((protocol, e) -> { if (e != null) { failProtocolImplPromise(e); } else { completeProtocolConfiguration(newChannel, protocol); } }); } else { failProtocolImplPromise(future.cause()); } }); } /** * Fail the current protocolImplPromise and null it out so the next acquire will attempt to re-initialize it. * * @param e Cause of failure. */ private void failProtocolImplPromise(Throwable e) { doInEventLoop(eventLoop, () -> { protocolImplPromise.setFailure(e); protocolImplPromise = eventLoop.newPromise(); protocolImplPromiseInitializationStarted = false; }); } private void completeProtocolConfiguration(Channel newChannel, Protocol protocol) { doInEventLoop(eventLoop, () -> { if (closed) { closeAndRelease(newChannel, new IllegalStateException("Pool closed")); } else { try { configureProtocol(newChannel, protocol); } catch (Throwable e) { closeAndRelease(newChannel, e); } } }); } private void closeAndRelease(Channel newChannel, Throwable e) { newChannel.close(); delegatePool.release(newChannel); protocolImplPromise.setFailure(e); } private void configureProtocol(Channel newChannel, Protocol protocol) { if (Protocol.HTTP1_1 == protocol) { // For HTTP/1.1 we use a traditional channel pool without multiplexing SdkChannelPool idleConnectionMetricChannelPool = new IdleConnectionCountingChannelPool(eventLoop, delegatePool); protocolImpl = BetterFixedChannelPool.builder() .channelPool(idleConnectionMetricChannelPool) .executor(eventLoop) .acquireTimeoutAction(BetterFixedChannelPool.AcquireTimeoutAction.FAIL) .acquireTimeoutMillis(configuration.connectionAcquireTimeoutMillis()) .maxConnections(maxConcurrency) .maxPendingAcquires(configuration.maxPendingConnectionAcquires()) .build(); } else { Duration idleConnectionTimeout = configuration.reapIdleConnections() ? Duration.ofMillis(configuration.idleTimeoutMillis()) : null; SdkChannelPool h2Pool = new Http2MultiplexedChannelPool(delegatePool, eventLoopGroup, idleConnectionTimeout); protocolImpl = BetterFixedChannelPool.builder() .channelPool(h2Pool) .executor(eventLoop) .acquireTimeoutAction(BetterFixedChannelPool.AcquireTimeoutAction.FAIL) .acquireTimeoutMillis(configuration.connectionAcquireTimeoutMillis()) .maxConnections(maxConcurrency) .maxPendingAcquires(configuration.maxPendingConnectionAcquires()) .build(); } // Give the channel back so it can be acquired again by protocolImpl // Await the release completion to ensure we do not unnecessarily acquire a second channel delegatePool.release(newChannel).addListener(runOrPropagate(protocolImplPromise, () -> { protocolImplPromise.trySuccess(protocolImpl); })); } @Override public Future<Void> release(Channel channel) { return release(channel, eventLoop.newPromise()); } @Override public Future<Void> release(Channel channel, Promise<Void> promise) { doInEventLoop(eventLoop, () -> release0(channel, promise), promise); return promise; } private void release0(Channel channel, Promise<Void> promise) { if (protocolImpl == null) { // If protocolImpl is null that means the first connection failed to establish. Release it back to the // underlying connection pool. delegatePool.release(channel, promise); } else { protocolImpl.release(channel, promise); } } @Override public void close() { doInEventLoop(eventLoop, this::close0); } private void close0() { if (closed) { return; } closed = true; if (protocolImpl != null) { protocolImpl.close(); } else if (protocolImplPromiseInitializationStarted) { protocolImplPromise.addListener((Future<ChannelPool> f) -> { if (f.isSuccess()) { f.getNow().close(); } else { delegatePool.close(); } }); } else { delegatePool.close(); } } @Override public CompletableFuture<Void> collectChannelPoolMetrics(MetricCollector metrics) { CompletableFuture<Void> result = new CompletableFuture<>(); protocolImplPromise.addListener(f -> { if (!f.isSuccess()) { result.completeExceptionally(f.cause()); } else { protocolImpl.collectChannelPoolMetrics(metrics).whenComplete((m, t) -> { if (t != null) { result.completeExceptionally(t); } else { result.complete(m); } }); } }); return result; } }
1,447
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ConnectionTerminatingException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Exception indicating a connection is terminating */ @SdkInternalApi final class Http2ConnectionTerminatingException extends RuntimeException { Http2ConnectionTerminatingException(String message) { super(message); } }
1,448
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/FlushOnReadHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This is an HTTP/2 related workaround for an issue where a WINDOW_UPDATE is * queued but not written to the socket, causing a read() on the channel to * hang if the remote endpoint thinks our inbound window is 0. */ @SdkInternalApi @ChannelHandler.Sharable public final class FlushOnReadHandler extends ChannelOutboundHandlerAdapter { private static final FlushOnReadHandler INSTANCE = new FlushOnReadHandler(); private FlushOnReadHandler() { } @Override public void read(ChannelHandlerContext ctx) { //Note: order is important, we need to fire the read() event first // since it's what triggers the WINDOW_UPDATE frame write ctx.read(); ctx.channel().parent().flush(); } public static FlushOnReadHandler getInstance() { return INSTANCE; } }
1,449
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2ToHttpInboundAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http2.Http2DataFrame; import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2Exception; import io.netty.handler.codec.http2.Http2Frame; import io.netty.handler.codec.http2.Http2HeadersFrame; import io.netty.handler.codec.http2.Http2ResetFrame; import io.netty.handler.codec.http2.HttpConversionUtil; import java.io.IOException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Converts {@link Http2Frame}s to {@link HttpObject}s. Ignores the majority of {@link Http2Frame}s like PING * or SETTINGS. */ @SdkInternalApi public class Http2ToHttpInboundAdapter extends SimpleChannelInboundHandler<Http2Frame> { private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2ToHttpInboundAdapter.class); @Override protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) throws Exception { if (frame instanceof Http2DataFrame) { onDataRead((Http2DataFrame) frame, ctx); } else if (frame instanceof Http2HeadersFrame) { onHeadersRead((Http2HeadersFrame) frame, ctx); ctx.channel().read(); } else if (frame instanceof Http2ResetFrame) { onRstStreamRead((Http2ResetFrame) frame, ctx); } else { // TODO this is related to the inbound window update bug. Revisit ctx.channel().parent().read(); } } private void onHeadersRead(Http2HeadersFrame headersFrame, ChannelHandlerContext ctx) throws Http2Exception { HttpResponse httpResponse = HttpConversionUtil.toHttpResponse(headersFrame.stream().id(), headersFrame.headers(), true); ctx.fireChannelRead(httpResponse); if (HttpStatusFamily.of(httpResponse.status().code()) == HttpStatusFamily.SERVER_ERROR) { fireConnectionExceptionForServerError(ctx); } } private void fireConnectionExceptionForServerError(ChannelHandlerContext ctx) { if (ctx.channel().parent() != null) { Channel parent = ctx.channel().parent(); log.debug(ctx.channel(), () -> "A 5xx server error occurred on an Http2 stream, notifying the connection channel " + ctx.channel()); parent.pipeline().fireExceptionCaught(new Http2ConnectionTerminatingException("A 5xx server error occurred on an " + "Http2 stream " + ctx.channel())); } } private void onDataRead(Http2DataFrame dataFrame, ChannelHandlerContext ctx) throws Http2Exception { ByteBuf data = dataFrame.content(); data.retain(); if (!dataFrame.isEndStream()) { ctx.fireChannelRead(new DefaultHttpContent(data)); } else { ctx.fireChannelRead(new DefaultLastHttpContent(data)); } } private void onRstStreamRead(Http2ResetFrame resetFrame, ChannelHandlerContext ctx) throws Http2Exception { ctx.fireExceptionCaught(new Http2ResetException(resetFrame.errorCode())); } public static final class Http2ResetException extends IOException { Http2ResetException(long errorCode) { super(String.format("Connection reset. Error - %s(%d)", Http2Error.valueOf(errorCode).name(), errorCode)); } } }
1,450
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2GoAwayEventListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.handler.codec.http2.Http2ConnectionAdapter; import io.netty.handler.codec.http2.Http2GoAwayFrame; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * Handles {@link Http2GoAwayFrame}s sent on a connection. This will pass the frame along to the connection's * {@link Http2MultiplexedChannelPool#handleGoAway(Channel, int, GoAwayException)}. */ @SdkInternalApi public final class Http2GoAwayEventListener extends Http2ConnectionAdapter { private static final NettyClientLogger log = NettyClientLogger.getLogger(Http2GoAwayEventListener.class); private final Channel parentChannel; public Http2GoAwayEventListener(Channel parentChannel) { this.parentChannel = parentChannel; } @Override public void onGoAwayReceived(int lastStreamId, long errorCode, ByteBuf debugData) { Http2MultiplexedChannelPool channelPool = parentChannel.attr(ChannelAttributeKey.HTTP2_MULTIPLEXED_CHANNEL_POOL).get(); GoAwayException exception = new GoAwayException(errorCode, debugData.toString(StandardCharsets.UTF_8)); if (channelPool != null) { channelPool.handleGoAway(parentChannel, lastStreamId, exception); } else { log.warn(parentChannel, () -> "GOAWAY received on a connection (" + parentChannel + ") not associated with any " + "multiplexed " + "channel pool."); parentChannel.pipeline().fireExceptionCaught(exception); } } }
1,451
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/HttpToHttp2OutboundAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.handler.codec.http.EmptyHttpHeaders; import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http2.DefaultHttp2DataFrame; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.EmptyHttp2Headers; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2MultiplexCodec; import io.netty.handler.codec.http2.HttpConversionUtil; import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandler; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.EventExecutor; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Translates HTTP/1.1 Netty objects to the corresponding HTTP/2 frame objects. Much of this was lifted from * {@link HttpToHttp2ConnectionHandler} but since that actually encodes to the raw bytes it doesn't play nice with * {@link Http2MultiplexCodec} which expects the frame objects. */ @SdkInternalApi public class HttpToHttp2OutboundAdapter extends ChannelOutboundHandlerAdapter { public HttpToHttp2OutboundAdapter() { } /** * Handles conversion of {@link HttpMessage} and {@link HttpContent} to HTTP/2 frames. */ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) { ctx.write(msg, promise); return; } boolean release = true; SimpleChannelPromiseAggregator promiseAggregator = new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor()); try { boolean endStream = false; if (msg instanceof HttpMessage) { HttpMessage httpMsg = (HttpMessage) msg; // Convert and write the headers. Http2Headers http2Headers = HttpConversionUtil.toHttp2Headers(httpMsg, false); endStream = msg instanceof FullHttpMessage && !((FullHttpMessage) msg).content().isReadable(); ctx.write(new DefaultHttp2HeadersFrame(http2Headers), promiseAggregator.newPromise()); } if (!endStream && msg instanceof HttpContent) { boolean isLastContent = false; HttpHeaders trailers = EmptyHttpHeaders.INSTANCE; Http2Headers http2Trailers = EmptyHttp2Headers.INSTANCE; if (msg instanceof LastHttpContent) { isLastContent = true; // Convert any trailing headers. LastHttpContent lastContent = (LastHttpContent) msg; trailers = lastContent.trailingHeaders(); http2Trailers = HttpConversionUtil.toHttp2Headers(trailers, false); } // Write the data ByteBuf content = ((HttpContent) msg).content(); endStream = isLastContent && trailers.isEmpty(); release = false; ctx.write(new DefaultHttp2DataFrame(content, endStream), promiseAggregator.newPromise()); if (!trailers.isEmpty()) { // Write trailing headers. ctx.write(new DefaultHttp2HeadersFrame(http2Trailers, true), promiseAggregator.newPromise()); } ctx.flush(); } } catch (Throwable t) { promiseAggregator.setFailure(t); } finally { if (release) { ReferenceCountUtil.release(msg); } promiseAggregator.doneAllocatingPromises(); } } /** * Provides the ability to associate the outcome of multiple {@link ChannelPromise} * objects into a single {@link ChannelPromise} object. */ static final class SimpleChannelPromiseAggregator extends DefaultChannelPromise { private final ChannelPromise promise; private int expectedCount; private int doneCount; private Throwable lastFailure; private boolean doneAllocating; SimpleChannelPromiseAggregator(ChannelPromise promise, Channel c, EventExecutor e) { super(c, e); assert promise != null && !promise.isDone(); this.promise = promise; } /** * Allocate a new promise which will be used to aggregate the overall success of this promise aggregator. * * @return A new promise which will be aggregated. * {@code null} if {@link #doneAllocatingPromises()} was previously called. */ public ChannelPromise newPromise() { assert !doneAllocating : "Done allocating. No more promises can be allocated."; ++expectedCount; return this; } /** * Signify that no more {@link #newPromise()} allocations will be made. * The aggregation can not be successful until this method is called. * * @return The promise that is the aggregation of all promises allocated with {@link #newPromise()}. */ public ChannelPromise doneAllocatingPromises() { if (!doneAllocating) { doneAllocating = true; if (doneCount == expectedCount || expectedCount == 0) { return setPromise(); } } return this; } @Override public boolean tryFailure(Throwable cause) { if (allowFailure()) { ++doneCount; lastFailure = cause; if (allPromisesDone()) { return tryPromise(); } // TODO: We break the interface a bit here. // Multiple failure events can be processed without issue because this is an aggregation. return true; } return false; } /** * Fail this object if it has not already been failed. * <p> * This method will NOT throw an {@link IllegalStateException} if called multiple times * because that may be expected. */ @Override public ChannelPromise setFailure(Throwable cause) { if (allowFailure()) { ++doneCount; lastFailure = cause; if (allPromisesDone()) { return setPromise(); } } return this; } @Override public ChannelPromise setSuccess(Void result) { if (awaitingPromises()) { ++doneCount; if (allPromisesDone()) { setPromise(); } } return this; } @Override public boolean trySuccess(Void result) { if (awaitingPromises()) { ++doneCount; if (allPromisesDone()) { return tryPromise(); } // TODO: We break the interface a bit here. // Multiple success events can be processed without issue because this is an aggregation. return true; } return false; } private boolean allowFailure() { return awaitingPromises() || expectedCount == 0; } private boolean awaitingPromises() { return doneCount < expectedCount; } private boolean allPromisesDone() { return doneCount == expectedCount && doneAllocating; } private ChannelPromise setPromise() { if (lastFailure == null) { promise.setSuccess(); return super.setSuccess(null); } else { promise.setFailure(lastFailure); return super.setFailure(lastFailure); } } private boolean tryPromise() { if (lastFailure == null) { promise.trySuccess(); return super.trySuccess(null); } else { promise.tryFailure(lastFailure); return super.tryFailure(lastFailure); } } } }
1,452
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/http2/Http2SettingsFrameHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.http2; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.MAX_CONCURRENT_STREAMS; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.PROTOCOL_FUTURE; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.pool.ChannelPool; import io.netty.handler.codec.http2.Http2SettingsFrame; import java.io.IOException; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.Protocol; /** * Configure channel based on the {@link Http2SettingsFrame} received from server */ @SdkInternalApi public final class Http2SettingsFrameHandler extends SimpleChannelInboundHandler<Http2SettingsFrame> { private Channel channel; private final long clientMaxStreams; private AtomicReference<ChannelPool> channelPoolRef; public Http2SettingsFrameHandler(Channel channel, long clientMaxStreams, AtomicReference<ChannelPool> channelPoolRef) { this.channel = channel; this.clientMaxStreams = clientMaxStreams; this.channelPoolRef = channelPoolRef; } @Override protected void channelRead0(ChannelHandlerContext ctx, Http2SettingsFrame msg) { Long serverMaxStreams = Optional.ofNullable(msg.settings().maxConcurrentStreams()).orElse(Long.MAX_VALUE); channel.attr(MAX_CONCURRENT_STREAMS).set(Math.min(clientMaxStreams, serverMaxStreams)); channel.attr(PROTOCOL_FUTURE).get().complete(Protocol.HTTP2); } @Override public void channelUnregistered(ChannelHandlerContext ctx) { if (!channel.attr(PROTOCOL_FUTURE).get().isDone()) { channelError(new IOException("The channel was closed before the protocol could be determined."), channel, ctx); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { channelError(cause, channel, ctx); } private void channelError(Throwable cause, Channel ch, ChannelHandlerContext ctx) { ch.attr(PROTOCOL_FUTURE).get().completeExceptionally(cause); ctx.fireExceptionCaught(cause); // Channel status may still be active at this point even if it's not so queue up the close so that status is // accurately updated ch.eventLoop().submit(() -> { try { if (ch.isActive()) { ch.close(); } } finally { channelPoolRef.get().release(ch); } }); } }
1,453
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/EmptyHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi class EmptyHttpResponse extends DelegateHttpResponse implements FullHttpResponse { EmptyHttpResponse(HttpResponse response) { super(response); } @Override public FullHttpResponse setStatus(HttpResponseStatus status) { super.setStatus(status); return this; } @Override public FullHttpResponse setProtocolVersion(HttpVersion version) { super.setProtocolVersion(version); return this; } @Override public FullHttpResponse copy() { if (response instanceof FullHttpResponse) { return new EmptyHttpResponse(((FullHttpResponse) response).copy()); } else { DefaultHttpResponse copy = new DefaultHttpResponse(protocolVersion(), status()); copy.headers().set(headers()); return new EmptyHttpResponse(copy); } } @Override public FullHttpResponse retain(int increment) { ReferenceCountUtil.retain(message, increment); return this; } @Override public FullHttpResponse retain() { ReferenceCountUtil.retain(message); return this; } @Override public FullHttpResponse touch() { if (response instanceof FullHttpResponse) { return ((FullHttpResponse) response).touch(); } else { return this; } } @Override public FullHttpResponse touch(Object o) { if (response instanceof FullHttpResponse) { return ((FullHttpResponse) response).touch(o); } else { return this; } } @Override public HttpHeaders trailingHeaders() { return new DefaultHttpHeaders(); } @Override public FullHttpResponse duplicate() { if (response instanceof FullHttpResponse) { return ((FullHttpResponse) response).duplicate(); } else { return this; } } @Override public FullHttpResponse retainedDuplicate() { if (response instanceof FullHttpResponse) { return ((FullHttpResponse) response).retainedDuplicate(); } else { return this; } } @Override public FullHttpResponse replace(ByteBuf byteBuf) { if (response instanceof FullHttpResponse) { return ((FullHttpResponse) response).replace(byteBuf); } else { return this; } } @Override public ByteBuf content() { return Unpooled.EMPTY_BUFFER; } @Override public int refCnt() { if (message instanceof ReferenceCounted) { return ((ReferenceCounted) message).refCnt(); } else { return 1; } } @Override public boolean release() { return ReferenceCountUtil.release(message); } @Override public boolean release(int decrement) { return ReferenceCountUtil.release(message, decrement); } }
1,454
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi class DelegateHttpRequest extends DelegateHttpMessage implements HttpRequest { protected final HttpRequest request; DelegateHttpRequest(HttpRequest request) { super(request); this.request = request; } @Override public HttpRequest setMethod(HttpMethod method) { request.setMethod(method); return this; } @Override public HttpRequest setUri(String uri) { request.setUri(uri); return this; } @Override @Deprecated public HttpMethod getMethod() { return request.method(); } @Override public HttpMethod method() { return request.method(); } @Override @Deprecated public String getUri() { return request.uri(); } @Override public String uri() { return request.uri(); } @Override public HttpRequest setProtocolVersion(HttpVersion version) { super.setProtocolVersion(version); return this; } }
1,455
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HttpStreamsClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.ReferenceCountUtil; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Handler that converts written {@link StreamedHttpRequest} messages into {@link HttpRequest} messages * followed by {@link HttpContent} messages and reads {@link HttpResponse} messages followed by * {@link HttpContent} messages and produces {@link StreamedHttpResponse} messages. * * This allows request and response bodies to be handled using reactive streams. * * There are two types of messages that this handler accepts for writing, {@link StreamedHttpRequest} and * {@link FullHttpRequest}. Writing any other messages may potentially lead to HTTP message mangling. * * There are two types of messages that this handler will send down the chain, {@link StreamedHttpResponse}, * and {@link FullHttpResponse}. If {@link io.netty.channel.ChannelOption#AUTO_READ} is false for the channel, * then any {@link StreamedHttpResponse} messages <em>must</em> be subscribed to consume the body, otherwise * it's possible that no read will be done of the messages. * * As long as messages are returned in the order that they arrive, this handler implicitly supports HTTP * pipelining. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public class HttpStreamsClientHandler extends HttpStreamsHandler<HttpResponse, HttpRequest> { private int inFlight = 0; private int withServer = 0; private ChannelPromise closeOnZeroInFlight = null; private Subscriber<HttpContent> awaiting100Continue; private StreamedHttpMessage awaiting100ContinueMessage; private boolean ignoreResponseBody = false; public HttpStreamsClientHandler() { super(HttpResponse.class, HttpRequest.class); } @Override protected boolean hasBody(HttpResponse response) { if (response.status().code() >= 100 && response.status().code() < 200) { return false; } if (response.status().equals(HttpResponseStatus.NO_CONTENT) || response.status().equals(HttpResponseStatus.NOT_MODIFIED)) { return false; } if (HttpUtil.isTransferEncodingChunked(response)) { return true; } if (HttpUtil.isContentLengthSet(response)) { return HttpUtil.getContentLength(response) > 0; } return true; } @Override public void close(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { if (inFlight == 0) { ctx.close(future); } else { closeOnZeroInFlight = future; } } @Override protected void consumedInMessage(ChannelHandlerContext ctx) { inFlight--; withServer--; if (inFlight == 0 && closeOnZeroInFlight != null) { ctx.close(closeOnZeroInFlight); } } @Override protected void receivedOutMessage(ChannelHandlerContext ctx) { inFlight++; } @Override protected void sentOutMessage(ChannelHandlerContext ctx) { withServer++; } @Override protected HttpResponse createEmptyMessage(HttpResponse response) { return new EmptyHttpResponse(response); } @Override protected HttpResponse createStreamedMessage(HttpResponse response, Publisher<HttpContent> stream) { return new DelegateStreamedHttpResponse(response, stream); } @Override protected void subscribeSubscriberToStream(StreamedHttpMessage msg, Subscriber<HttpContent> subscriber) { if (HttpUtil.is100ContinueExpected(msg)) { awaiting100Continue = subscriber; awaiting100ContinueMessage = msg; } else { super.subscribeSubscriberToStream(msg, subscriber); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse && awaiting100Continue != null && withServer == 0) { HttpResponse response = (HttpResponse) msg; if (response.status().equals(HttpResponseStatus.CONTINUE)) { super.subscribeSubscriberToStream(awaiting100ContinueMessage, awaiting100Continue); awaiting100Continue = null; awaiting100ContinueMessage = null; if (msg instanceof FullHttpResponse) { ReferenceCountUtil.release(msg); } else { ignoreResponseBody = true; } } else { awaiting100ContinueMessage.subscribe(new CancelledSubscriber<HttpContent>()); awaiting100ContinueMessage = null; awaiting100Continue.onSubscribe(new NoOpSubscription()); awaiting100Continue.onComplete(); awaiting100Continue = null; super.channelRead(ctx, msg); } } else if (ignoreResponseBody && msg instanceof HttpContent) { ReferenceCountUtil.release(msg); if (msg instanceof LastHttpContent) { ignoreResponseBody = false; } } else { super.channelRead(ctx, msg); } } private static class NoOpSubscription implements Subscription { @Override public void request(long n) { } @Override public void cancel() { } } }
1,456
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpRequest; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Combines {@link HttpRequest} and {@link StreamedHttpMessage} into one * message. So it represents an http request with a stream of * {@link io.netty.handler.codec.http.HttpContent} messages that can be subscribed to. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public interface StreamedHttpRequest extends HttpRequest, StreamedHttpMessage { }
1,457
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpResponse; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Combines {@link HttpResponse} and {@link StreamedHttpMessage} into one * message. So it represents an http response with a stream of * {@link io.netty.handler.codec.http.HttpContent} messages that can be subscribed to. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public interface StreamedHttpResponse extends HttpResponse, StreamedHttpMessage { }
1,458
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.EventExecutor; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.OrderedWriteChannelHandlerContext; import software.amazon.awssdk.utils.Validate; /** * Subscriber that publishes received messages to the handler pipeline. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public class HandlerSubscriber<T> extends ChannelDuplexHandler implements Subscriber<T> { static final long DEFAULT_LOW_WATERMARK = 4; static final long DEFAULT_HIGH_WATERMARK = 16; private final EventExecutor executor; private final long demandLowWatermark; private final long demandHighWatermark; private final AtomicBoolean hasSubscription = new AtomicBoolean(); private volatile Subscription subscription; private volatile ChannelHandlerContext ctx; private State state = HandlerSubscriber.State.NO_SUBSCRIPTION_OR_CONTEXT; private long outstandingDemand = 0; private ChannelFuture lastWriteFuture; /** * Create a new handler subscriber. * * The supplied executor must be the same event loop as the event loop that this handler is eventually registered * with, if not, an exception will be thrown when the handler is registered. * * @param executor The executor to execute asynchronous events from the publisher on. * @param demandLowWatermark The low watermark for demand. When demand drops below this, more will be requested. * @param demandHighWatermark The high watermark for demand. This is the maximum that will be requested. */ public HandlerSubscriber(EventExecutor executor, long demandLowWatermark, long demandHighWatermark) { this.executor = executor; this.demandLowWatermark = demandLowWatermark; this.demandHighWatermark = demandHighWatermark; } /** * Create a new handler subscriber with the default low and high watermarks. * * The supplied executor must be the same event loop as the event loop that this handler is eventually registered * with, if not, an exception will be thrown when the handler is registered. * * @param executor The executor to execute asynchronous events from the publisher on. * @see #HandlerSubscriber(EventExecutor, long, long) */ public HandlerSubscriber(EventExecutor executor) { this(executor, DEFAULT_LOW_WATERMARK, DEFAULT_HIGH_WATERMARK); } /** * Override for custom error handling. By default, it closes the channel. * * @param error The error to handle. */ protected void error(Throwable error) { doClose(); } /** * Override for custom completion handling. By default, it closes the channel. */ protected void complete() { doClose(); } enum State { NO_SUBSCRIPTION_OR_CONTEXT, NO_SUBSCRIPTION, NO_CONTEXT, INACTIVE, RUNNING, CANCELLED, COMPLETE } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { verifyRegisteredWithRightExecutor(ctx); // Ensure that writes to the context happen consecutively, even if they're performed from within the event loop. // See https://github.com/netty/netty/issues/7783 ctx = OrderedWriteChannelHandlerContext.wrap(ctx); switch (state) { case NO_SUBSCRIPTION_OR_CONTEXT: this.ctx = ctx; // We were in no subscription or context, now we just don't have a subscription. state = HandlerSubscriber.State.NO_SUBSCRIPTION; break; case NO_CONTEXT: this.ctx = ctx; // We were in no context, we're now fully initialised maybeStart(); break; case COMPLETE: // We are complete, close state = HandlerSubscriber.State.COMPLETE; ctx.close(); break; default: throw new IllegalStateException("This handler must only be added to a pipeline once " + state); } } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { verifyRegisteredWithRightExecutor(ctx); ctx.fireChannelRegistered(); } private void verifyRegisteredWithRightExecutor(ChannelHandlerContext ctx) { if (ctx.channel().isRegistered() && !executor.inEventLoop()) { throw new IllegalArgumentException("Channel handler MUST be registered with the same EventExecutor that " + "it is created with."); } } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { maybeRequestMore(); ctx.fireChannelWritabilityChanged(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (state == HandlerSubscriber.State.INACTIVE) { state = HandlerSubscriber.State.RUNNING; maybeRequestMore(); } ctx.fireChannelActive(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { cancel(); ctx.fireChannelInactive(); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { cancel(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cancel(); ctx.fireExceptionCaught(cause); } private void cancel() { switch (state) { case NO_SUBSCRIPTION: state = HandlerSubscriber.State.CANCELLED; break; case RUNNING: case INACTIVE: subscription.cancel(); state = HandlerSubscriber.State.CANCELLED; break; default: // ignore } } @Override public void onSubscribe(final Subscription subscription) { if (subscription == null) { throw new NullPointerException("Null subscription"); } else if (!hasSubscription.compareAndSet(false, true)) { subscription.cancel(); } else { this.subscription = subscription; executor.execute(new Runnable() { @Override public void run() { provideSubscription(); } }); } } private void provideSubscription() { switch (state) { case NO_SUBSCRIPTION_OR_CONTEXT: state = HandlerSubscriber.State.NO_CONTEXT; break; case NO_SUBSCRIPTION: maybeStart(); break; case CANCELLED: subscription.cancel(); break; default: // ignore } } private void maybeStart() { if (ctx.channel().isActive()) { state = HandlerSubscriber.State.RUNNING; maybeRequestMore(); } else { state = HandlerSubscriber.State.INACTIVE; } } @Override public void onNext(T t) { // Publish straight to the context. Validate.notNull(t, "Event must not be null."); lastWriteFuture = ctx.writeAndFlush(t); lastWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { outstandingDemand--; maybeRequestMore(); } }); } @Override public void onError(final Throwable error) { if (error == null) { throw new NullPointerException("Null error published"); } error(error); } @Override public void onComplete() { if (lastWriteFuture == null) { complete(); } else { lastWriteFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { complete(); } }); } } private void doClose() { executor.execute(new Runnable() { @Override public void run() { switch (state) { case NO_SUBSCRIPTION: case INACTIVE: case RUNNING: ctx.close(); state = HandlerSubscriber.State.COMPLETE; break; default: // ignore } } }); } private void maybeRequestMore() { if (outstandingDemand <= demandLowWatermark && ctx.channel().isWritable()) { long toRequest = demandHighWatermark - outstandingDemand; outstandingDemand = demandHighWatermark; subscription.request(toRequest); } } }
1,459
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DefaultStreamedHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import java.util.Objects; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A default streamed HTTP request. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public class DefaultStreamedHttpRequest extends DefaultHttpRequest implements StreamedHttpRequest { private final Publisher<HttpContent> stream; public DefaultStreamedHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri, Publisher<HttpContent> stream) { super(httpVersion, method, uri); this.stream = stream; } public DefaultStreamedHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri, boolean validateHeaders, Publisher<HttpContent> stream) { super(httpVersion, method, uri, validateHeaders); this.stream = stream; } @Override public void subscribe(Subscriber<? super HttpContent> subscriber) { stream.subscribe(subscriber); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } DefaultStreamedHttpRequest that = (DefaultStreamedHttpRequest) o; return Objects.equals(stream, that.stream); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (stream != null ? stream.hashCode() : 0); return result; } }
1,460
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HttpStreamsHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import static software.amazon.awssdk.http.nio.netty.internal.ChannelAttributeKey.STREAMING_COMPLETE_KEY; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.FullHttpMessage; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.LastHttpContent; import io.netty.util.ReferenceCountUtil; import java.util.LinkedList; import java.util.Queue; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.nio.netty.internal.utils.NettyClientLogger; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi abstract class HttpStreamsHandler<InT extends HttpMessage, OutT extends HttpMessage> extends ChannelDuplexHandler { private static final NettyClientLogger logger = NettyClientLogger.getLogger(HttpStreamsHandler.class); private final Queue<Outgoing> outgoing = new LinkedList<>(); private final Class<InT> inClass; private final Class<OutT> outClass; /** * The incoming message that is currently being streamed out to a subscriber. * * This is tracked so that if its subscriber cancels, we can go into a mode where we ignore the rest of the body. * Since subscribers may cancel as many times as they like, including well after they've received all their content, * we need to track what the current message that's being streamed out is so that we can ignore it if it's not * currently being streamed out. */ private InT currentlyStreamedMessage; /** * Ignore the remaining reads for the incoming message. * * This is used in conjunction with currentlyStreamedMessage, as well as in situations where we have received the * full body, but still might be expecting a last http content message. */ private boolean ignoreBodyRead; /** * Whether a LastHttpContent message needs to be written once the incoming publisher completes. * * Since the publisher may itself publish a LastHttpContent message, we need to track this fact, because if it * doesn't, then we need to write one ourselves. */ private boolean sendLastHttpContent; HttpStreamsHandler(Class<InT> inClass, Class<OutT> outClass) { this.inClass = inClass; this.outClass = outClass; } /** * Whether the given incoming message has a body. */ protected abstract boolean hasBody(InT in); /** * Create an empty incoming message. This must be of type FullHttpMessage, and is invoked when we've determined * that an incoming message can't have a body, so we send it on as a FullHttpMessage. */ protected abstract InT createEmptyMessage(InT in); /** * Create a streamed incoming message with the given stream. */ protected abstract InT createStreamedMessage(InT in, Publisher<HttpContent> stream); /** * Invoked when an incoming message is first received. * * Overridden by sub classes for state tracking. */ protected void receivedInMessage(ChannelHandlerContext ctx) { } /** * Invoked when an incoming message is fully consumed. * * Overridden by sub classes for state tracking. */ protected void consumedInMessage(ChannelHandlerContext ctx) { } /** * Invoked when an outgoing message is first received. * * Overridden by sub classes for state tracking. */ protected void receivedOutMessage(ChannelHandlerContext ctx) { } /** * Invoked when an outgoing message is fully sent. * * Overridden by sub classes for state tracking. */ protected void sentOutMessage(ChannelHandlerContext ctx) { } /** * Subscribe the given subscriber to the given streamed message. * * Provided so that the client subclass can intercept this to hold off sending the body of an expect 100 continue * request. */ protected void subscribeSubscriberToStream(StreamedHttpMessage msg, Subscriber<HttpContent> subscriber) { msg.subscribe(subscriber); } /** * Invoked every time a read of the incoming body is requested by the subscriber. * * Provided so that the server subclass can intercept this to send a 100 continue response. */ protected void bodyRequested(ChannelHandlerContext ctx) { } @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { if (inClass.isInstance(msg)) { receivedInMessage(ctx); InT inMsg = inClass.cast(msg); if (inMsg instanceof FullHttpMessage) { // Forward as is ctx.fireChannelRead(inMsg); consumedInMessage(ctx); } else if (!hasBody(inMsg)) { // Wrap in empty message ctx.fireChannelRead(createEmptyMessage(inMsg)); consumedInMessage(ctx); // There will be a LastHttpContent message coming after this, ignore it ignoreBodyRead = true; } else { currentlyStreamedMessage = inMsg; // It has a body, stream it HandlerPublisher<HttpContent> publisher = new HandlerPublisher<HttpContent>(ctx.executor(), HttpContent.class) { @Override protected void cancelled() { if (ctx.executor().inEventLoop()) { handleCancelled(ctx, inMsg); } else { ctx.executor().execute(new Runnable() { @Override public void run() { handleCancelled(ctx, inMsg); } }); } } @Override protected void requestDemand() { bodyRequested(ctx); super.requestDemand(); } }; ctx.channel().pipeline().addAfter(ctx.name(), ctx.name() + "-body-publisher", publisher); ctx.fireChannelRead(createStreamedMessage(inMsg, publisher)); } } else if (msg instanceof HttpContent) { handleReadHttpContent(ctx, (HttpContent) msg); } } private void handleCancelled(ChannelHandlerContext ctx, InT msg) { if (currentlyStreamedMessage == msg) { ignoreBodyRead = true; // Need to do a read in case the subscriber ignored a read completed. ctx.read(); } } private void handleReadHttpContent(ChannelHandlerContext ctx, HttpContent content) { boolean lastHttpContent = content instanceof LastHttpContent; if (lastHttpContent) { logger.debug(ctx.channel(), () -> "Received LastHttpContent " + ctx.channel() + " with ignoreBodyRead as " + ignoreBodyRead); ctx.channel().attr(STREAMING_COMPLETE_KEY).set(true); } if (!ignoreBodyRead) { if (lastHttpContent) { if (content.content().readableBytes() > 0 || !((LastHttpContent) content).trailingHeaders().isEmpty()) { // It has data or trailing headers, send them ctx.fireChannelRead(content); } else { ReferenceCountUtil.release(content); } removeHandlerIfActive(ctx, ctx.name() + "-body-publisher"); currentlyStreamedMessage = null; consumedInMessage(ctx); } else { ctx.fireChannelRead(content); } } else { ReferenceCountUtil.release(content); if (lastHttpContent) { ignoreBodyRead = false; if (currentlyStreamedMessage != null) { removeHandlerIfActive(ctx, ctx.name() + "-body-publisher"); } currentlyStreamedMessage = null; } } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { if (ignoreBodyRead) { ctx.read(); } else { ctx.fireChannelReadComplete(); } } @Override public void write(final ChannelHandlerContext ctx, Object msg, final ChannelPromise promise) throws Exception { if (outClass.isInstance(msg)) { Outgoing out = new Outgoing(outClass.cast(msg), promise); receivedOutMessage(ctx); if (outgoing.isEmpty()) { outgoing.add(out); flushNext(ctx); } else { outgoing.add(out); } } else if (msg instanceof LastHttpContent) { sendLastHttpContent = false; ctx.write(msg, promise); } else { ctx.write(msg, promise); } } protected void unbufferedWrite(final ChannelHandlerContext ctx, final Outgoing out) { if (out.message instanceof FullHttpMessage) { // Forward as is ctx.writeAndFlush(out.message, out.promise); out.promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { executeInEventLoop(ctx, new Runnable() { @Override public void run() { sentOutMessage(ctx); outgoing.remove(); flushNext(ctx); } }); } }); } else if (out.message instanceof StreamedHttpMessage) { StreamedHttpMessage streamed = (StreamedHttpMessage) out.message; HandlerSubscriber<HttpContent> subscriber = new HandlerSubscriber<HttpContent>(ctx.executor()) { @Override protected void error(Throwable error) { out.promise.tryFailure(error); ctx.close(); } @Override protected void complete() { executeInEventLoop(ctx, new Runnable() { @Override public void run() { completeBody(ctx); } }); } }; sendLastHttpContent = true; // DON'T pass the promise through, create a new promise instead. ctx.writeAndFlush(out.message); ctx.pipeline().addAfter(ctx.name(), ctx.name() + "-body-subscriber", subscriber); subscribeSubscriberToStream(streamed, subscriber); } } private void completeBody(final ChannelHandlerContext ctx) { removeHandlerIfActive(ctx, ctx.name() + "-body-subscriber"); if (sendLastHttpContent) { ChannelPromise promise = outgoing.peek().promise; ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, promise).addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { executeInEventLoop(ctx, new Runnable() { @Override public void run() { outgoing.remove(); sentOutMessage(ctx); flushNext(ctx); } }); } } ); } else { outgoing.remove().promise.setSuccess(); sentOutMessage(ctx); flushNext(ctx); } } /** * Most operations we want to do even if the channel is not active, because if it's not, then we want to encounter * the error that occurs when that operation happens and so that it can be passed up to the user. However, removing * handlers should only be done if the channel is active, because the error that is encountered when they aren't * makes no sense to the user (NoSuchElementException). */ private void removeHandlerIfActive(ChannelHandlerContext ctx, String name) { if (ctx.channel().isActive()) { ctx.pipeline().remove(name); } } private void flushNext(ChannelHandlerContext ctx) { if (!outgoing.isEmpty()) { unbufferedWrite(ctx, outgoing.element()); } else { ctx.fireChannelWritabilityChanged(); } } private void executeInEventLoop(ChannelHandlerContext ctx, Runnable runnable) { if (ctx.executor().inEventLoop()) { runnable.run(); } else { ctx.executor().execute(runnable); } } class Outgoing { final OutT message; final ChannelPromise promise; Outgoing(OutT message, ChannelPromise promise) { this.message = message; this.promise = promise; } } }
1,461
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateStreamedHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponse; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi final class DelegateStreamedHttpResponse extends DelegateHttpResponse implements StreamedHttpResponse { private final Publisher<HttpContent> stream; DelegateStreamedHttpResponse(HttpResponse response, Publisher<HttpContent> stream) { super(response); this.stream = stream; } @Override public void subscribe(Subscriber<? super HttpContent> subscriber) { stream.subscribe(subscriber); } }
1,462
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DefaultStreamedHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import java.util.Objects; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A default streamed HTTP response. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public class DefaultStreamedHttpResponse extends DefaultHttpResponse implements StreamedHttpResponse { private final Publisher<HttpContent> stream; public DefaultStreamedHttpResponse(HttpVersion version, HttpResponseStatus status, Publisher<HttpContent> stream) { super(version, status); this.stream = stream; } public DefaultStreamedHttpResponse(HttpVersion version, HttpResponseStatus status, boolean validateHeaders, Publisher<HttpContent> stream) { super(version, status, validateHeaders); this.stream = stream; } @Override public void subscribe(Subscriber<? super HttpContent> subscriber) { stream.subscribe(subscriber); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } DefaultStreamedHttpResponse that = (DefaultStreamedHttpResponse) o; return Objects.equals(stream, that.stream); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (stream != null ? stream.hashCode() : 0); return result; } }
1,463
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/HandlerPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelPipeline; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.EventExecutor; import io.netty.util.internal.TypeParameterMatcher; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Publisher for a Netty Handler. * * This publisher supports only one subscriber. * * All interactions with the subscriber are done from the handlers executor, hence, they provide the same happens before * semantics that Netty provides. * * The handler publishes all messages that match the type as specified by the passed in class. Any non matching messages * are forwarded to the next handler. * * The publisher will signal complete if it receives a channel inactive event. * * The publisher will release any messages that it drops (for example, messages that are buffered when the subscriber * cancels), but other than that, it does not release any messages. It is up to the subscriber to release messages. * * If the subscriber cancels, the publisher will send a close event up the channel pipeline. * * All errors will short circuit the buffer, and cause publisher to immediately call the subscribers onError method, * dropping the buffer. * * The publisher can be subscribed to or placed in a handler chain in any order. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt */ @SdkInternalApi public class HandlerPublisher<T> extends ChannelDuplexHandler implements Publisher<T> { /** * Used for buffering a completion signal. */ private static final Object COMPLETE = new Object() { @Override public String toString() { return "COMPLETE"; } }; private final EventExecutor executor; private final TypeParameterMatcher matcher; private final Queue<Object> buffer = new LinkedList<>(); /** * Whether a subscriber has been provided. This is used to detect whether two subscribers are subscribing * simultaneously. */ private final AtomicBoolean hasSubscriber = new AtomicBoolean(); private State state = HandlerPublisher.State.NO_SUBSCRIBER_OR_CONTEXT; private volatile Subscriber<? super T> subscriber; private ChannelHandlerContext ctx; private long outstandingDemand = 0; private Throwable noSubscriberError; /** * Create a handler publisher. * * The supplied executor must be the same event loop as the event loop that this handler is eventually registered * with, if not, an exception will be thrown when the handler is registered. * * @param executor The executor to execute asynchronous events from the subscriber on. * @param subscriberMessageType The type of message this publisher accepts. */ public HandlerPublisher(EventExecutor executor, Class<? extends T> subscriberMessageType) { this.executor = executor; this.matcher = TypeParameterMatcher.get(subscriberMessageType); } /** * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * * @param msg The message to check. * @return True if the message should be accepted. */ protected boolean acceptInboundMessage(Object msg) throws Exception { return matcher.match(msg); } /** * Override to handle when a subscriber cancels the subscription. * * By default, this method will simply close the channel. */ protected void cancelled() { ctx.close(); } /** * Override to intercept when demand is requested. * * By default, a channel read is invoked. */ protected void requestDemand() { ctx.read(); } enum State { /** * Initial state. There's no subscriber, and no context. */ NO_SUBSCRIBER_OR_CONTEXT, /** * A subscriber has been provided, but no context has been provided. */ NO_CONTEXT, /** * A context has been provided, but no subscriber has been provided. */ NO_SUBSCRIBER, /** * An error has been received, but there's no subscriber to receive it. */ NO_SUBSCRIBER_ERROR, /** * There is no demand, and we have nothing buffered. */ IDLE, /** * There is no demand, and we're buffering elements. */ BUFFERING, /** * We have nothing buffered, but there is demand. */ DEMANDING, /** * The stream is complete, however there are still elements buffered for which no demand has come from the subscriber. */ DRAINING, /** * We're done, in the terminal state. */ DONE } @Override public void subscribe(final Subscriber<? super T> subscriber) { if (subscriber == null) { throw new NullPointerException("Null subscriber"); } if (!hasSubscriber.compareAndSet(false, true)) { // Must call onSubscribe first. subscriber.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { } }); subscriber.onError(new IllegalStateException("This publisher only supports one subscriber")); } else { executor.execute(new Runnable() { @Override public void run() { provideSubscriber(subscriber); } }); } } private void provideSubscriber(Subscriber<? super T> subscriber) { this.subscriber = subscriber; switch (state) { case NO_SUBSCRIBER_OR_CONTEXT: state = HandlerPublisher.State.NO_CONTEXT; break; case NO_SUBSCRIBER: if (buffer.isEmpty()) { state = HandlerPublisher.State.IDLE; } else { state = HandlerPublisher.State.BUFFERING; } subscriber.onSubscribe(new ChannelSubscription()); break; case DRAINING: subscriber.onSubscribe(new ChannelSubscription()); break; case NO_SUBSCRIBER_ERROR: cleanup(); state = HandlerPublisher.State.DONE; subscriber.onSubscribe(new ChannelSubscription()); subscriber.onError(noSubscriberError); break; default: // Do nothing } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // If the channel is not yet registered, then it's not safe to invoke any methods on it, eg read() or close() // So don't provide the context until it is registered. if (ctx.channel().isRegistered()) { provideChannelContext(ctx); } } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { provideChannelContext(ctx); ctx.fireChannelRegistered(); } private void provideChannelContext(ChannelHandlerContext ctx) { switch (state) { case NO_SUBSCRIBER_OR_CONTEXT: verifyRegisteredWithRightExecutor(ctx); this.ctx = ctx; // It's set, we don't have a subscriber state = HandlerPublisher.State.NO_SUBSCRIBER; break; case NO_CONTEXT: verifyRegisteredWithRightExecutor(ctx); this.ctx = ctx; state = HandlerPublisher.State.IDLE; subscriber.onSubscribe(new ChannelSubscription()); break; default: // Ignore, this could be invoked twice by both handlerAdded and channelRegistered. } } private void verifyRegisteredWithRightExecutor(ChannelHandlerContext ctx) { if (!executor.inEventLoop()) { throw new IllegalArgumentException("Channel handler MUST be registered with the same EventExecutor that it is " + "created with."); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // If we subscribed before the channel was active, then our read would have been ignored. if (state == HandlerPublisher.State.DEMANDING) { requestDemand(); } ctx.fireChannelActive(); } private void receivedDemand(long demand) { switch (state) { case BUFFERING: case DRAINING: if (addDemand(demand)) { flushBuffer(); } break; case DEMANDING: addDemand(demand); break; case IDLE: if (addDemand(demand)) { // Important to change state to demanding before doing a read, in case we get a synchronous // read back. state = HandlerPublisher.State.DEMANDING; requestDemand(); } break; default: } } private boolean addDemand(long demand) { if (demand <= 0) { illegalDemand(); return false; } else { if (outstandingDemand < Long.MAX_VALUE) { outstandingDemand += demand; if (outstandingDemand < 0) { outstandingDemand = Long.MAX_VALUE; } } return true; } } private void illegalDemand() { cleanup(); subscriber.onError(new IllegalArgumentException("Request for 0 or negative elements in violation of Section 3.9 " + "of the Reactive Streams specification")); ctx.close(); state = HandlerPublisher.State.DONE; } private void flushBuffer() { while (!buffer.isEmpty() && (outstandingDemand > 0 || outstandingDemand == Long.MAX_VALUE)) { publishMessage(buffer.remove()); } if (buffer.isEmpty()) { if (outstandingDemand > 0) { if (state == HandlerPublisher.State.BUFFERING) { state = HandlerPublisher.State.DEMANDING; } // otherwise we're draining requestDemand(); } else if (state == HandlerPublisher.State.BUFFERING) { state = HandlerPublisher.State.IDLE; } } } private void receivedCancel() { switch (state) { case BUFFERING: case DEMANDING: case IDLE: cancelled(); state = HandlerPublisher.State.DONE; break; case DRAINING: state = HandlerPublisher.State.DONE; break; default: // ignore } cleanup(); subscriber = null; } @Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception { if (acceptInboundMessage(message)) { switch (state) { case IDLE: buffer.add(message); state = HandlerPublisher.State.BUFFERING; break; case NO_SUBSCRIBER: case BUFFERING: buffer.add(message); break; case DEMANDING: publishMessage(message); break; case DRAINING: case DONE: ReferenceCountUtil.release(message); break; case NO_CONTEXT: case NO_SUBSCRIBER_OR_CONTEXT: throw new IllegalStateException("Message received before added to the channel context"); default: // Ignore } } else { ctx.fireChannelRead(message); } } private void publishMessage(Object message) { if (COMPLETE.equals(message)) { subscriber.onComplete(); state = HandlerPublisher.State.DONE; } else { @SuppressWarnings("unchecked") T next = (T) message; subscriber.onNext(next); if (outstandingDemand < Long.MAX_VALUE) { outstandingDemand--; if (outstandingDemand == 0 && state != HandlerPublisher.State.DRAINING) { if (buffer.isEmpty()) { state = HandlerPublisher.State.IDLE; } else { state = HandlerPublisher.State.BUFFERING; } } } } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { if (state == HandlerPublisher.State.DEMANDING) { requestDemand(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { complete(); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { complete(); } private void complete() { switch (state) { case NO_SUBSCRIBER: case BUFFERING: buffer.add(COMPLETE); state = HandlerPublisher.State.DRAINING; break; case DEMANDING: case IDLE: subscriber.onComplete(); state = HandlerPublisher.State.DONE; break; case NO_SUBSCRIBER_ERROR: // Ignore, we're already going to complete the stream with an error // when the subscriber subscribes. break; default: // Ignore } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { switch (state) { case NO_SUBSCRIBER: noSubscriberError = cause; state = HandlerPublisher.State.NO_SUBSCRIBER_ERROR; cleanup(); break; case BUFFERING: case DEMANDING: case IDLE: case DRAINING: state = HandlerPublisher.State.DONE; cleanup(); subscriber.onError(cause); break; default: // Ignore } } /** * Release all elements from the buffer. */ private void cleanup() { while (!buffer.isEmpty()) { ReferenceCountUtil.release(buffer.remove()); } } private class ChannelSubscription implements Subscription { @Override public void request(final long demand) { executor.execute(new Runnable() { @Override public void run() { receivedDemand(demand); } }); } @Override public void cancel() { executor.execute(new Runnable() { @Override public void run() { receivedCancel(); } }); } } }
1,464
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi class DelegateHttpResponse extends DelegateHttpMessage implements HttpResponse { protected final HttpResponse response; DelegateHttpResponse(HttpResponse response) { super(response); this.response = response; } @Override public HttpResponse setStatus(HttpResponseStatus status) { response.setStatus(status); return this; } @Override @Deprecated public HttpResponseStatus getStatus() { return response.status(); } @Override public HttpResponseStatus status() { return response.status(); } @Override public HttpResponse setProtocolVersion(HttpVersion version) { super.setProtocolVersion(version); return this; } }
1,465
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/StreamedHttpMessage.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMessage; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Combines {@link HttpMessage} and {@link Publisher} into one * message. So it represents an http message with a stream of {@link HttpContent} * messages that can be subscribed to. * * Note that receivers of this message <em>must</em> consume the publisher, * since the publisher will exert back pressure up the stream if not consumed. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public interface StreamedHttpMessage extends HttpMessage, Publisher<HttpContent> { }
1,466
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateHttpMessage.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMessage; import io.netty.handler.codec.http.HttpVersion; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi class DelegateHttpMessage implements HttpMessage { protected final HttpMessage message; DelegateHttpMessage(HttpMessage message) { this.message = message; } @Override @Deprecated public HttpVersion getProtocolVersion() { return message.protocolVersion(); } @Override public HttpVersion protocolVersion() { return message.protocolVersion(); } @Override public HttpMessage setProtocolVersion(HttpVersion version) { message.setProtocolVersion(version); return this; } @Override public HttpHeaders headers() { return message.headers(); } @Override @Deprecated public DecoderResult getDecoderResult() { return message.decoderResult(); } @Override public DecoderResult decoderResult() { return message.decoderResult(); } @Override public void setDecoderResult(DecoderResult result) { message.setDecoderResult(result); } @Override public String toString() { return this.getClass().getName() + "(" + message.toString() + ")"; } }
1,467
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/DelegateStreamedHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpRequest; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi final class DelegateStreamedHttpRequest extends DelegateHttpRequest implements StreamedHttpRequest { private final Publisher<HttpContent> stream; DelegateStreamedHttpRequest(HttpRequest request, Publisher<HttpContent> stream) { super(request); this.stream = stream; } @Override public void subscribe(Subscriber<? super HttpContent> subscriber) { stream.subscribe(subscriber); } }
1,468
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/EmptyHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi class EmptyHttpRequest extends DelegateHttpRequest implements FullHttpRequest { EmptyHttpRequest(HttpRequest request) { super(request); } @Override public FullHttpRequest setUri(String uri) { super.setUri(uri); return this; } @Override public FullHttpRequest setMethod(HttpMethod method) { super.setMethod(method); return this; } @Override public FullHttpRequest setProtocolVersion(HttpVersion version) { super.setProtocolVersion(version); return this; } @Override public FullHttpRequest copy() { if (request instanceof FullHttpRequest) { return new EmptyHttpRequest(((FullHttpRequest) request).copy()); } else { DefaultHttpRequest copy = new DefaultHttpRequest(protocolVersion(), method(), uri()); copy.headers().set(headers()); return new EmptyHttpRequest(copy); } } @Override public FullHttpRequest retain(int increment) { ReferenceCountUtil.retain(message, increment); return this; } @Override public FullHttpRequest retain() { ReferenceCountUtil.retain(message); return this; } @Override public FullHttpRequest touch() { if (request instanceof FullHttpRequest) { return ((FullHttpRequest) request).touch(); } else { return this; } } @Override public FullHttpRequest touch(Object o) { if (request instanceof FullHttpRequest) { return ((FullHttpRequest) request).touch(o); } else { return this; } } @Override public HttpHeaders trailingHeaders() { return new DefaultHttpHeaders(); } @Override public FullHttpRequest duplicate() { if (request instanceof FullHttpRequest) { return ((FullHttpRequest) request).duplicate(); } else { return this; } } @Override public FullHttpRequest retainedDuplicate() { if (request instanceof FullHttpRequest) { return ((FullHttpRequest) request).retainedDuplicate(); } else { return this; } } @Override public FullHttpRequest replace(ByteBuf byteBuf) { if (message instanceof FullHttpRequest) { return ((FullHttpRequest) request).replace(byteBuf); } else { return this; } } @Override public ByteBuf content() { return Unpooled.EMPTY_BUFFER; } @Override public int refCnt() { if (message instanceof ReferenceCounted) { return ((ReferenceCounted) message).refCnt(); } else { return 1; } } @Override public boolean release() { return ReferenceCountUtil.release(message); } @Override public boolean release(int decrement) { return ReferenceCountUtil.release(message, decrement); } }
1,469
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/CancelledSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal.nrs; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A cancelled subscriber. * * This class contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ @SdkInternalApi public final class CancelledSubscriber<T> implements Subscriber<T> { @Override public void onSubscribe(Subscription subscription) { if (subscription == null) { throw new NullPointerException("Null subscription"); } else { subscription.cancel(); } } @Override public void onNext(T t) { } @Override public void onError(Throwable error) { if (error == null) { throw new NullPointerException("Null error published"); } } @Override public void onComplete() { } }
1,470
0
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal
Create_ds/aws-sdk-java-v2/http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/nrs/package-info.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * This package contains source imported from https://github.com/playframework/netty-reactive-streams, * licensed under the Apache License 2.0, available at the time of the fork (1/31/2020) here: * https://github.com/playframework/netty-reactive-streams/blob/master/LICENSE.txt * * All original source licensed under the Apache License 2.0 by playframework. All modifications are * licensed under the Apache License 2.0 by Amazon Web Services. */ package software.amazon.awssdk.http.nio.netty.internal.nrs;
1,471
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/AwsRequestOverrideConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; public class AwsRequestOverrideConfigurationTest { @Test public void testCredentialsProviderWorksWithBothOldAndNewInterfaceTypes() { AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("akid","skid")); AwsRequestOverrideConfiguration configuration1 = AwsRequestOverrideConfiguration .builder().credentialsProvider(credentialsProvider).build(); AwsRequestOverrideConfiguration configuration2 = AwsRequestOverrideConfiguration .builder().credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider).build(); assertCredentialsEqual(configuration1.credentialsProvider().get(), configuration1.credentialsIdentityProvider().get()); assertCredentialsEqual(configuration2.credentialsProvider().get(), configuration2.credentialsIdentityProvider().get()); assertCredentialsEqual(configuration1.credentialsProvider().get(), configuration2.credentialsIdentityProvider().get()); assertCredentialsEqual(configuration2.credentialsProvider().get(), configuration1.credentialsIdentityProvider().get()); } private void assertCredentialsEqual(AwsCredentialsProvider credentialsProvider, IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) { AwsCredentials creds1 = credentialsProvider.resolveCredentials(); AwsCredentialsIdentity creds2 = identityProvider.resolveIdentity().join(); assertThat(creds1.accessKeyId()).isEqualTo(creds2.accessKeyId()); assertThat(creds1.secretAccessKey()).isEqualTo(creds2.secretAccessKey()); } }
1,472
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/eventstream/EventStreamInitialRequestInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT; import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import io.reactivex.Flowable; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.Context.ModifyHttpRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class EventStreamInitialRequestInterceptorTest { static final String RPC_CONTENT_TYPE = "rpc-format"; Message eventMessage = getEventMessage(); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()); byte[] payload = "initial request payload".getBytes(StandardCharsets.UTF_8); ExecutionAttributes attr = new ExecutionAttributes().putAttribute(HAS_INITIAL_REQUEST_EVENT, true); EventStreamInitialRequestInterceptor interceptor = new EventStreamInitialRequestInterceptor(); @Test public void testHttpHeaderModification() { ModifyHttpRequest context = buildContext(bytePublisher, payload); SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(context, attr); List<String> contentType = modifiedRequest.headers().get(CONTENT_TYPE); assertEquals(1, contentType.size()); assertEquals(MIMETYPE_EVENT_STREAM, contentType.get(0)); } @Test public void testInitialRequestEvent() { ModifyHttpRequest context = buildContext(bytePublisher, payload); Optional<AsyncRequestBody> modifiedBody = interceptor.modifyAsyncHttpContent(context, attr); List<Message> messages = Flowable.fromPublisher(modifiedBody.get()).map(Message::decode).toList().blockingGet(); Message initialRequestEvent = messages.get(0); assertArrayEquals(payload, initialRequestEvent.getPayload()); assertEquals(RPC_CONTENT_TYPE, initialRequestEvent.getHeaders().get(":content-type").getString()); } @Test public void testPrepending() { ModifyHttpRequest context = buildContext(bytePublisher, payload); Optional<AsyncRequestBody> modifiedBody = interceptor.modifyAsyncHttpContent(context, attr); List<Message> messages = Flowable.fromPublisher(modifiedBody.get()).map(Message::decode).toList().blockingGet(); assertEquals(3, messages.size()); assertEquals(eventMessage, messages.get(1)); assertEquals(eventMessage, messages.get(2)); } @Test public void testDisabled() { ModifyHttpRequest context = buildContext(bytePublisher, payload); attr.putAttribute(HAS_INITIAL_REQUEST_EVENT, false); assertSame(context.httpRequest(), interceptor.modifyHttpRequest(context, attr)); assertSame(context.asyncRequestBody(), interceptor.modifyAsyncHttpContent(context, attr)); } private ModifyHttpRequest buildContext(Flowable<ByteBuffer> bytePublisher, byte[] payload) { SdkHttpFullRequest request = buildRequest(); ModifyHttpRequest context = Mockito.mock(ModifyHttpRequest.class); when(context.httpRequest()).thenReturn(request); when(context.asyncRequestBody()).thenReturn(Optional.of(AsyncRequestBody.fromPublisher(bytePublisher))); when(context.requestBody()).thenReturn(Optional.of(RequestBody.fromByteBuffer(ByteBuffer.wrap(payload)))); return context; } private SdkHttpFullRequest buildRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .uri(URI.create("https://example.com/")) .putHeader(CONTENT_TYPE, RPC_CONTENT_TYPE) .build(); } private Message getEventMessage() { Map<String, HeaderValue> headers = ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")); return new Message(headers, new byte[0]); } }
1,473
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/eventstream/EventStreamAsyncResponseTransformerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class EventStreamAsyncResponseTransformerTest { @Test public void multipleEventsInChunk_OnlyDeliversOneEvent() throws InterruptedException { Message eventMessage = new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")), new byte[0]); CountDownLatch latch = new CountDownLatch(1); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()) .doOnCancel(latch::countDown); AtomicInteger numEvents = new AtomicInteger(0); // Request one event then cancel Subscriber<Object> requestOneSubscriber = new Subscriber<Object>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(Object o) { numEvents.incrementAndGet(); subscription.cancel(); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }; AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> p.subscribe(requestOneSubscriber))) .eventResponseHandler((r, e) -> new Object()) .executor(Executors.newSingleThreadExecutor()) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); assertThat(numEvents) .as("Expected only one event to be delivered") .hasValue(1); } @Test public void devilSubscriber_requestDataAfterComplete() throws InterruptedException { Message eventMessage = new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")), "helloworld".getBytes()); CountDownLatch latch = new CountDownLatch(1); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()); AtomicInteger numEvents = new AtomicInteger(0); Subscriber<Object> requestAfterCompleteSubscriber = new Subscriber<Object>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(Object o) { subscription.request(1); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { // Should never ever do this in production! subscription.request(1); latch.countDown(); } }; AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> p.subscribe(requestAfterCompleteSubscriber))) .eventResponseHandler((r, e) -> numEvents.incrementAndGet()) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); assertThat(numEvents) .as("Expected only one event to be delivered") .hasValue(2); } @Test public void unknownExceptionEventsThrowException() { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":message-type", HeaderValue.fromString("exception")); headers.put(":exception-type", HeaderValue.fromString("modeledException")); headers.put(":content-type", HeaderValue.fromString("application/json")); verifyExceptionThrown(headers); } @Test public void errorEventsThrowException() { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":message-type", HeaderValue.fromString("error")); verifyExceptionThrown(headers); } @Test public void prepareReturnsNewFuture() { AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> {})) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); CompletableFuture<?> cf1 = transformer.prepare(); transformer.exceptionOccurred(new RuntimeException("Boom!")); assertThat(cf1.isCompletedExceptionally()).isTrue(); assertThat(transformer.prepare()).isNotEqualTo(cf1); } @Test(timeout = 2000) public void prepareResetsSubscriberRef() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); AtomicBoolean exceptionThrown = new AtomicBoolean(false); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> { try { p.subscribe(e -> {}); } catch (Throwable t) { exceptionThrown.set(true); } finally { latch.countDown(); } })) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); Flowable<ByteBuffer> bytePublisher = Flowable.empty(); CompletableFuture<Void> transformFuture = transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); transformFuture.join(); transformFuture = transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); transformFuture.join(); latch.await(); assertThat(exceptionThrown).isFalse(); } @Test public void erroneousExtraExceptionOccurredDoesNotSurfaceException() { AtomicLong numExceptions = new AtomicLong(0); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { } @Override public void exceptionOccurred(Throwable throwable) { numExceptions.incrementAndGet(); } @Override public void complete() { } }) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.exceptionOccurred(new RuntimeException("Boom!")); transformer.exceptionOccurred(new RuntimeException("Boom again!")); assertThat(numExceptions).hasValue(1); } // Test that the class guards against signalling exceptionOccurred if the stream is already complete. @Test public void erroneousExceptionOccurredAfterCompleteDoesNotSurfaceException() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Subscriber<Object> subscriber = new Subscriber<Object>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(1); } @Override public void onNext(Object o) { } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { latch.countDown(); } }; AtomicLong numExceptionOccurredCalls = new AtomicLong(0); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { publisher.subscribe(subscriber); } @Override public void exceptionOccurred(Throwable throwable) { numExceptionOccurredCalls.incrementAndGet(); } @Override public void complete() { latch.countDown(); } }) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); Flowable<ByteBuffer> bytePublisher = Flowable.empty(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); transformer.exceptionOccurred(new RuntimeException("Uh-oh")); assertThat(numExceptionOccurredCalls) .as("Expected only one event to be delivered") .hasValue(0); } private void verifyExceptionThrown(Map<String, HeaderValue> headers) { SdkServiceException exception = SdkServiceException.builder().build(); Message exceptionMessage = new Message(headers, new byte[0]); Flowable<ByteBuffer> bytePublisher = Flowable.just(exceptionMessage.toByteBuffer()); SubscribingResponseHandler handler = new SubscribingResponseHandler(); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(handler) .exceptionResponseHandler((response, executionAttributes) -> exception) .executor(Executors.newSingleThreadExecutor()) .future(new CompletableFuture<>()) .build(); CompletableFuture<Void> cf = transformer.prepare(); transformer.onResponse(null); transformer.onStream(SdkPublisher.adapt(bytePublisher)); assertThatThrownBy(() -> { try { cf.join(); } catch (CompletionException e) { if (e.getCause() instanceof SdkServiceException) { throw e.getCause(); } } }).isSameAs(exception); assertThat(handler.exceptionOccurredCalled).isTrue(); } private static class SubscribingResponseHandler implements EventStreamResponseHandler<Object, Object> { private volatile boolean exceptionOccurredCalled = false; @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { publisher.subscribe(e -> { }); } @Override public void exceptionOccurred(Throwable throwable) { exceptionOccurredCalled = true; } @Override public void complete() { } } public EventStreamResponseHandler<Object, Object> onEventStream(Consumer<SdkPublisher<Object>> onEventStream) { return new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { onEventStream.accept(publisher); } @Override public void exceptionOccurred(Throwable throwable) { } @Override public void complete() { } }; } }
1,474
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/retry/RetryOnErrorCodeConditionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Sets; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.awscore.retry.conditions.RetryOnErrorCodeCondition; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class RetryOnErrorCodeConditionTest { private RetryOnErrorCodeCondition condition = RetryOnErrorCodeCondition.create(Sets.newHashSet("Foo", "Bar")); @Test public void noExceptionInContext_ReturnsFalse() { assertFalse(shouldRetry(builder -> builder.exception(null))); } @Test public void retryableErrorCodes_ReturnsTrue() { assertTrue(shouldRetry(applyErrorCode("Foo"))); assertTrue(shouldRetry(applyErrorCode("Bar"))); } @Test public void nonRetryableErrorCode_ReturnsFalse() { assertFalse(shouldRetry(applyErrorCode("HelloWorld"))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return condition.shouldRetry(RetryPolicyContext.builder().applyMutation(builder).build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) { AwsServiceException.Builder exception = AwsServiceException.builder(); exception.statusCode(404); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build()); return b -> b.exception(exception.build()); } }
1,475
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/retry/AwsRetryPolicyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry; import static java.time.temporal.ChronoUnit.HOURS; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static software.amazon.awssdk.awscore.retry.AwsRetryPolicy.defaultRetryCondition; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.DateUtils; public class AwsRetryPolicyTest { @Test public void retriesOnRetryableErrorCodes() { assertTrue(shouldRetry(applyErrorCode("PriorRequestNotComplete"))); } @Test public void retriesOnThrottlingExceptions() { assertTrue(shouldRetry(applyErrorCode("ThrottlingException"))); assertTrue(shouldRetry(applyErrorCode("ThrottledException"))); assertTrue(shouldRetry(applyStatusCode(429))); } @Test public void retriesOnClockSkewErrors() { assertTrue(shouldRetry(applyErrorCode("RequestTimeTooSkewed"))); assertTrue(shouldRetry(applyErrorCode("AuthFailure", Duration.ZERO, Instant.now().minus(1, HOURS)))); } @Test public void retriesOnInternalError() { assertTrue(shouldRetry(applyStatusCode(500))); } @Test public void retriesOnBadGateway() { assertTrue(shouldRetry(applyStatusCode(502))); } @Test public void retriesOnServiceUnavailable() { assertTrue(shouldRetry(applyStatusCode(503))); } @Test public void retriesOnGatewayTimeout() { assertTrue(shouldRetry(applyStatusCode(504))); } @Test public void retriesOnIOException() { assertTrue(shouldRetry(b -> b.exception(SdkClientException.builder() .message("IO") .cause(new IOException()) .build()))); } @Test public void retriesOnRetryableException() { assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().build()))); } @Test public void doesNotRetryOnNonRetryableException() { assertFalse(shouldRetry(b -> b.exception(NonRetryableException.builder().build()))); } @Test public void doesNotRetryOnNonRetryableStatusCode() { assertFalse(shouldRetry(applyStatusCode(404))); } @Test public void doesNotRetryOnNonRetryableErrorCode() { assertFalse(shouldRetry(applyErrorCode("ValidationError"))); } @Test public void retriesOnEC2ThrottledException() { AwsServiceException ex = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorCode("EC2ThrottledException") .build()) .build(); assertTrue(shouldRetry(b -> b.exception(ex))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return defaultRetryCondition().shouldRetry(RetryPolicyContext.builder().applyMutation(builder).build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) { AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(404); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build()); return b -> b.exception(exception.build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode, Duration clockSkew, Instant dateHeader) { SdkHttpFullResponse response = SdkHttpFullResponse.builder() .putHeader("Date", DateUtils.formatRfc822Date(dateHeader)) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode(errorCode) .sdkHttpResponse(response) .build(); AwsServiceException.Builder exception = AwsServiceException.builder() .statusCode(404) .awsErrorDetails(errorDetails) .clockSkew(clockSkew); return b -> b.exception(exception.build()); } private Consumer<RetryPolicyContext.Builder> applyStatusCode(Integer statusCode) { AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(statusCode); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode("Foo").build()); return b -> b.exception(exception.build()) .httpStatusCode(statusCode); } }
1,476
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/TestWrapperSchedulerService.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import software.amazon.awssdk.utils.ThreadFactoryBuilder; /** * Test Scheduler class to Spy on default implementation of ScheduledExecutorService. */ public class TestWrapperSchedulerService implements ScheduledExecutorService { ScheduledExecutorService scheduledExecutorService; public TestWrapperSchedulerService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return scheduledExecutorService.schedule(command,delay,unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return scheduledExecutorService.schedule(callable,delay,unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return scheduledExecutorService.scheduleAtFixedRate(command,initialDelay,delay,unit); } @Override public void shutdown() { scheduledExecutorService.shutdown(); } @Override public List<Runnable> shutdownNow() { return scheduledExecutorService.shutdownNow(); } @Override public boolean isShutdown() { return scheduledExecutorService.isShutdown(); } @Override public boolean isTerminated() { return scheduledExecutorService.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return scheduledExecutorService.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { return scheduledExecutorService.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return scheduledExecutorService.submit(task,result); } @Override public Future<?> submit(Runnable task) { return scheduledExecutorService.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return scheduledExecutorService.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return scheduledExecutorService.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return scheduledExecutorService.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return scheduledExecutorService.invokeAny(tasks,timeout,unit); } @Override public void execute(Runnable command) { scheduledExecutorService.execute(command); } }
1,477
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/SignerOverrideUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.http.NoopTestAwsRequest; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.Pair; class SignerOverrideUtilsTest { @Test @DisplayName("If signer is already overridden, assert that it is not modified") void overrideSignerIfNotOverridden() { Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(new FooSigner()); SdkRequest request = stubs.left(); ExecutionAttributes executionAttributes = stubs.right(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, BarSigner::new); assertThat(result.overrideConfiguration()).isPresent(); assertThat(result.overrideConfiguration().get().signer().get()).isInstanceOf(FooSigner.class); } @Test @DisplayName("If signer is not already overridden, assert that it is overridden with the new signer") void overrideSignerIfNotOverridden2() { Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(null); SdkRequest request = stubs.left(); ExecutionAttributes executionAttributes = stubs.right(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, BarSigner::new); assertThat(result.overrideConfiguration()).isPresent(); assertThat(result.overrideConfiguration().get().signer().get()).isInstanceOf(BarSigner.class); } @Test @DisplayName("If signer will be overridden, assert that the other existing override configuration properties are preserved") public void overrideSignerOriginalConfigPreserved() { AwsRequestOverrideConfiguration originalOverride = AwsRequestOverrideConfiguration.builder() .putHeader("Header1", "HeaderValue1") .putRawQueryParameter("QueryParam1", "QueryValue1") .addApiName(ApiName.builder().name("foo").version("bar").build()) .build(); Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(null); SdkRequest request = ((AwsRequest) stubs.left()).toBuilder() .overrideConfiguration(originalOverride) .build(); ExecutionAttributes executionAttributes = stubs.right(); BarSigner overrideSigner = new BarSigner(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, () -> overrideSigner); AwsRequestOverrideConfiguration originalOverrideWithNewSigner = originalOverride.toBuilder() .signer(overrideSigner) .build(); assertThat(result.overrideConfiguration().get()).isEqualTo(originalOverrideWithNewSigner); } private static Pair<SdkRequest, ExecutionAttributes> stubInitialSigner(Signer signer) { AwsRequest request; if (signer != null) { AwsRequestOverrideConfiguration config = AwsRequestOverrideConfiguration.builder() .signer(signer) .build(); request = NoopTestAwsRequest.builder() .overrideConfiguration(config) .build(); } else { request = NoopTestAwsRequest.builder().build(); } ExecutionAttributes executionAttributes = new ExecutionAttributes(); if (signer != null) { executionAttributes.putAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN, true); } return Pair.of(request, executionAttributes); } private static class FooSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { throw new UnsupportedOperationException(); } } private static class BarSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { throw new UnsupportedOperationException(); } } }
1,478
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/AwsHostNameUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.awscore.util.AwsHostNameUtils.parseSigningRegion; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; /** Unit tests for the utility methods that parse information from AWS URLs. */ public class AwsHostNameUtilsTest { @Test public void testStandardNoHint() { // Verify that standard endpoints parse correctly without a service hint assertThat(parseSigningRegion("iam.amazonaws.com", null)).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", null)).hasValue(Region.US_WEST_2); } @Test public void testStandard() { // Verify that standard endpoints parse correctly with a service hint assertThat(parseSigningRegion("iam.amazonaws.com", "iam")).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", "iam")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", "ec2")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); } @Test public void testBjs() { // Verify that BJS endpoints parse correctly even though they're non-standard. assertThat(parseSigningRegion("iam.cn-north-1.amazonaws.com.cn", "iam")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("ec2.cn-north-1.amazonaws.com.cn", "ec2")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); } @Test public void testParseRegionWithIpv4() { assertThat(parseSigningRegion("54.231.16.200", null)).isNotPresent(); } }
1,479
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/AwsExecutionContextBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.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 java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; 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.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.core.internal.util.HttpChecksumUtils; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.profiles.ProfileFile; @RunWith(MockitoJUnitRunner.class) public class AwsExecutionContextBuilderTest { @Mock SdkRequest sdkRequest; @Mock ExecutionInterceptor interceptor; @Mock IdentityProvider<AwsCredentialsIdentity> defaultCredentialsProvider; @Mock Signer defaultSigner; @Mock Signer clientOverrideSigner; @Mock Map<String, AuthScheme<?>> defaultAuthSchemes; @Before public void setUp() throws Exception { when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); when(interceptor.modifyRequest(any(), any())).thenReturn(sdkRequest); when(defaultCredentialsProvider.resolveIdentity()).thenAnswer( invocationOnMock -> CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk"))); } @Test public void verifyInterceptors() { AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); verify(interceptor, times(1)).beforeExecution(any(), any()); verify(interceptor, times(1)).modifyRequest(any(), any()); } @Test public void verifyCoreExecutionAttributesTakePrecedence() { ExecutionAttributes requestOverrides = ExecutionAttributes.builder() .put(SdkExecutionAttribute.SERVICE_NAME, "RequestOverrideServiceName") .build(); Optional requestOverrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .executionAttributes(requestOverrides) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(requestOverrideConfiguration); ExecutionAttributes clientConfigOverrides = ExecutionAttributes.builder() .put(SdkExecutionAttribute.SERVICE_NAME, "ClientConfigServiceName") .build(); SdkClientConfiguration testClientConfiguration = testClientConfiguration() .option(SdkClientOption.SERVICE_NAME, "DoNotOverrideService") .option(SdkClientOption.EXECUTION_ATTRIBUTES, clientConfigOverrides) .build(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration); assertThat(executionContext.executionAttributes().getAttribute(SdkExecutionAttribute.SERVICE_NAME)).isEqualTo("DoNotOverrideService"); } // pre SRA, AuthorizationStrategy would setup the signer and resolve identity. @Test public void preSra_signing_ifNoOverrides_assignDefaultSigner_resolveIdentity() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), preSraClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(defaultSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } // This is post SRA case. This is asserting that AuthorizationStrategy is not used. @Test public void postSra_ifNoOverrides_doesNotResolveIdentity_doesNotAssignSigner() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_signing_ifClientOverride_assignClientOverrideSigner_resolveIdentity() { Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), preSraClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(clientOverrideSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } @Test public void postSra_signing_ifClientOverride_assignClientOverrideSigner_resolveIdentity() { Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(clientOverrideSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } @Test public void preSra_authTypeNone_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_authTypeNone_signerClientOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); clientConfig.option(SdkAdvancedClientOption.SIGNER, this.clientOverrideSigner) .option(SdkClientOption.SIGNER_OVERRIDDEN, true); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_signerClientOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); clientConfig.option(SdkAdvancedClientOption.SIGNER, this.clientOverrideSigner) .option(SdkClientOption.SIGNER_OVERRIDDEN, true); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_authTypeNone_signerRequestOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_signerRequestOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void invokeInterceptorsAndCreateExecutionContext_noHttpChecksumTrait_resolvesChecksumSpecs() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); Optional<ChecksumSpecs> checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes); Optional<ChecksumSpecs> checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes); assertThat(checksumSpecs1).isNotPresent(); assertThat(checksumSpecs2).isNotPresent(); assertThat(checksumSpecs1).isSameAs(checksumSpecs2); } @Test public void invokeInterceptorsAndCreateExecutionContext_singleExecutionContext_resolvesEqualChecksumSpecs() { HttpChecksum httpCrc32Checksum = HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build(); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams() .putExecutionAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, httpCrc32Checksum); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); ChecksumSpecs checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).get(); ChecksumSpecs checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).get(); assertThat(checksumSpecs1).isEqualTo(checksumSpecs2); } @Test public void invokeInterceptorsAndCreateExecutionContext_multipleExecutionContexts_resolvesEqualChecksumSpecs() { HttpChecksum httpCrc32Checksum = HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build(); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams() .putExecutionAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, httpCrc32Checksum); SdkClientConfiguration clientConfig = testClientConfiguration().build(); ExecutionContext executionContext1 = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes1 = executionContext1.executionAttributes(); ChecksumSpecs checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes1).get(); ExecutionContext executionContext2 = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes2 = executionContext2.executionAttributes(); ChecksumSpecs checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes2).get(); ChecksumSpecs checksumSpecs3 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes2).get(); assertThat(checksumSpecs1).isEqualTo(checksumSpecs2); assertThat(checksumSpecs2).isEqualTo(checksumSpecs3); } @Test public void invokeInterceptorsAndCreateExecutionContext_profileFileSupplier_storesValueInExecutionAttributes() { ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); Supplier<ProfileFile> profileFileSupplier = () -> null; SdkClientConfiguration clientConfig = testClientConfiguration() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFileSupplier) .build(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); assertThat(profileFileSupplier).isSameAs(executionAttributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER)); } @Test public void invokeInterceptorsAndCreateExecutionContext_withoutIdentityProviders_assignsNull() { ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); assertThat(executionAttributes.getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS)).isNull(); } @Test public void invokeInterceptorsAndCreateExecutionContext_requestOverrideForIdentityProvider_updatesIdentityProviders() { IdentityProvider<? extends AwsCredentialsIdentity> clientCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")); IdentityProviders identityProviders = IdentityProviders.builder().putIdentityProvider(clientCredentialsProvider).build(); SdkClientConfiguration clientConfig = testClientConfiguration() .option(SdkClientOption.IDENTITY_PROVIDERS, identityProviders) .build(); IdentityProvider<? extends AwsCredentialsIdentity> requestCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder().credentialsProvider(requestCredentialsProvider).build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); IdentityProviders actualIdentityProviders = executionContext.executionAttributes().getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS); IdentityProvider<AwsCredentialsIdentity> actualIdentityProvider = actualIdentityProviders.identityProvider(AwsCredentialsIdentity.class); assertThat(actualIdentityProvider).isSameAs(requestCredentialsProvider); } private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(sdkRequest) .withFullDuplex(false) .withOperationName("TestOperation"); } private SdkClientConfiguration.Builder testClientConfiguration() { // In real SRA case, SelectedAuthScheme is setup as an executionAttribute by {Service}AuthSchemeInterceptor that is setup // in EXECUTION_INTERCEPTORS. But, faking it here for unit test, by already setting SELECTED_AUTH_SCHEME into the // executionAttributes. SelectedAuthScheme<?> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk")), mock(HttpSigner.class), AuthSchemeOption.builder().schemeId(AwsV4AuthScheme.SCHEME_ID).build() ); ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, selectedAuthScheme) .build(); List<ExecutionInterceptor> interceptorList = Collections.singletonList(interceptor); return SdkClientConfiguration.builder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, interceptorList) .option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, defaultCredentialsProvider) .option(SdkClientOption.AUTH_SCHEMES, defaultAuthSchemes) .option(SdkClientOption.EXECUTION_ATTRIBUTES, executionAttributes); } private SdkClientConfiguration.Builder noAuthAuthSchemeClientConfiguration() { SdkClientConfiguration.Builder clientConfig = testClientConfiguration(); SelectedAuthScheme<?> selectedNoAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk")), mock(HttpSigner.class), AuthSchemeOption.builder().schemeId(NoAuthAuthScheme.SCHEME_ID).build() ); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) .putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, selectedNoAuthScheme); return clientConfig; } private SdkClientConfiguration.Builder preSraClientConfiguration() { SdkClientConfiguration.Builder clientConfiguration = testClientConfiguration(); clientConfiguration.option(SdkClientOption.EXECUTION_ATTRIBUTES) .putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); return clientConfiguration.option(SdkClientOption.AUTH_SCHEMES, null) .option(SdkAdvancedClientOption.SIGNER, this.defaultSigner); } }
1,480
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/CachedTokenRefresherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.atMost; 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 java.time.Duration; import java.time.Instant; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; public class CachedTokenRefresherTest { @Test public void doNotRefresh_when_valueIsNotStale() { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().plus(Duration.ofMillis(10000))).build(); TestToken token2 = TestToken.builder().token("token2").expirationDate(Instant.now().plus(Duration.ofMillis(900))).build(); when(supplier.get()).thenReturn(token1) .thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(99)) .tokenRetriever(supplier) .build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token1); } @Test public void refresh_when_valueIsStale() { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().minus(Duration.ofMillis(1))).build(); TestToken token2 = TestToken.builder().token("token2").expirationDate(Instant.now().plus(Duration.ofMillis(900))).build(); when(supplier.get()).thenReturn(token1) .thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(99)) .tokenRetriever(supplier) .build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token2); } @Test public void refreshTokenFails_when_exceptionHandlerThrowsBackException() { Function<RuntimeException, TestToken> fun = e -> { throw e; }; CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(fun) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); assertThatExceptionOfType(SdkException.class) .isThrownBy(() -> tokenRefresher.refreshIfStaleAndFetch()).withMessage("Auth Failure"); } @Test public void refreshTokenPasses_when_exceptionHandlerSkipsException() throws ExecutionException, InterruptedException { TestToken initialToken = getTestTokenBuilder().token("OldToken").expirationDate(Instant.now()).build(); CachedTokenRefresher<TestToken> tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(e -> initialToken) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); TestToken testToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(testToken).isEqualTo(initialToken); assertThat(testToken.token()).isEqualTo("OldToken"); assertThat(initialToken).isEqualTo(testToken); } @Test public void refreshTokenFails_when_baseTokenIsNotInTokenManagerWhileTokenFailedToObtainFromService() { Function<RuntimeException, TestToken> handleException = e -> { // handle Exception throws back another exception while handling the exception. throw new IllegalStateException("Unable to load token from Disc"); }; CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(handleException) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> tokenRefresher.refreshIfStaleAndFetch()).withMessage("Unable to load token from Disc"); } @Test public void autoRefresheToken_when_tokensExpire() throws InterruptedException { Supplier<TestToken> testTokenSupplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().minus(Duration.ofMillis(10000))).build(); TestToken token3 = TestToken.builder().token("token3").expirationDate(Instant.now().plus(Duration.ofDays(1))).build(); when(testTokenSupplier.get()).thenReturn(token1).thenReturn(token1).thenReturn(token3); CachedTokenRefresher tokenRefresher = CachedTokenRefresher.builder() .tokenRetriever(testTokenSupplier). staleDuration(Duration.ofMillis(100)) .prefetchTime(Duration.ofMillis(110)) .build(); Thread.sleep(400); verify(testTokenSupplier, atMost(3)).get(); } @Test public void prefetchToken_whenTokenNotStale_and_withinPrefetchTime() throws InterruptedException { Supplier<TestToken> mockCache = mock(Supplier.class); Instant startInstance = Instant.now(); TestToken firstToken = TestToken.builder().token("firstToken").expirationDate(startInstance.plusSeconds(1)).build(); TestToken secondToken = TestToken.builder().token("secondTokenWithinStaleTime").expirationDate(startInstance.plusSeconds(1)).build(); TestToken thirdToken = TestToken.builder().token("thirdTokenOutsidePrefetchTime").expirationDate(startInstance.plusMillis(1500)).build(); TestToken fourthToken = TestToken.builder().token("thirdTokenOutsidePrefetchTime").expirationDate(Instant.now().plusSeconds(6000)).build(); when(mockCache.get()).thenReturn(firstToken) .thenReturn(secondToken) .thenReturn(thirdToken) .thenReturn(fourthToken); CachedTokenRefresher cachedTokenRefresher = CachedTokenRefresher.builder() .asyncRefreshEnabled(true) .staleDuration(Duration.ofMillis(1000)) .tokenRetriever(mockCache) .prefetchTime(Duration.ofMillis(1500)) .build(); // Sleep is invoked to make sure executor executes refresh in initializeCachedSupplier() in NonBlocking CachedSupplier.PrefetchStrategy Thread.sleep(1000); verify(mockCache, times(0)).get(); SdkToken firstRetrieved = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRetrieved).isEqualTo(firstToken); Thread.sleep(1000); // Sleep to make sure the Async prefetch thread is picked up verify(mockCache, times(1)).get(); SdkToken secondRetrieved = cachedTokenRefresher.refreshIfStaleAndFetch(); // Note that since the token has already been prefetched mockCache.get() is not called again thus it is secondToken. assertThat(secondRetrieved).isEqualTo(secondToken); Thread.sleep(1000); // Sleep to make sure the Async prefetch thread is picked up verify(mockCache, times(2)).get(); SdkToken thirdRetrievedToken = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(thirdRetrievedToken).isEqualTo(thirdToken); // Sleep to make sure the Async prefetch thread is picked up Thread.sleep(1000); verify(mockCache, times(3)).get(); SdkToken fourthRetrievedToken = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(fourthRetrievedToken).isEqualTo(fourthToken); // Sleep to make sure the Async prefetch thread is picked up Thread.sleep(1000); verify(mockCache, times(4)).get(); SdkToken fifthToken = cachedTokenRefresher.refreshIfStaleAndFetch(); // Note that since Fourth token's expiry date is too high the prefetch is no longer done and the last fetch token is used. verify(mockCache, times(4)).get(); assertThat(fifthToken).isEqualTo(fourthToken); } @Test public void refreshEveryTime_when_ExpirationDateDoesNotExist() throws InterruptedException { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").build(); TestToken token2 = TestToken.builder().token("token2").build(); when(supplier.get()).thenReturn(token1).thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder().tokenRetriever(supplier).build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); Thread.sleep(1000); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token2); } private TestAwsResponse.Builder getDefaultTestAwsResponseBuilder() { return TestAwsResponse.builder().accessToken("serviceToken") .expiryTime(Instant.ofEpochMilli(1743680000000L)).startUrl("new_start_url"); } private CachedTokenRefresher.Builder tokenRefresherBuilder() { return CachedTokenRefresher.builder(); } private TestToken.Builder getTestTokenBuilder() { return TestToken.builder().token("sampleToken") .start_url("start_url"); } }
1,481
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/TestToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.time.Instant; import java.util.Optional; import software.amazon.awssdk.auth.token.credentials.SdkToken; public class TestToken implements SdkToken { private final String token; private final Instant expirationDate; private final String start_url; public static Builder builder() { return new Builder(); } public TestToken(Builder builder) { this.token = builder.token; this.start_url = builder.start_url; this.expirationDate = builder.expirationDate; } @Override public String token() { return token; } @Override public Optional<Instant> expirationTime() { return Optional.ofNullable(expirationDate); } public static class Builder { private String token; private Instant expirationDate; private String start_url; public Builder token(String token) { this.token = token; return this; } public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } public Builder start_url(String start_url) { this.start_url = start_url; return this; } public TestToken build() { return new TestToken(this); } } }
1,482
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/TestAwsResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.time.Instant; import java.util.List; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.SdkField; public class TestAwsResponse extends AwsResponse { private final String accessToken; private final Instant expiryTime; private final String startUrl; protected TestAwsResponse(Builder builder) { super(builder); this.accessToken = builder.accessToken; this.expiryTime = builder.expiryTime; this.startUrl = builder.startUrl; } public String getAccessToken() { return accessToken; } public Instant getExpiryTime() { return expiryTime; } public String getStartUrl() { return startUrl; } public static Builder builder(){ return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } @Override public List<SdkField<?>> sdkFields() { return null; } public static class Builder extends BuilderImpl{ public Builder() { } private String accessToken; private Instant expiryTime; private String startUrl; public Builder(TestAwsResponse testAwsResponse) { this.accessToken = testAwsResponse.accessToken; this.expiryTime = testAwsResponse.expiryTime; this.startUrl = testAwsResponse.startUrl; } public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } public Builder expiryTime(Instant expiryTime) { this.expiryTime = expiryTime; return this; } public Builder startUrl(String startUrl) { this.startUrl = startUrl; return this; } @Override public TestAwsResponse build() { return new TestAwsResponse(this); } } }
1,483
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/AutoDefaultsModeDiscoveryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; 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.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.JavaSystemSetting; @RunWith(Parameterized.class) public class AutoDefaultsModeDiscoveryTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Mobile new TestData().clientRegion(Region.US_EAST_1) .javaVendorProperty("The Android Project") .awsExecutionEnvVar("AWS_Lambda_java8") .awsRegionEnvVar("us-east-1") .expectedResolvedMode(DefaultsMode.MOBILE), // Region available from AWS execution environment new TestData().clientRegion(Region.US_EAST_1) .awsExecutionEnvVar("AWS_Lambda_java8") .awsRegionEnvVar("us-east-1") .expectedResolvedMode(DefaultsMode.IN_REGION), // Region available from AWS execution environment new TestData().clientRegion(Region.US_EAST_1) .awsExecutionEnvVar("AWS_Lambda_java8") .awsDefaultRegionEnvVar("us-west-2") .expectedResolvedMode(DefaultsMode.CROSS_REGION), // ImdsV2 available, in-region new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-east-1") .imdsAvailable(true)) .expectedResolvedMode(DefaultsMode.IN_REGION), // ImdsV2 available, cross-region new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-west-2") .imdsAvailable(true) .ec2MetadataDisabledEnvVar("false")) .expectedResolvedMode(DefaultsMode.CROSS_REGION), // Imdsv2 disabled, should not query ImdsV2 and use fallback mode new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-west-2") .imdsAvailable(true) .ec2MetadataDisabledEnvVar("true")) .expectedResolvedMode(DefaultsMode.STANDARD), // Imdsv2 not available, should use fallback mode. new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().imdsAvailable(false)) .expectedResolvedMode(DefaultsMode.STANDARD), }); } @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void methodSetup() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + wireMock.port()); } @After public void cleanUp() { EC2MetadataUtils.clearCache(); wireMock.resetAll(); ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.javaVendorProperty != null) { System.setProperty(JavaSystemSetting.JAVA_VENDOR.property(), testData.javaVendorProperty); } if (testData.awsExecutionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EXECUTION_ENV.environmentVariable(), testData.awsExecutionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove(SdkSystemSetting.AWS_EXECUTION_ENV.environmentVariable()); } if (testData.awsRegionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_REGION.environmentVariable(), testData.awsRegionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove(SdkSystemSetting.AWS_REGION.environmentVariable()); } if (testData.awsDefaultRegionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set("AWS_DEFAULT_REGION", testData.awsDefaultRegionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove("AWS_DEFAULT_REGION"); } if (testData.ec2MetadataConfig != null) { if (testData.ec2MetadataConfig.ec2MetadataDisabledEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.environmentVariable(), testData.ec2MetadataConfig.ec2MetadataDisabledEnvVar); } if (testData.ec2MetadataConfig.imdsAvailable) { stubSuccessfulResponse(testData.ec2MetadataConfig.region); } } Callable<DefaultsMode> result = () -> new AutoDefaultsModeDiscovery().discover(testData.clientRegion); assertThat(result.call()).isEqualTo(testData.expectedResolvedMode); } public void stubSuccessfulResponse(String region) { stubFor(put("/latest/api/token") .willReturn(aResponse().withStatus(200).withBody("token"))); stubFor(get("/latest/meta-data/placement/region") .willReturn(aResponse().withStatus(200).withBody(region))); } private static final class TestData { private Region clientRegion; private String javaVendorProperty; private String awsExecutionEnvVar; private String awsRegionEnvVar; private String awsDefaultRegionEnvVar; private Ec2MetadataConfig ec2MetadataConfig; private DefaultsMode expectedResolvedMode; public TestData clientRegion(Region clientRegion) { this.clientRegion = clientRegion; return this; } public TestData javaVendorProperty(String javaVendorProperty) { this.javaVendorProperty = javaVendorProperty; return this; } public TestData awsExecutionEnvVar(String awsExecutionEnvVar) { this.awsExecutionEnvVar = awsExecutionEnvVar; return this; } public TestData awsRegionEnvVar(String awsRegionEnvVar) { this.awsRegionEnvVar = awsRegionEnvVar; return this; } public TestData awsDefaultRegionEnvVar(String awsDefaultRegionEnvVar) { this.awsDefaultRegionEnvVar = awsDefaultRegionEnvVar; return this; } public TestData ec2MetadataConfig(Ec2MetadataConfig ec2MetadataConfig) { this.ec2MetadataConfig = ec2MetadataConfig; return this; } public TestData expectedResolvedMode(DefaultsMode expectedResolvedMode) { this.expectedResolvedMode = expectedResolvedMode; return this; } } private static final class Ec2MetadataConfig { private boolean imdsAvailable; private String region; private String ec2MetadataDisabledEnvVar; public Ec2MetadataConfig imdsAvailable(boolean imdsAvailable) { this.imdsAvailable = imdsAvailable; return this; } public Ec2MetadataConfig region(String region) { this.region = region; return this; } public Ec2MetadataConfig ec2MetadataDisabledEnvVar(String ec2MetadataDisabledEnvVar) { this.ec2MetadataDisabledEnvVar = ec2MetadataDisabledEnvVar; return this; } } }
1,484
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.utils.AttributeMap; public class DefaultsModeConfigurationTest { @Test public void defaultConfig_shouldPresentExceptLegacyAndAuto() { Arrays.stream(DefaultsMode.values()).forEach(m -> { if (m == DefaultsMode.LEGACY || m == DefaultsMode.AUTO) { assertThat(DefaultsModeConfiguration.defaultConfig(m)).isEqualTo(AttributeMap.empty()); assertThat(DefaultsModeConfiguration.defaultHttpConfig(m)).isEqualTo(AttributeMap.empty()); } else { assertThat(DefaultsModeConfiguration.defaultConfig(m)).isNotEqualTo(AttributeMap.empty()); assertThat(DefaultsModeConfiguration.defaultHttpConfig(m)).isNotEqualTo(AttributeMap.empty()); } }); } }
1,485
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeResolverTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class DefaultsModeResolverTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, DefaultsMode.LEGACY), new TestData(null, null, "PropertyNotSet", null, DefaultsMode.LEGACY), // Test resolution new TestData("legacy", null, null, null, DefaultsMode.LEGACY), new TestData("standard", null, null, null, DefaultsMode.STANDARD), new TestData("auto", null, null, null, DefaultsMode.AUTO), new TestData("lEgAcY", null, null, null, DefaultsMode.LEGACY), new TestData("sTanDaRd", null, null, null, DefaultsMode.STANDARD), new TestData("AUtO", null, null, null, DefaultsMode.AUTO), // Test precedence new TestData("standard", "legacy", "PropertySetToLegacy", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData("standard", null, null, DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, "standard", "PropertySetToLegacy", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, "standard", null, DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, null, "PropertySetToStandard", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, null, "PropertySetToAuto", DefaultsMode.LEGACY, DefaultsMode.AUTO), new TestData(null, null, null, DefaultsMode.STANDARD, DefaultsMode.STANDARD), // Test invalid values new TestData("wrongValue", null, null, null, IllegalArgumentException.class), new TestData(null, "wrongValue", null, null, IllegalArgumentException.class), new TestData(null, null, "PropertySetToUnsupportedValue", null, IllegalArgumentException.class), // Test capitalization standardization new TestData("sTaNdArD", null, null, null, DefaultsMode.STANDARD), new TestData(null, "sTaNdArD", null, null, DefaultsMode.STANDARD), new TestData(null, null, "PropertyMixedCase", null, DefaultsMode.STANDARD), }); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_DEFAULTS_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_DEFAULTS_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_DEFAULTS_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } Callable<DefaultsMode> result = DefaultsModeResolver.create().defaultMode(testData.defaultMode)::resolve; if (testData.expected instanceof Class<?>) { Class<?> expectedClassType = (Class<?>) testData.expected; assertThatThrownBy(result::call).isInstanceOf(expectedClassType); } else { assertThat(result.call()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String envVarValue; private final String systemProperty; private final String configFile; private final DefaultsMode defaultMode; private final Object expected; TestData(String systemProperty, String envVarValue, String configFile, DefaultsMode defaultMode, Object expected) { this.envVarValue = envVarValue; this.systemProperty = systemProperty; this.configFile = configFile; this.defaultMode = defaultMode; this.expected = expected; } } }
1,486
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/AwsCredentialsAuthorizationStrategyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import java.util.Optional; 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.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.metrics.MetricCollector; @RunWith(MockitoJUnitRunner.class) public class AwsCredentialsAuthorizationStrategyTest { @Mock SdkRequest sdkRequest; @Mock Signer defaultSigner; @Mock Signer requestOverrideSigner; AwsCredentialsProvider credentialsProvider; AwsCredentials credentials; @Mock MetricCollector metricCollector; @Before public void setUp() throws Exception { when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); credentials = AwsBasicCredentials.create("foo", "bar"); credentialsProvider = StaticCredentialsProvider.create(credentials); } @Test public void noOverrideSigner_returnsDefaultSigner() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(defaultSigner); } @Test public void overrideSigner_returnsOverrideSigner() { Optional cfg = Optional.of(requestOverrideConfiguration()); when(sdkRequest.overrideConfiguration()).thenReturn(cfg); AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(requestOverrideSigner); } @Test public void noDefaultSignerNoOverride_returnsNull() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(null) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isNull(); } @Test public void providerExists_credentialsAddedToExecutionAttributes() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); authorizationContext.addCredentialsToExecutionAttributes(executionAttributes); assertThat(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isEqualTo(credentials); } @Test public void noProvider_throwsError() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(null) .metricCollector(metricCollector) .build(); assertThatThrownBy(() -> authorizationContext.addCredentialsToExecutionAttributes(new ExecutionAttributes())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("No credentials provider exists to resolve credentials from."); } private AwsRequestOverrideConfiguration requestOverrideConfiguration() { return AwsRequestOverrideConfiguration.builder() .signer(requestOverrideSigner) .build(); } }
1,487
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/TokenAuthorizationStrategyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import java.util.Optional; 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.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.StaticTokenProvider; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.internal.token.TestToken; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.metrics.MetricCollector; @RunWith(MockitoJUnitRunner.class) public class TokenAuthorizationStrategyTest { private static final String TOKEN_VALUE = "token_value"; private SdkToken token; private SdkTokenProvider tokenProvider; @Mock SdkRequest sdkRequest; @Mock Signer defaultSigner; @Mock Signer requestOverrideSigner; @Mock MetricCollector metricCollector; @Before public void setUp() throws Exception { token = TestToken.builder().token(TOKEN_VALUE).build(); tokenProvider = StaticTokenProvider.create(token); when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); } @Test public void noOverrideSigner_returnsDefaultSigner() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(defaultSigner); } @Test public void overrideSigner_returnsOverrideSigner() { Optional cfg = Optional.of(requestOverrideConfiguration()); when(sdkRequest.overrideConfiguration()).thenReturn(cfg); TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(requestOverrideSigner); } @Test public void noDefaultSignerNoOverride_returnsNull() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(null) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isNull(); } @Test public void providerExists_credentialsAddedToExecutionAttributes() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); authorizationContext.addCredentialsToExecutionAttributes(executionAttributes); assertThat(executionAttributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isEqualTo(token); } @Test public void noProvider_throwsError() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(null) .metricCollector(metricCollector) .build(); assertThatThrownBy(() -> authorizationContext.addCredentialsToExecutionAttributes(new ExecutionAttributes())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("No token provider exists to resolve a token from."); } private AwsRequestOverrideConfiguration requestOverrideConfiguration() { return AwsRequestOverrideConfiguration.builder() .signer(requestOverrideSigner) .build(); } }
1,488
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategyFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.mockito.Mock; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.metrics.MetricCollector; public class AuthorizationStrategyFactoryTest { @Mock SdkRequest sdkRequest; @Mock MetricCollector metricCollector; @Test public void credentialTypeBearerToken_returnsTokenStrategy() { AuthorizationStrategyFactory factory = new AuthorizationStrategyFactory(sdkRequest, metricCollector, SdkClientConfiguration.builder().build()); AuthorizationStrategy authorizationStrategy = factory.strategyFor(CredentialType.TOKEN); assertThat(authorizationStrategy).isExactlyInstanceOf(TokenAuthorizationStrategy.class); } @Test public void credentialTypeAwsCredentials_returnsCredentialsStrategy() { AuthorizationStrategyFactory factory = new AuthorizationStrategyFactory(sdkRequest, metricCollector, SdkClientConfiguration.builder().build()); AuthorizationStrategy authorizationStrategy = factory.strategyFor(CredentialType.of("AWS")); assertThat(authorizationStrategy).isExactlyInstanceOf(AwsCredentialsAuthorizationStrategy.class); } }
1,489
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/checksum/AwsSignerWithChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.checksum; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.Optional; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import static org.assertj.core.api.Assertions.assertThat; public class AwsSignerWithChecksumTest { final String headerName = "x-amz-checksum-sha256"; final ChecksumSpecs SHA_256_HEADER = getCheckSum(Algorithm.SHA256, false, headerName); private final Aws4Signer signer = Aws4Signer.create(); private final AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); @Test public void signingWithChecksumWithSha256ShouldHaveChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(SHA_256_HEADER); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); final Optional<String> checksumHeader = signed.firstMatchingHeader(headerName); assertThat(checksumHeader).hasValue("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="); } @Test public void signingWithNoChecksumHeaderAlgorithmShouldNotAddChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(null); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); assertThat(signed.firstMatchingHeader(headerName)).isNotPresent(); } @Test public void signingWithNoChecksumShouldNotHaveChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(null); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); assertThat(signed.firstMatchingHeader(headerName)).isNotPresent(); } private ExecutionAttributes getExecutionAttributes(ChecksumSpecs checksumSpecs) { ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "demo") .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of("us-east-1")) .put(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, checksumSpecs) .build(); return executionAttributes; } private SdkHttpFullRequest.Builder generateBasicRequest(String stringInput) { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> { return new ByteArrayInputStream(stringInput.getBytes()); }) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } private ChecksumSpecs getCheckSum(Algorithm algorithm, boolean isStreamingRequest, String headerName) { return ChecksumSpecs.builder().algorithm(algorithm) .isRequestStreaming(isStreamingRequest).headerName(headerName).build(); } }
1,490
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsServiceExceptionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.DateUtils; public class AwsServiceExceptionTest { private static final int SKEWED_SECONDS = 60 * 60; private Instant unskewedDate = Instant.now(); private Instant futureSkewedDate = unskewedDate.plusSeconds(SKEWED_SECONDS); private Instant pastSkewedDate = unskewedDate.minusSeconds(SKEWED_SECONDS); @Test public void nonSkewErrorsAreIdentifiedCorrectly() { assertNotSkewed(0, "", 401, unskewedDate); assertNotSkewed(0, "", 403, unskewedDate); assertNotSkewed(0, "SignatureDoesNotMatch", 404, unskewedDate); assertNotSkewed(-SKEWED_SECONDS, "", 403, futureSkewedDate); assertNotSkewed(SKEWED_SECONDS, "", 403, pastSkewedDate); assertNotSkewed(0, "", 404, futureSkewedDate); assertNotSkewed(0, "", 404, pastSkewedDate); } @Test public void skewErrorsAreIdentifiedCorrectly() { assertSkewed(0, "RequestTimeTooSkewed", 404, unskewedDate); assertSkewed(0, "", 403, futureSkewedDate); assertSkewed(0, "", 401, futureSkewedDate); assertSkewed(0, "", 403, pastSkewedDate); assertSkewed(-SKEWED_SECONDS, "", 403, unskewedDate); assertSkewed(SKEWED_SECONDS, "", 403, unskewedDate); } @Test public void exceptionMessage_withExtendedRequestId() { AwsServiceException e = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorMessage("errorMessage") .serviceName("serviceName") .errorCode("errorCode") .build()) .statusCode(500) .requestId("requestId") .extendedRequestId("extendedRequestId") .build(); assertThat(e.getMessage()).isEqualTo("errorMessage (Service: serviceName, Status Code: 500, Request ID: requestId, " + "Extended Request ID: extendedRequestId)"); } @Test public void exceptionMessage_withoutExtendedRequestId() { AwsServiceException e = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorMessage("errorMessage") .serviceName("serviceName") .errorCode("errorCode") .build()) .statusCode(500) .requestId("requestId") .build(); assertThat(e.getMessage()).isEqualTo("errorMessage (Service: serviceName, Status Code: 500, Request ID: requestId)"); } public void assertSkewed(int clientSideTimeOffset, String errorCode, int statusCode, Instant serverDate) { AwsServiceException exception = exception(clientSideTimeOffset, errorCode, statusCode, DateUtils.formatRfc822Date(serverDate)); assertThat(exception.isClockSkewException()).isTrue(); } public void assertNotSkewed(int clientSideTimeOffset, String errorCode, int statusCode, Instant serverDate) { AwsServiceException exception = exception(clientSideTimeOffset, errorCode, statusCode, DateUtils.formatRfc822Date(serverDate)); assertThat(exception.isClockSkewException()).isFalse(); } private AwsServiceException exception(int clientSideTimeOffset, String errorCode, int statusCode, String serverDate) { SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(statusCode) .applyMutation(r -> { if (serverDate != null) { r.putHeader("Date", serverDate); } }) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode(errorCode) .sdkHttpResponse(httpResponse) .build(); return AwsServiceException.builder() .clockSkew(Duration.ofSeconds(clientSideTimeOffset)) .awsErrorDetails(errorDetails) .statusCode(statusCode) .build(); } }
1,491
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsServiceExceptionSerializationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.StringInputStream; public class AwsServiceExceptionSerializationTest { @Test public void serializeServiceException() throws Exception { AwsServiceException expectedException = createException(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(expectedException); objectOutputStream.flush(); objectOutputStream.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); AwsServiceException resultException = (AwsServiceException) ois.readObject(); assertSameValues(resultException, expectedException); } private void assertSameValues(AwsServiceException resultException, AwsServiceException expectedException) { assertThat(resultException.getMessage()).isEqualTo(expectedException.getMessage()); assertThat(resultException.requestId()).isEqualTo(expectedException.requestId()); assertThat(resultException.extendedRequestId()).isEqualTo(expectedException.extendedRequestId()); assertThat(resultException.toBuilder().clockSkew()).isEqualTo(expectedException.toBuilder().clockSkew()); assertThat(resultException.toBuilder().cause().getMessage()).isEqualTo(expectedException.toBuilder().cause().getMessage()); assertThat(resultException.awsErrorDetails()).isEqualTo(expectedException.awsErrorDetails()); } private AwsServiceException createException() { AbortableInputStream contentStream = AbortableInputStream.create(new StringInputStream("some content")); SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(403) .statusText("SomeText") .content(contentStream) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode("someCode") .errorMessage("message") .serviceName("someService") .sdkHttpResponse(httpResponse) .build(); return AwsServiceException.builder() .awsErrorDetails(errorDetails) .statusCode(403) .cause(new RuntimeException("someThrowable")) .clockSkew(Duration.ofSeconds(2)) .requestId("requestId") .extendedRequestId("extendedRequestId") .message("message") .build(); } }
1,492
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsErrorDetailsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class AwsErrorDetailsTest { @Test public void equals_hashcode() throws Exception { EqualsVerifier.forClass(AwsErrorDetails.class) .usingGetClass() .verify(); } }
1,493
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/utils/ValidSdkObjects.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.utils; import java.net.URI; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; /** * A collection of objects (or object builder) pre-populated with all required fields. This allows tests to focus on what data * they care about, not necessarily what data is required. */ public final class ValidSdkObjects { private ValidSdkObjects() {} public static SdkHttpFullRequest.Builder sdkHttpFullRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("http://test.com:80")) .method(SdkHttpMethod.GET); } public static SdkHttpFullResponse.Builder sdkHttpFullResponse() { return SdkHttpFullResponse.builder() .statusCode(200); } }
1,494
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/utils/HttpTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.utils; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Executors; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; public class HttpTestUtils { public static SdkHttpClient testSdkHttpClient() { return new DefaultSdkHttpClientBuilder().buildWithDefaults( AttributeMap.empty().merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)); } public static AmazonSyncHttpClient testAmazonHttpClient() { return testClientBuilder().httpClient(testSdkHttpClient()).build(); } public static TestClientBuilder testClientBuilder() { return new TestClientBuilder(); } public static SdkClientConfiguration testClientConfiguration() { return SdkClientConfiguration.builder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, new ArrayList<>()) .option(SdkClientOption.ENDPOINT, URI.create("http://localhost:8080")) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.defaultRetryPolicy()) .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, new HashMap<>()) .option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED, false) .option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, DefaultCredentialsProvider.create()) .option(SdkAdvancedClientOption.SIGNER, new NoOpSigner()) .option(SdkAdvancedClientOption.USER_AGENT_PREFIX, "") .option(SdkAdvancedClientOption.USER_AGENT_SUFFIX, "") .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE, Executors.newScheduledThreadPool(1)) .build(); } public static class TestClientBuilder { private RetryPolicy retryPolicy; private SdkHttpClient httpClient; public TestClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public TestClientBuilder httpClient(SdkHttpClient sdkHttpClient) { this.httpClient = sdkHttpClient; return this; } public AmazonSyncHttpClient build() { SdkHttpClient sdkHttpClient = this.httpClient != null ? this.httpClient : testSdkHttpClient(); return new AmazonSyncHttpClient(testClientConfiguration().toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .applyMutation(this::configureRetryPolicy) .build()); } private void configureRetryPolicy(SdkClientConfiguration.Builder builder) { if (retryPolicy != null) { builder.option(SdkClientOption.RETRY_POLICY, retryPolicy); } } } }
1,495
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/http/NoopTestAwsRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.http; import java.util.Collections; import java.util.List; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; public class NoopTestAwsRequest extends AwsRequest { private NoopTestAwsRequest(Builder builder) { super(builder); } @Override public Builder toBuilder() { return new BuilderImpl(); } public static Builder builder() { return new BuilderImpl(); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public interface Builder extends AwsRequest.Builder { @Override NoopTestAwsRequest build(); @Override Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig); } private static class BuilderImpl extends AwsRequest.BuilderImpl implements Builder { @Override public NoopTestAwsRequest build() { return new NoopTestAwsRequest(this); } @Override public Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig) { super.overrideConfiguration(awsRequestOverrideConfig); return this; } } }
1,496
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/endpoint/DefaultServiceEndpointBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.endpoint; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; public class DefaultServiceEndpointBuilderTest { @Test public void getServiceEndpoint_S3StandardRegion_HttpsProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "https") .withRegion(Region.US_EAST_1); assertEquals("https://s3.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_S3StandardRegion_HttpProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.US_EAST_1); assertEquals("http://s3.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_S3NonStandardRegion_HttpProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.EU_CENTRAL_1); assertEquals("http://s3.eu-central-1.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_regionalOption_shouldUseRegionalEndpoint() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.US_EAST_1).putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional"); assertEquals("http://s3.us-east-1.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } }
1,497
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/FipsPseudoRegionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; 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.when; import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; public class FipsPseudoRegionTest { private static final AttributeMap MOCK_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "s3"; private static final String SIGNING_NAME = "demo"; private static final String SERVICE_NAME = "Demo"; private SdkHttpClient.Builder defaultHttpClientBuilder; @BeforeEach public void setup() { defaultHttpClientBuilder = mock(SdkHttpClient.Builder.class); when(defaultHttpClientBuilder.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class)); } @ParameterizedTest @MethodSource("testCases") public void verifyRegion(TestCase tc) { TestClient client = testClientBuilder().region(tc.inputRegion).build(); assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(tc.expectedClientRegion); assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue(); } public static List<TestCase> testCases() { List<TestCase> testCases = new ArrayList<>(); testCases.add(new TestCase(Region.of("fips-us-west-2"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("us-west-2-fips"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("rekognition-fips.us-west-2"), Region.of("rekognition.us-west-2"))); testCases.add(new TestCase(Region.of("rekognition.fips-us-west-2"), Region.of("rekognition.us-west-2"))); testCases.add(new TestCase(Region.of("query-fips-us-west-2"), Region.of("query-us-west-2"))); testCases.add(new TestCase(Region.of("fips-fips-us-west-2"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("fips-us-west-2-fips"), Region.of("us-west-2"))); return testCases; } private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, mock(Signer.class)) .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private static class TestCase { private Region inputRegion; private Region expectedClientRegion; public TestCase(Region inputRegion, Region expectedClientRegion) { this.inputRegion = inputRegion; this.expectedClientRegion = expectedClientRegion; } } private static class TestClient { private final SdkClientConfiguration clientConfiguration; public TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient> implements AwsClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientBuilder, null, null); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return MOCK_DEFAULTS; } } }
1,498
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/DefaultsModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; 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.when; import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION; import static software.amazon.awssdk.awscore.client.config.AwsClientOption.DEFAULTS_MODE; import static software.amazon.awssdk.core.client.config.SdkClientOption.DEFAULT_RETRY_MODE; import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY; import static software.amazon.awssdk.regions.ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT; import java.time.Duration; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; @RunWith(MockitoJUnitRunner.class) public class DefaultsModeTest { private static final AttributeMap SERVICE_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "test"; private static final String SIGNING_NAME = "test"; private static final String SERVICE_NAME = "test"; @Mock private SdkHttpClient.Builder defaultHttpClientBuilder; @Mock private SdkAsyncHttpClient.Builder defaultAsyncHttpClientBuilder; @Mock private AutoDefaultsModeDiscovery autoModeDiscovery; @Test public void defaultClient_shouldUseLegacyModeWithExistingDefaults() { TestClient client = testClientBuilder() .region(Region.US_WEST_2) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { assertThat(serviceDefaults).isEqualTo(SERVICE_DEFAULTS); return mock(SdkHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(DefaultsMode.LEGACY); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(RetryMode.defaultRetryMode()); assertThat(client.clientConfiguration.option(DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)).isNull(); } @Test public void nonLegacyDefaultsMode_shouldApplySdkDefaultsAndHttpDefaults() { DefaultsMode targetMode = DefaultsMode.IN_REGION; TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(targetMode) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { AttributeMap defaultHttpConfig = DefaultsModeConfiguration.defaultHttpConfig(targetMode); AttributeMap mergedDefaults = SERVICE_DEFAULTS.merge(defaultHttpConfig); assertThat(serviceDefaults).isEqualTo(mergedDefaults); return mock(SdkHttpClient.class); }).build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(targetMode); AttributeMap attributes = DefaultsModeConfiguration.defaultConfig(targetMode); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(attributes.get(DEFAULT_RETRY_MODE)); assertThat(client.clientConfiguration.option(DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)).isEqualTo("regional"); } @Test public void nonLegacyDefaultsModeAsyncClient_shouldApplySdkDefaultsAndHttpDefaults() { DefaultsMode targetMode = DefaultsMode.IN_REGION; TestAsyncClient client = testAsyncClientBuilder().region(Region.US_WEST_1) .defaultsMode(targetMode) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { AttributeMap defaultHttpConfig = DefaultsModeConfiguration.defaultHttpConfig(targetMode); AttributeMap mergedDefaults = SERVICE_DEFAULTS.merge(defaultHttpConfig); assertThat(serviceDefaults).isEqualTo(mergedDefaults); return mock(SdkHttpClient.class); }).build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(targetMode); AttributeMap attributes = DefaultsModeConfiguration.defaultConfig(targetMode); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(attributes.get(DEFAULT_RETRY_MODE)); } @Test public void clientOverrideRetryMode_shouldTakePrecedence() { TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(DefaultsMode.IN_REGION) .overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(DefaultsMode.IN_REGION); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(RetryMode.LEGACY); } @Test public void autoMode_shouldResolveDefaultsMode() { DefaultsMode expectedMode = DefaultsMode.IN_REGION; when(autoModeDiscovery.discover(any(Region.class))).thenReturn(expectedMode); TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(DefaultsMode.AUTO) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(expectedMode); } private static class TestClient { private final SdkClientConfiguration clientConfiguration; public TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestAsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient> implements AwsClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientBuilder, defaultAsyncHttpClientBuilder, autoModeDiscovery); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return SERVICE_DEFAULTS; } } private class TestAsyncClientBuilder extends AwsDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> implements AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> { public TestAsyncClientBuilder() { super(defaultHttpClientBuilder, defaultAsyncHttpClientBuilder, autoModeDiscovery); } @Override protected TestAsyncClient buildClient() { return new TestAsyncClient(super.asyncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return SERVICE_DEFAULTS; } } private static class TestAsyncClient { private final SdkClientConfiguration clientConfiguration; private TestAsyncClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } }
1,499