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 — Port 5.0: Keep reading a closed QUIC stream until the end of its inpu… · netty/netty@f03e3ee

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-classes-quic/src/main/java/io/netty/handler/codec/quic
    • QuicheQuicStreamChannel.java
  • codec-native-quic/src/test/java/io/netty/handler/codec/quic
    • QuicStreamChannelCloseTest.java
    • QuicStreamLimitTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicStreamChannel.java‎

Copy file name to clipboardExpand all lines: codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicStreamChannel.java
+74-20Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -332,9 +332,10 @@ private void updateWritabilityIfNeeded(boolean newWritable) {
332332
*/
333333
void readable() {
334334
assert executor().inEventLoop();
335-
// Mark as readable and if a read is pending execute it.
335+
// Mark as readable and if a read is pending execute it. If the channel was closed already, what is left
336+
// must be dropped, see QuicStreamChannelUnsafe.recv().
336337
readable = true;
337-
if (readPending) {
338+
if (readPending || !active) {
338339
ioTransport().recv();
339340
}
340341
}
@@ -503,6 +504,21 @@ void close(@Nullable ClosedChannelException writeFailCause, CompletionHandler<Vo
503504
} else {
504505
deregister(CompletionHandler.ignore(), true);
505506
}
507+
// If we are in recv() already, it drops what is left once the loop is done and the parent flushes after
508+
// it processed the received packets.
509+
if (readable && !inRecv) {
510+
// Drop what is left to read, see recv().
511+
recv();
512+
513+
// As the stream was readable, and we called recv() ourselves we also need to call
514+
// connectionSendAndFlush(). This is needed as recv() consumes data and so a window update frame
515+
// might be produced. If close() was not triggered while processing received packets (for example
516+
// by a timeout or a cancellation from another task) nobody else will send it. If we miss to call
517+
// connectionSendAndFlush() the remote peer may not learn about the new credit and so might never
518+
// send more data, on this stream or on the connection.
519+
// See also https://docs.rs/quiche/latest/quiche/struct.Connection.html#method.send.
520+
parent().connectionSendAndFlush();
521+
}
506522
}
507523

508524
private void deregister(final CompletionHandler<Void> handler, final boolean fireChannelInactive) {
@@ -887,24 +903,7 @@ void recv() {
887903
while (!finReceived && continueReading) {
888904
byteBuf = allocHandle.allocate(allocator);
889905
allocHandle.attemptedBytesRead(byteBuf.writableBytes());
890-
QuicheQuicChannel.StreamRecvResult result = parent.streamRecv(streamId(), byteBuf);
891-
switch (result) {
892-
case DONE:
893-
// Nothing left to read;
894-
readable = false;
895-
break;
896-
case FIN:
897-
// If we received a FIN we also should mark the channel as non-readable as
898-
// there is nothing left to read really.
899-
readable = false;
900-
finReceived = true;
901-
inputShutdown = true;
902-
break;
903-
case OK:
904-
break;
905-
default:
906-
throw new Error("Unexpected StreamRecvResult: " + result);
907-
}
906+
handleRecvResult(parent.streamRecv(streamId(), byteBuf));
908907
allocHandle.lastBytesRead(byteBuf.readableBytes());
909908
if (allocHandle.lastBytesRead() <= 0) {
910909
byteBuf.release();
@@ -946,13 +945,68 @@ void recv() {
946945
handleReadException(pipeline, byteBuf, cause, allocHandle, readFrames);
947946
}
948947
}
948+
if (!active) {
949+
discardInput(allocator, allocHandle);
950+
}
949951
} finally {
950952
// About to leave the method lets reset so we can enter it again.
951953
inRecv = false;
952954
removeStreamFromParent();
953955
}
954956
}
955957

958+
private void handleRecvResult(QuicheQuicChannel.StreamRecvResult result) {
959+
switch (result) {
960+
case DONE:
961+
// Nothing left to read;
962+
readable = false;
963+
break;
964+
case FIN:
965+
// If we received a FIN we also should mark the channel as non-readable as
966+
// there is nothing left to read really.
967+
readable = false;
968+
finReceived = true;
969+
inputShutdown = true;
970+
break;
971+
case OK:
972+
break;
973+
default:
974+
throw new Error("Unexpected StreamRecvResult: " + result);
975+
}
976+
}
977+
978+
/**
979+
* The channel was closed before the end of the stream was read. Read and drop what is left: as long as quiche
980+
* holds the data it keeps its connection flow control credit, and the stream is never completed and collected,
981+
* so its stream credit is never returned to the remote peer either.
982+
*/
983+
private void discardInput(DirectIoByteBufAllocator allocator,
984+
@SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle) {
985+
QuicheQuicChannel parent = parent();
986+
while (readable && !finReceived) {
987+
allocHandle.reset(config());
988+
ByteBuf byteBuf = allocHandle.allocate(allocator);
989+
try {
990+
handleRecvResult(parent.streamRecv(streamId(), byteBuf));
991+
} catch (Throwable cause) {
992+
// The stream was reset by the remote peer or the connection was closed, there is nothing left
993+
// to read.
994+
readable = false;
995+
finReceived = true;
996+
inputShutdown = true;
997+
// A ClosedChannelException means the connection was closed or freed already. This is expected
998+
// when the streams are closed as part of closing the connection, and the user is notified about
999+
// the closure of the stream and the connection anyway, so there is no need to fire it. Everything
1000+
// else is reported as the data that was dropped is lost.
1001+
if (!(cause instanceof ClosedChannelException)) {
1002+
pipeline().fireExceptionCaught(cause);
1003+
}
1004+
} finally {
1005+
byteBuf.release();
1006+
}
1007+
}
1008+
}
1009+
9561010
// Read was complete and something was read, so we we need to reset the readPending flags, the allocHandle
9571011
// and call fireChannelReadComplete(). The user may schedule another read now.
9581012
private void readComplete(@SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle,
Collapse file

‎codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicStreamChannelCloseTest.java‎

Copy file name to clipboardExpand all lines: codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicStreamChannelCloseTest.java
+201Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package io.netty.handler.codec.quic;
1717

18+
import io.netty.buffer.ByteBuf;
1819
import io.netty.buffer.Unpooled;
1920
import io.netty.channel.Channel;
2021
import io.netty.channel.ChannelHandlerContext;
@@ -31,10 +32,15 @@
3132
import org.junit.jupiter.params.provider.MethodSource;
3233

3334
import java.nio.channels.ClosedChannelException;
35+
import java.util.concurrent.CountDownLatch;
3436
import java.util.concurrent.Executor;
37+
import java.util.concurrent.Semaphore;
3538
import java.util.concurrent.TimeUnit;
39+
import java.util.concurrent.atomic.AtomicInteger;
3640

41+
import static org.junit.jupiter.api.Assertions.assertEquals;
3742
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
43+
import static org.junit.jupiter.api.Assertions.assertTrue;
3844

3945
public class QuicStreamChannelCloseTest extends AbstractQuicTest {
4046

@@ -292,6 +298,201 @@ public void channelActive(ChannelHandlerContext ctx) {
292298
}
293299
}
294300

301+
@ParameterizedTest
302+
@MethodSource("newSslTaskExecutors")
303+
public void testCloseBeforeEndOfInputReturnsFlowControlCredit(Executor executor) throws Throwable {
304+
final int window = 64 * 1024;
305+
// Larger than the windows of the client, so the response can't be received completely before it reads.
306+
final int responseSize = 2 * window;
307+
Channel server = null;
308+
Channel channel = null;
309+
try {
310+
server = QuicTestUtils.newServer(executor, QuicTestUtils.NOOP_HANDLER,
311+
new ChannelInboundHandler() {
312+
@Override
313+
public boolean isSharable() {
314+
return true;
315+
}
316+
317+
@Override
318+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
319+
ReferenceCountUtil.release(msg);
320+
}
321+
322+
@Override
323+
public void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownType type) {
324+
if (type.direction() == ChannelShutdownDirection.Inbound) {
325+
ctx.writeAndFlush(Unpooled.directBuffer(responseSize).writeZero(responseSize))
326+
.addListener(f -> ctx.shutdown(ChannelShutdownType.newOutbound()));
327+
}
328+
ctx.fireChannelShutdown(type);
329+
}
330+
});
331+
channel = QuicTestUtils.newClient(QuicTestUtils.newQuicClientBuilder(executor)
332+
.initialMaxData(window).initialMaxStreamDataBidirectionalLocal(window));
333+
QuicChannel quicChannel = QuicTestUtils.newQuicChannelBootstrap(channel)
334+
.handler(new ChannelInboundHandler() { })
335+
.streamHandler(new ChannelInboundHandler() { })
336+
.remoteAddress(server.localAddress())
337+
.connect().get();
338+
339+
// Close the stream once the first bytes of the response were received, the rest is never read by the
340+
// user.
341+
QuicStreamChannel cancelled = quicChannel.createStream(QuicStreamType.BIDIRECTIONAL,
342+
new ChannelInboundHandler() {
343+
@Override
344+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
345+
ReferenceCountUtil.release(msg);
346+
ctx.close();
347+
}
348+
}).get();
349+
cancelled.writeAndFlush(Unpooled.directBuffer().writeZero(8))
350+
.addListener(f -> cancelled.shutdown(ChannelShutdownType.newOutbound()));
351+
cancelled.closeFuture().sync();
352+
353+
// The next response must still be received completely.
354+
AtomicInteger received = new AtomicInteger();
355+
CountDownLatch endOfInput = new CountDownLatch(1);
356+
QuicStreamChannel stream = quicChannel.createStream(QuicStreamType.BIDIRECTIONAL,
357+
new ChannelInboundHandler() {
358+
@Override
359+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
360+
received.addAndGet(((ByteBuf) msg).readableBytes());
361+
ReferenceCountUtil.release(msg);
362+
}
363+
364+
@Override
365+
public void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownType type) {
366+
if (type.direction() == ChannelShutdownDirection.Inbound) {
367+
endOfInput.countDown();
368+
}
369+
ctx.fireChannelShutdown(type);
370+
}
371+
}).get();
372+
stream.writeAndFlush(Unpooled.directBuffer().writeZero(8))
373+
.addListener(f -> stream.shutdown(ChannelShutdownType.newOutbound()));
374+
assertTrue(endOfInput.await(5, TimeUnit.SECONDS), "received only " + received.get() + " bytes");
375+
assertEquals(responseSize, received.get());
376+
stream.closeFuture().sync();
377+
quicChannel.close().sync();
378+
} finally {
379+
QuicTestUtils.closeIfNotNull(channel);
380+
QuicTestUtils.closeIfNotNull(server);
381+
382+
shutdown(executor);
383+
}
384+
}
385+
386+
@ParameterizedTest
387+
@MethodSource("newSslTaskExecutors")
388+
public void testCloseOutsideOfReadBeforeEndOfInputReturnsFlowControlCredit(Executor executor) throws Throwable {
389+
final int window = 64 * 1024;
390+
// Larger than the windows of the client, so the response can't be received completely before it reads.
391+
final int responseSize = 2 * window;
392+
Semaphore responseWritten = new Semaphore(0);
393+
Channel server = null;
394+
Channel channel = null;
395+
try {
396+
server = QuicTestUtils.newServer(executor, QuicTestUtils.NOOP_HANDLER,
397+
new ChannelInboundHandler() {
398+
@Override
399+
public boolean isSharable() {
400+
return true;
401+
}
402+
403+
@Override
404+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
405+
ReferenceCountUtil.release(msg);
406+
}
407+
408+
@Override
409+
public void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownType type) {
410+
if (type.direction() == ChannelShutdownDirection.Inbound) {
411+
// The write only completes once the client opened its flow control windows far
412+
// enough to accept the whole response.
413+
ctx.writeAndFlush(Unpooled.directBuffer(responseSize).writeZero(responseSize))
414+
.addListener(future -> {
415+
if (future.isSuccess()) {
416+
responseWritten.release();
417+
}
418+
})
419+
.addListener(f -> ctx.shutdown(ChannelShutdownType.newOutbound()));
420+
}
421+
ctx.fireChannelShutdown(type);
422+
}
423+
});
424+
channel = QuicTestUtils.newClient(QuicTestUtils.newQuicClientBuilder(executor)
425+
.initialMaxData(window).initialMaxStreamDataBidirectionalLocal(window));
426+
QuicChannel quicChannel = QuicTestUtils.newQuicChannelBootstrap(channel)
427+
.handler(new ChannelInboundHandler() { })
428+
.streamHandler(new ChannelInboundHandler() { })
429+
.remoteAddress(server.localAddress())
430+
.connect().get();
431+
432+
// Read only the first bytes of the response, the rest stays in quiche as the user never asks for it.
433+
CountDownLatch firstRead = new CountDownLatch(1);
434+
QuicStreamChannel cancelled = quicChannel.createStream(QuicStreamType.BIDIRECTIONAL,
435+
new ChannelInboundHandler() {
436+
@Override
437+
public void handlerAdded(ChannelHandlerContext ctx) {
438+
ctx.channel().config().setAutoRead(false);
439+
}
440+
441+
@Override
442+
public void channelActive(ChannelHandlerContext ctx) {
443+
ctx.read();
444+
ctx.fireChannelActive();
445+
}
446+
447+
@Override
448+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
449+
ReferenceCountUtil.release(msg);
450+
firstRead.countDown();
451+
}
452+
}).get();
453+
cancelled.writeAndFlush(Unpooled.directBuffer().writeZero(8))
454+
.addListener(f -> cancelled.shutdown(ChannelShutdownType.newOutbound()));
455+
assertTrue(firstRead.await(5, TimeUnit.SECONDS));
456+
457+
// Close the stream outside of a read callback, so it is up to close() to drop what is left and to send
458+
// the resulting window updates. Nothing else is sent by the client until the response is written.
459+
cancelled.close().sync();
460+
assertTrue(responseWritten.tryAcquire(5, TimeUnit.SECONDS),
461+
"server could not write the whole response of the closed stream");
462+
463+
// The next response must be received completely as well.
464+
AtomicInteger received = new AtomicInteger();
465+
CountDownLatch endOfInput = new CountDownLatch(1);
466+
QuicStreamChannel stream = quicChannel.createStream(QuicStreamType.BIDIRECTIONAL,
467+
new ChannelInboundHandler() {
468+
@Override
469+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
470+
received.addAndGet(((ByteBuf) msg).readableBytes());
471+
ReferenceCountUtil.release(msg);
472+
}
473+
474+
@Override
475+
public void channelShutdown(ChannelHandlerContext ctx, ChannelShutdownType type) {
476+
if (type.direction() == ChannelShutdownDirection.Inbound) {
477+
endOfInput.countDown();
478+
}
479+
ctx.fireChannelShutdown(type);
480+
}
481+
}).get();
482+
stream.writeAndFlush(Unpooled.directBuffer().writeZero(8))
483+
.addListener(f -> stream.shutdown(ChannelShutdownType.newOutbound()));
484+
assertTrue(endOfInput.await(5, TimeUnit.SECONDS), "received only " + received.get() + " bytes");
485+
assertEquals(responseSize, received.get());
486+
stream.closeFuture().sync();
487+
quicChannel.close().sync();
488+
} finally {
489+
QuicTestUtils.closeIfNotNull(channel);
490+
QuicTestUtils.closeIfNotNull(server);
491+
492+
shutdown(executor);
493+
}
494+
}
495+
295496
private static final class StreamHandler implements ChannelInboundHandler {
296497

297498
@Override

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.