Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "bugfix",
"category": "Netty NIO HTTP Client",
"description": "Fixed an issue where HTTP/2 requests without a body could fail with a stream reset after the server had already sent a complete response. Such requests now send END_STREAM on the HEADERS frame.",
"contributor": "crliao"
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpContent;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest;
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.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
Expand Down Expand Up @@ -241,14 +245,30 @@ private void makeRequest() {
}

private void writeRequest(HttpRequest request) {
if (shouldWriteAsEmptyFullRequest(request)) {
// Still subscribe to the (empty) request publisher: some bodies, e.g.
// AsyncRequestBody.forBlockingInputStream(0L), block their producer until they are subscribed to.
context.executeRequest().requestContentPublisher().subscribe(new EmptyBodySubscriber(request));
return;
}
writeToChannel(new StreamedRequest(request, context.executeRequest().requestContentPublisher()));
}

private void writeToChannel(HttpRequest requestToWrite) {
addWriteTimeoutHandlers();
StreamedRequest streamedRequest = new StreamedRequest(request,
context.executeRequest().requestContentPublisher());

channel.writeAndFlush(streamedRequest)
channel.writeAndFlush(requestToWrite)
.addListener(wireCall -> {
// Done writing so remove the idle write timeout handler
removeWriteTimeoutHandlers();
if (!wireCall.isSuccess() && isResponseCompletedSuccessfully()) {
// The server may respond and close/reset the stream before our END_STREAM has been written
// (e.g. RST_STREAM(NO_ERROR), RFC 9113 section 8.1). The response has already been delivered
// and the channel released, so this late write failure must not fail the request.
log.debug(channel, () -> "Ignoring request write failure after the response completed for "
+ endpoint(), wireCall.cause());
return;
}
if (wireCall.isSuccess()) {
NettyRequestMetrics.publishHttp2StreamMetrics(context.metricCollector(), channel);

Expand Down Expand Up @@ -284,6 +304,121 @@ private void writeRequest(HttpRequest request) {
}
}

private boolean isResponseCompletedSuccessfully() {
return executeFuture.isDone() && !executeFuture.isCompletedExceptionally();
}

/**
* For HTTP/2 requests without a body, send a single HEADERS frame with END_STREAM instead of HEADERS followed by
* a separate empty DATA(END_STREAM) frame. Otherwise the server can respond and reset the stream before the
* trailing empty DATA frame is written, which fails a request whose response was already received.
*/
private boolean shouldWriteAsEmptyFullRequest(HttpRequest request) {
if (ChannelAttributeKey.getProtocolNow(channel) != Protocol.HTTP2
|| context.executeRequest().fullDuplex()
|| is100ContinueExpected()) {
return false;
}
Optional<Long> publisherLength = context.executeRequest().requestContentPublisher().contentLength();
if (!publisherLength.isPresent() || publisherLength.get() != 0L) {
return false;
}
String contentLength = request.headers().get(HttpHeaderNames.CONTENT_LENGTH);
return (contentLength == null || "0".equals(contentLength.trim()))
&& !request.headers().contains(HttpHeaderNames.TRANSFER_ENCODING);
}

private static FullHttpRequest toEmptyFullRequest(HttpRequest request) {
return new DefaultFullHttpRequest(request.protocolVersion(), request.method(), request.uri(),
Unpooled.EMPTY_BUFFER, request.headers(), EmptyHttpHeaders.INSTANCE);
}

/**
* Drives the lifecycle of a request publisher that declared a zero content length, then writes the request as a
* single {@link FullHttpRequest} (HEADERS with END_STREAM) once the publisher completes. Publisher errors fail the
* request, and the subscription is cancelled if the request fails or is cancelled first.
*/
private final class EmptyBodySubscriber implements Subscriber<ByteBuffer> {
private final HttpRequest request;
private final boolean contentLengthHeaderPresent;
private Subscription subscription;
private boolean done;

private EmptyBodySubscriber(HttpRequest request) {
this.request = request;
this.contentLengthHeaderPresent = request.headers().contains(HttpHeaderNames.CONTENT_LENGTH);
}

@Override
public void onSubscribe(Subscription s) {
if (subscription != null) {
s.cancel();
return;
}
subscription = s;
executeFuture.whenComplete((r, t) -> {
if (t != null) {
s.cancel();
}
});
s.request(Long.MAX_VALUE);
}

@Override
public void onNext(ByteBuffer byteBuffer) {
if (done || !byteBuffer.hasRemaining()) {
return;
}
subscription.cancel();
if (contentLengthHeaderPresent) {
// Same as StreamedRequest: content beyond the declared Content-Length (0) is not sent.
complete();
} else {
onError(new IllegalStateException("Request content publisher declared a content length of 0 but "
+ "published " + byteBuffer.remaining() + " bytes."));
}
}

@Override
public void onError(Throwable t) {
if (done) {
return;
}
done = true;
NettyUtils.doInEventLoop(channel.eventLoop(), () -> {
if (executeFuture.isDone()) {
// The request already completed or was cancelled; the publisher error raced with it.
return;
}
closeAndRelease(channel);
handleFailure(channel, () -> "Failed to read request content for " + endpoint(), t);
});
}

@Override
public void onComplete() {
complete();
}

private void complete() {
if (done) {
return;
}
done = true;
NettyUtils.doInEventLoop(channel.eventLoop(), () -> {
if (executeFuture.isDone()) {
return;
}
try {
writeToChannel(toEmptyFullRequest(request));
} catch (Throwable t) {
closeAndRelease(channel);
handleFailure(channel, () -> "Failed to make request to " + endpoint(), t);
}
});
}
}

private void removeWriteTimeoutHandlers() {
ChannelUtils.removeIfExists(channel.pipeline(), WriteTimeoutHandler.class,
WriteIdleTimeoutHandler.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,10 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)

// 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());
endStream = msg instanceof FullHttpMessage
&& !((FullHttpMessage) msg).content().isReadable()
&& ((FullHttpMessage) msg).trailingHeaders().isEmpty();
ctx.write(new DefaultHttp2HeadersFrame(http2Headers, endStream), promiseAggregator.newPromise());

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2Headers;
Expand Down Expand Up @@ -174,7 +175,8 @@ private class MightReturn500StreamFrameHandler extends SimpleChannelInboundHandl

@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
if (frame instanceof Http2DataFrame
|| (frame instanceof Http2HeadersFrame && ((Http2HeadersFrame) frame).isEndStream())) {
DefaultHttp2DataFrame dataFrame = new DefaultHttp2DataFrame(true);

// returning 500 this is channel 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
Expand Down Expand Up @@ -241,16 +242,17 @@ private static final class StreamHandler extends SimpleChannelInboundHandler<Htt

@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame http2Frame) throws Exception {
if (http2Frame instanceof Http2DataFrame) {
Http2DataFrame dataFrame = (Http2DataFrame) http2Frame;
if (dataFrame.isEndStream()) {
Http2Headers headers = new DefaultHttp2Headers().status("200");
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false));
ctx.executor().scheduleAtFixedRate(() -> {
DefaultHttp2DataFrame respData = new DefaultHttp2DataFrame(Unpooled.wrappedBuffer("hello".getBytes()), false);
ctx.writeAndFlush(respData);
}, 0, 2, TimeUnit.SECONDS);
}
// Bodyless requests end the stream on the HEADERS frame; others end it with a DATA frame.
boolean requestEnded =
(http2Frame instanceof Http2DataFrame && ((Http2DataFrame) http2Frame).isEndStream())
|| (http2Frame instanceof Http2HeadersFrame && ((Http2HeadersFrame) http2Frame).isEndStream());
if (requestEnded) {
Http2Headers headers = new DefaultHttp2Headers().status("200");
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(headers, false));
ctx.executor().scheduleAtFixedRate(() -> {
DefaultHttp2DataFrame respData = new DefaultHttp2DataFrame(Unpooled.wrappedBuffer("hello".getBytes()), false);
ctx.writeAndFlush(respData);
}, 0, 2, TimeUnit.SECONDS);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
Expand Down Expand Up @@ -220,7 +221,8 @@ private class MightCloseConnectionStreamFrameHandler extends SimpleChannelInboun

@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
if (frame instanceof Http2DataFrame
|| (frame instanceof Http2HeadersFrame && ((Http2HeadersFrame) frame).isEndStream())) {
// Not respond if this is channel 1
if (channelIds[0].equals(ctx.channel().parent().id().asShortText()) && failOnFirstChannel) {
ctx.channel().parent().close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import io.netty.handler.codec.http2.DefaultHttp2PingFrame;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2Frame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
Expand Down Expand Up @@ -261,7 +262,8 @@ private class MightNotRespondStreamFrameHandler extends SimpleChannelInboundHand

@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) {
if (frame instanceof Http2DataFrame) {
if (frame instanceof Http2DataFrame
|| (frame instanceof Http2HeadersFrame && ((Http2HeadersFrame) frame).isEndStream())) {
// Not respond if this is channel 1
if (channelIds[0].equals(ctx.channel().parent().id().asShortText()) && notRespondOnFirstChannel) {
LOGGER.info(() -> "This is the first request, not responding" + ctx.channel());
Expand Down
Loading