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 — FlowControlHandler: Fix channelReadComplete behaviour · netty/netty@08ec40a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-http/src/test/java/io/netty/handler/codec/http
    • HttpContentDecompressorTest.java
  • handler/src
    • main/java/io/netty/handler/flow
      • FlowControlHandler.java
    • test/java/io/netty/handler/flow
      • FlowControlHandlerTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecompressorTest.java‎

Copy file name to clipboardExpand all lines: codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecompressorTest.java
+46-1Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
*/
1616
package io.netty.handler.codec.http;
1717

18-
import io.netty.buffer.AdaptiveByteBufAllocator;
1918
import io.netty.buffer.ByteBuf;
2019
import io.netty.buffer.PooledByteBufAllocator;
2120
import io.netty.buffer.Unpooled;
@@ -25,6 +24,8 @@
2524
import io.netty.channel.embedded.EmbeddedChannel;
2625
import io.netty.handler.codec.compression.Brotli;
2726
import io.netty.handler.codec.compression.Zstd;
27+
import io.netty.handler.flow.FlowControlHandler;
28+
import io.netty.util.ReferenceCountUtil;
2829
import io.netty.util.test.DisabledForSlowLeakDetection;
2930
import org.junit.jupiter.api.Test;
3031
import org.junit.jupiter.params.ParameterizedTest;
@@ -81,6 +82,50 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
8182
assertFalse(channel.finishAndReleaseAll());
8283
}
8384

