GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — HTTP/2: Fix stream stall when toggling auto-read on a child channel (… · lltopk/netty@ee269f5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-http2/src
    • main/java/io/netty/handler/codec/http2
      • AbstractHttp2StreamChannel.java
    • test/java/io/netty/handler/codec/http2
      • Http2MultiplexTest.java
      • Http2MultiplexTransportTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java‎

Copy file name to clipboardExpand all lines: codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java
+47-12Lines changed: 47 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -600,10 +600,11 @@ void fireChildRead(Http2Frame frame) {
600600
assert eventLoop().inEventLoop();
601601
if (!isActive()) {
602602
ReferenceCountUtil.release(frame);
603-
} else if (readStatus != ReadStatus.IDLE) {
604-
// If a read is in progress or has been requested, there cannot be anything in the queue,
605-
// otherwise we would have drained it from the queue and processed it during the read cycle.
606-
assert inboundBuffer == null || inboundBuffer.isEmpty();
603+
} else if (readStatus != ReadStatus.IDLE && isInboundBufferEmpty()) {
604+
// A read is in progress or has been requested and nothing is queued, so dispatch directly. If frames are
605+
// still queued (e.g. this frame was delivered re-entrantly while doBeginRead() is running pipeline
606+
// callbacks after it stopped early) we must queue behind them below to preserve ordering; the read loop
607+
// that is still on the stack will drain them.
607608
final RecvByteBufAllocator.Handle allocHandle = unsafe.recvBufAllocHandle();
608609

609610
unsafe.doRead0(frame, allocHandle);
@@ -624,6 +625,10 @@ void fireChildRead(Http2Frame frame) {
624625
}
625626
}
626627

628+
private boolean isInboundBufferEmpty() {
629+
return inboundBuffer == null || inboundBuffer.isEmpty();
630+
}
631+
627632
void fireChildReadComplete() {
628633
assert eventLoop().inEventLoop();
629634
assert readStatus != ReadStatus.IDLE || !readCompletePending;
@@ -850,19 +855,39 @@ public void beginRead() {
850855
if (!isActive()) {
851856
return;
852857
}
853-
updateLocalWindowIfNeeded();
858+
final boolean windowUpdated = updateLocalWindowIfNeeded();
854859

855860
switch (readStatus) {
856861
case IDLE:
857862
readStatus = ReadStatus.IN_PROGRESS;
863+
// doBeginRead() always flushes (or defers to the parent's read-complete flush).
858864
doBeginRead();
859-
break;
865+
return;
860866
case IN_PROGRESS:
861867
readStatus = ReadStatus.REQUESTED;
862868
break;
863869
default:
864870
break;
865871
}
872+
if (windowUpdated) {
873+
// A WINDOW_UPDATE was just written above, but no read loop runs in this branch to flush it, so an
874+
// unflushed frame here can stall the remote peer forever (netty/netty#17600).
875+
//
876+
// flush() alone is not enough: it no-ops while isParentReadInProgress(), since
877+
// Http2MultiplexHandler batches all children's flushes into one ctx.flush() at the end of its read
878+
// loop (processPendingReadCompleteQueue()) -- but that batched flush only runs if some channel
879+
// registered via maybeAddChannelToReadCompletePendingQueue(), which doBeginRead()/fireChildRead()
880+
// do but this branch doesn't. If a cross-thread setAutoRead(true) lands here as the only activity
881+
// in the parent's read loop, the queue stays empty, the end-of-loop flush is skipped, and this
882+
// WINDOW_UPDATE (flowControlledBytes already zeroed) is never retried -- permanent stall.
883+
//
884+
// So register into that queue while the parent is reading; otherwise flush immediately.
885+
if (isParentReadInProgress()) {
886+
maybeAddChannelToReadCompletePendingQueue();
887+
} else {
888+
flush();
889+
}
890+
}
866891
}
867892

868893
private Object pollQueuedMessage() {
@@ -872,20 +897,23 @@ private Object pollQueuedMessage() {
872897
void doBeginRead() {
873898
if (readStatus == ReadStatus.IDLE) {
874899
// Don't wait for the user to request a read to notify of channel closure.
875-
if (readEOS && (inboundBuffer == null || inboundBuffer.isEmpty())) {
900+
if (readEOS && isInboundBufferEmpty()) {
876901
// Double check there is nothing left to flush such as a window update frame.
877902
flush();
878-
unsafe.closeForcibly();
903+
closeIfReadEOSAndDrained();
879904
}
880905
} else {
881906
do { // Process messages until there are none left (or the user stopped requesting) and also handle EOS.
882907
Object message = pollQueuedMessage();
883908
if (message == null) {
884909
// Double check there is nothing left to flush such as a window update frame.
885910
flush();
886-
if (readEOS) {
887-
unsafe.closeForcibly();
911+
if (!isInboundBufferEmpty()) {
912+
// The flush re-entrantly delivered more frames which got queued; keep reading if we
913+
// still should.
914+
continue;
888915
}
916+
closeIfReadEOSAndDrained();
889917
break;
890918
}
891919
final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle();
@@ -957,8 +985,15 @@ void notifyReadComplete(RecvByteBufAllocator.Handle allocHandle, boolean forceRe
957985
// channel is not currently reading we need to force a flush at the child channel, because we cannot
958986
// rely upon flush occurring in channelReadComplete on the parent channel.
959987
flush();
960-
if (readEOS) {
961-
unsafe.closeForcibly();
988+
closeIfReadEOSAndDrained();
989+
}
990+
991+
private void closeIfReadEOSAndDrained() {
992+
// Pipeline callbacks and flush() can re-entrantly deliver more frames, including the one that ends the
993+
// stream, and queue them if the user stopped reading. Only close once all of them have been read,
994+
// otherwise the queued frames would be released and the stream silently truncated.
995+
if (readEOS && isInboundBufferEmpty()) {
996+
closeForcibly();
962997
}
963998
}
964999

Collapse file

‎codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java‎

Copy file name to clipboardExpand all lines: codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexTest.java
+132Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,138 @@ public void windowUpdatesSendWhenAutoReadEnabled() {
16801680
assertTrue(flushSniffer.checkFlush());
16811681
}
16821682

1683+
@Test
1684+
public void windowUpdateFlushedWhenReadRequestedWhileReadInProgress() {
1685+
LastInboundHandler inboundHandler = new LastInboundHandler();
1686+
FlushSniffer flushSniffer = new FlushSniffer();
1687+
parentChannel.pipeline().addFirst(flushSniffer);
1688+
1689+
Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);
1690+
assertTrue(childChannel.config().isAutoRead());
1691+
Http2HeadersFrame headersFrame = inboundHandler.readInbound();
1692+
assertNotNull(headersFrame);
1693+
1694+
// Each round: a read() is requested while the child is waiting for data (the same thing a
1695+
// setAutoRead(false) -> setAutoRead(true) flip does), auto-read is disabled again, and then a DATA frame
1696+
// arrives. The frame is still delivered because a read was pending, but its bytes are not returned yet.
1697+
for (int i = 0; i < 2; i++) {
1698+
childChannel.config().setAutoRead(false);
1699+
childChannel.config().setAutoRead(true);
1700+
childChannel.config().setAutoRead(false);
1701+
frameInboundWriter.writeInboundData(childChannel.stream().id(), bb(16 * 1024), 0, false);
1702+
verifyFramesMultiplexedToCorrectChannel(childChannel, inboundHandler, 1);
1703+
}
1704+
verify(frameWriter, never()).writeWindowUpdate(eqCodecCtx(), anyInt(), anyInt(), anyChannelPromise());
1705+
flushSniffer.checkFlush();
1706+
1707+
// Re-enabling auto-read triggers a read() which returns the consumed bytes to the flow controller. That
1708+
// results in a wire-level WINDOW_UPDATE which must be flushed, otherwise the remote peer may stall forever
1709+
// once its send window is exhausted.
1710+
childChannel.config().setAutoRead(true);
1711+
verify(frameWriter).writeWindowUpdate(eqCodecCtx(), eq(0), eq(32 * 1024), anyChannelPromise());
1712+
verify(frameWriter).writeWindowUpdate(
1713+
eqCodecCtx(), eq(childChannel.stream().id()), eq(32 * 1024), anyChannelPromise());
1714+
assertTrue(flushSniffer.checkFlush(), "WINDOW_UPDATE was written but never flushed");
1715+
}
1716+
1717+
@Test
1718+
public void framesDeliveredReentrantlyWhileFramesQueuedAreNotReordered() {
1719+
final LastInboundHandler inboundHandler = new LastInboundHandler();
1720+
final Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);
1721+
assertNotNull(inboundHandler.readInbound());
1722+
final int streamId = childChannel.stream().id();
1723+
1724+
// Queue two frames while auto-read is disabled. The first is dispatched immediately as a read was pending.
1725+
childChannel.config().setAutoRead(false);
1726+
frameInboundWriter.writeInboundData(streamId, bb(1), 0, false);
1727+
assertDataFrame(inboundHandler, 1, false);
1728+
frameInboundWriter.writeInboundData(streamId, bb(2), 0, false);
1729+
frameInboundWriter.writeInboundData(streamId, bb(3), 0, false);
1730+
assertNull(inboundHandler.readInbound());
1731+
1732+
// Stop reading again after the first queued frame, and have a new frame arrive re-entrantly (e.g. because a
1733+
// flush synchronously triggered the remote peer to send more) while the read loop is still completing.
1734+
final AtomicBoolean armed = new AtomicBoolean(true);
1735+
childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {
1736+
@Override
1737+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
1738+
ctx.channel().config().setAutoRead(false);
1739+
ctx.fireChannelRead(msg);
1740+
}
1741+
1742+
@Override
1743+
public void channelReadComplete(ChannelHandlerContext ctx) {
1744+
if (armed.getAndSet(false)) {
1745+
frameInboundWriter.writeInboundData(streamId, bb(4), 0, false);
1746+
}
1747+
ctx.fireChannelReadComplete();
1748+
}
1749+
});
1750+
childChannel.config().setAutoRead(true);
1751+
assertDataFrame(inboundHandler, 2, false);
1752+
assertNull(inboundHandler.readInbound());
1753+
1754+
// The re-entrant frame must be delivered after the frame that was already queued.
1755+
childChannel.read();
1756+
assertDataFrame(inboundHandler, 3, false);
1757+
childChannel.read();
1758+
assertDataFrame(inboundHandler, 4, false);
1759+
assertNull(inboundHandler.readInbound());
1760+
}
1761+
1762+
@Test
1763+
public void endOfStreamDeliveredReentrantlyDoesNotDropQueuedFrames() {
1764+
final LastInboundHandler inboundHandler = new LastInboundHandler();
1765+
final Http2StreamChannel childChannel = newInboundStream(3, false, inboundHandler);
1766+
assertNotNull(inboundHandler.readInbound());
1767+
final int streamId = childChannel.stream().id();
1768+
// Half-close our side so that receiving END_STREAM fully closes the stream.
1769+
assertTrue(childChannel.writeAndFlush(
1770+
new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), true)).isSuccess());
1771+
1772+
childChannel.config().setAutoRead(false);
1773+
frameInboundWriter.writeInboundData(streamId, bb(1), 0, false);
1774+
assertDataFrame(inboundHandler, 1, false);
1775+
frameInboundWriter.writeInboundData(streamId, bb(2), 0, false);
1776+
assertNull(inboundHandler.readInbound());
1777+
1778+
// While the read loop completes, stop reading and have the rest of the stream (including END_STREAM)
1779+
// arrive re-entrantly. The last frame gets queued and the stream is closed at the HTTP/2 level.
1780+
final AtomicBoolean armed = new AtomicBoolean(true);
1781+
childChannel.pipeline().addFirst(new ChannelInboundHandlerAdapter() {
1782+
@Override
1783+
public void channelReadComplete(ChannelHandlerContext ctx) {
1784+
if (armed.getAndSet(false)) {
1785+
ctx.channel().config().setAutoRead(false);
1786+
frameInboundWriter.writeInboundData(streamId, bb(3), 0, false);
1787+
frameInboundWriter.writeInboundData(streamId, bb(4), 0, true);
1788+
}
1789+
ctx.fireChannelReadComplete();
1790+
}
1791+
});
1792+
childChannel.config().setAutoRead(true);
1793+
assertDataFrame(inboundHandler, 2, false);
1794+
assertDataFrame(inboundHandler, 3, false);
1795+
assertNull(inboundHandler.readInbound());
1796+
1797+
// The queued END_STREAM frame must not be dropped by closing the channel early.
1798+
assertTrue(childChannel.isActive());
1799+
childChannel.read();
1800+
assertDataFrame(inboundHandler, 4, true);
1801+
assertFalse(childChannel.isActive());
1802+
}
1803+
1804+
private static void assertDataFrame(LastInboundHandler inboundHandler, int expectedBytes, boolean endStream) {
1805+
Http2DataFrame frame = inboundHandler.readInbound();
1806+
assertNotNull(frame, "expected a DATA frame with " + expectedBytes + " bytes");
1807+
try {
1808+
assertEquals(expectedBytes, frame.content().readableBytes());
1809+
assertEquals(endStream, frame.isEndStream());
1810+
} finally {
1811+
frame.release();
1812+
}
1813+
}
1814+
16831815
@ParameterizedTest(name = "{displayName} [{index}] value={0}")
16841816
@MethodSource("userEvents")
16851817
public void userEventsThatPropagatedToChildChannels(Object userEvent) {

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.