85+
// See https://github.com/netty/netty/issues/15053.
86+
@Test
87+
public void testFlowControlHandlerEmitsOneMessagePerRead() {
88+
final AtomicInteger reads = new AtomicInteger();
89+
final AtomicInteger readCompletes = new AtomicInteger();
90+
EmbeddedChannel channel = new EmbeddedChannel(
91+
new FlowControlHandler(),
92+
new HttpContentDecompressor(0),
93+
new ChannelInboundHandlerAdapter() {
94+
@Override
95+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
96+
reads.incrementAndGet();
97+
ReferenceCountUtil.release(msg);
98+
}
99+
100+
@Override
101+
public void channelReadComplete(ChannelHandlerContext ctx) {
102+
readCompletes.incrementAndGet();
103+
}
104+
});
105+
106+
channel.config().setAutoRead(false);
107+
108+
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
109+
response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
110+
111+
assertFalse(channel.writeInbound(response));
112+
assertFalse(channel.writeInbound(new DefaultHttpContent(Unpooled.EMPTY_BUFFER)));
113+
assertFalse(channel.writeInbound(new DefaultHttpContent(Unpooled.EMPTY_BUFFER)));
114+
115+
assertEquals(1, reads.get());
116+
assertEquals(1, readCompletes.get());
117+
118+
channel.read();
119+
assertEquals(2, reads.get());
120+
assertEquals(2, readCompletes.get());
121+
122+
channel.read();
123+
assertEquals(3, reads.get());
124+
assertEquals(3, readCompletes.get());
125+
126+
assertFalse(channel.finishAndReleaseAll());
127+
}
128+
84129
static String[] encodings() {
85130
List<String> encodings = new ArrayList<>();
86131
encodings.add("gzip");
Collapse file

‎handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java
+51-29Lines changed: 51 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
/**
3434
* The {@link FlowControlHandler} ensures that only one message per {@code read()} is sent downstream.
35-
*
35+
* <p>
3636
* Classes such as {@link ByteToMessageDecoder} or {@link MessageToByteEncoder} are free to emit as
3737
* many events as they like for any given input. A channel's auto reading configuration doesn't usually
3838
* apply in these scenarios. This is causing problems in downstream {@link ChannelHandler}s that would
@@ -73,7 +73,25 @@ public class FlowControlHandler extends ChannelDuplexHandler {
7373

7474
private ChannelConfig config;
7575

76-
private boolean shouldConsume;
76+
/**
77+
* Number of unsatisfied downstream {@code read()} calls. A downstream {@code read()} is considered unsatisfied
78+
* if it has not yet been paired with a {@code fireChannelRead} or a cumulative {@code fireChannelReadComplete}.
79+
* <p>
80+
* A {@code read()} can be satisfied in three ways, whichever comes first:
81+
* <ul>
82+
* <li>inside the {@code read()} call itself, by {@code dequeue()}ing a message</li>
83+
* <li>in a {@code channelRead()}</li>
84+
* <li>in a {@code channelReadComplete()}</li>
85+
* </ul>
86+
* <p>
87+
* When one or more {@code read()} calls are unsatisfied, a downstream {@code channelReadComplete} is fired
88+
* only when either of the following happens:
89+
* <ul>
90+
* <li>{@code unsatisfiedReads} returns to zero after {@code dequeue()}ing, or</li>
91+
* <li>an upstream {@code channelReadComplete} arrives</li>
92+
* </ul>
93+
*/
94+
private int unsatisfiedReads;
7795

7896
public FlowControlHandler() {
7997
this(true);
@@ -123,6 +141,7 @@ public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
123141
super.handlerRemoved(ctx);
124142
if (!isQueueEmpty()) {
125143
dequeue(ctx, queue.size());
144+
ctx.fireChannelReadComplete();
126145
}
127146
destroy();
128147
}
@@ -135,13 +154,11 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
135154

136155
@Override
137156
public void read(ChannelHandlerContext ctx) throws Exception {
138-
if (dequeue(ctx, 1) == 0) {
139-
// It seems no messages were consumed. We need to read() some
140-
// messages from upstream and once one arrives it need to be
141-
// relayed to downstream to keep the flow going.
142-
shouldConsume = true;
143-
ctx.read();
144-
} else if (config.isAutoRead()) {
157+
unsatisfiedReads++;
158+
159+
if (dequeue(ctx, 1) > 0) {
160+
satisfyRead(ctx);
161+
} else {
145162
ctx.read();
146163
}
147164
}
@@ -154,31 +171,43 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
154171

155172
queue.offer(msg);
156173

174+
// Snapshot before dequeue(), which may re-enter read() via fireChannelRead(...).
175+
boolean shouldSatisfyRead = unsatisfiedReads > 0;
157176
// We just received one message. Do we need to relay it regardless
158-
// of the auto reading configuration? The answer is yes if this
159-
// method was called as a result of a prior read() call.
160-
int minConsume = shouldConsume ? 1 : 0;
161-
shouldConsume = false;
177+
// of the auto-reading configuration? The answer is yes if this
178+
// method call originates from a prior read call.
179+
int minConsume = shouldSatisfyRead? 1 : 0;
162180

163-
dequeue(ctx, minConsume);
181+
if (dequeue(ctx, minConsume) > 0 && shouldSatisfyRead) {
182+
satisfyRead(ctx);
183+
}
164184
}
165185

166186
@Override
167187
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
168-
if (isQueueEmpty()) {
188+
// Upstream closed the read cycle. Collapse every outstanding read() into a single downstream
189+
// channelReadComplete; spurious upstream completions with no pending read are dropped.
190+
satisfyAllReads(ctx);
191+
}
192+
193+
private void satisfyRead(ChannelHandlerContext ctx) {
194+
if (unsatisfiedReads > 0 && --unsatisfiedReads == 0) {
195+
ctx.fireChannelReadComplete();
196+
}
197+
}
198+
199+
private void satisfyAllReads(ChannelHandlerContext ctx) {
200+
if (unsatisfiedReads > 0) {
201+
unsatisfiedReads = 0;
169202
ctx.fireChannelReadComplete();
170-
} else {
171-
// Don't relay completion events from upstream as they
172-
// make no sense in this context. See dequeue() where
173-
// a new set of completion events is being produced.
174203
}
175204
}
176205

177206
/**
178207
* Dequeues one or many (or none) messages depending on the channel's auto
179208
* reading state and returns the number of messages that were consumed from
180209
* the internal queue.
181-
*
210+
* <p>
182211
* The {@code minConsume} argument is used to force {@code dequeue()} into
183212
* consuming that number of messages regardless of the channel's auto
184213
* reading configuration.
@@ -189,8 +218,8 @@ public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
189218
private int dequeue(ChannelHandlerContext ctx, int minConsume) {
190219
int consumed = 0;
191220

192-
// fireChannelRead(...) may call ctx.read() and so this method may reentrance. Because of this we need to
193-
// check if queue was set to null in the meantime and if so break the loop.
221+
// fireChannelRead(...) may call ctx.read() and so this method may be re-entered. Because of that
222+
// we need to check if queue was set to null in the meantime and, if so, break out of the loop.
194223
while (queue != null && (consumed < minConsume || config.isAutoRead())) {
195224
Object msg = queue.poll();
196225
if (msg == null) {
@@ -201,16 +230,9 @@ private int dequeue(ChannelHandlerContext ctx, int minConsume) {
201230
ctx.fireChannelRead(msg);
202231
}
203232

204-
// We're firing a completion event every time one (or more)
205-
// messages were consumed and the queue ended up being drained
206-
// to an empty state.
207233
if (queue != null && queue.isEmpty()) {
208234
queue.recycle();
209235
queue = null;
210-
211-
if (consumed > 0) {
212-
ctx.fireChannelReadComplete();
213-
}
214236
}
215237

216238
return consumed;

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.