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 — Quic: don't permanently consume stream ids when createStream(...) fails · Echo009/netty@b64a112

File tree

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

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

Copy file name to clipboardExpand all lines: codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicStreamIdGenerator.java
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,22 @@ long nextStreamId(boolean bidirectional) {
3838
nextUnidirectionalStreamId += 4;
3939
return stream;
4040
}
41+
42+
/**
43+
* Rolls back the given {@code streamId} if it is the most recently allocated one of its
44+
* direction, so a failed stream creation does not permanently consume it. Returns
45+
* {@code true} if the rollback was done.
46+
*/
47+
boolean rollbackStreamId(long streamId, boolean bidirectional) {
48+
if (bidirectional) {
49+
if (streamId == nextBidirectionalStreamId - 4) {
50+
nextBidirectionalStreamId = streamId;
51+
return true;
52+
}
53+
} else if (streamId == nextUnidirectionalStreamId - 4) {
54+
nextUnidirectionalStreamId = streamId;
55+
return true;
56+
}
57+
return false;
58+
}
4159
}
Collapse file

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

Copy file name to clipboardExpand all lines: codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicChannel.java
+37-2Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,12 @@ public void operationComplete(ChannelFuture future) {
184184
AtomicLongFieldUpdater.newUpdater(QuicheQuicChannel.class, "bidiStreamsLeft");
185185
private volatile long bidiStreamsLeft;
186186

187+
// Whether the cached stream credits were refreshed from quiche at least once. Before the
188+
// first refresh the caches are 0 even though the peer may have announced credits, so the
189+
// fail-fast check in connectStream(...) must not fire yet; a rejected implicit open in
190+
// that window is instead handled by rolling back the allocated stream id.
191+
private volatile boolean streamCreditsInitialized;
192+
187193
private QuicheQuicChannel(Channel parent, boolean server, @Nullable ByteBuffer key, InetSocketAddress local,
188194
InetSocketAddress remote, boolean supportsDatagram, ChannelHandler streamHandler,
189195
Map.Entry<ChannelOption<?>, Object>[] streamOptionsArray,
@@ -1574,6 +1580,18 @@ void connectStream(QuicStreamType type, @Nullable ChannelHandler handler,
15741580
if (!promise.setUncancellable()) {
15751581
return;
15761582
}
1583+
// Fail fast without consuming a stream id when all credits are used. Otherwise a
1584+
// failed createStream(...) permanently consumes the id: quiche rejects the implicit
1585+
// open by stream id position and never returns it, so once ids are allocated past
1586+
// the peer's limit every future createStream(...) fails with STREAM_LIMIT_ERROR,
1587+
// even after MAX_STREAMS restored the limit, while peerAllowedStreams(...) keeps
1588+
// reporting capacity. Only trusted once the caches were refreshed from quiche;
1589+
// before that they are 0 even though the peer may have announced credits, so we
1590+
// fall through to quiche and let the rollback below handle a rejection.
1591+
if (streamCreditsInitialized && peerAllowedStreams(type) <= 0) {
1592+
promise.setFailure(Quiche.convertToException(Quiche.QUICHE_ERR_STREAM_LIMIT));
1593+
return;
1594+
}
15771595
long streamId = idGenerator.nextStreamId(type == QuicStreamType.BIDIRECTIONAL);
15781596

15791597
try {
@@ -1582,6 +1600,13 @@ void connectStream(QuicStreamType type, @Nullable ChannelHandler handler,
15821600
throw Quiche.convertToException(res);
15831601
}
15841602
} catch (Exception e) {
1603+
// quiche rejected the implicit open before creating any state for the stream,
1604+
// so the id can safely be given back and must be, to not permanently consume
1605+
// it (only done for STREAM_LIMIT as other errors might have left state behind).
1606+
if (e instanceof QuicException &&
1607+
((QuicException) e).error() == QuicTransportError.STREAM_LIMIT_ERROR) {
1608+
idGenerator.rollbackStreamId(streamId, type == QuicStreamType.BIDIRECTIONAL);
1609+
}
15851610
promise.setFailure(e);
15861611
return;
15871612
}
@@ -1784,12 +1809,22 @@ private void processReceived(QuicheQuicConnection conn) {
17841809
Quiche.quiche_conn_is_in_early_data(connAddr)) {
17851810
long uniLeftOld = uniStreamsLeft;
17861811
long bidiLeftOld = bidiStreamsLeft;
1787-
// Only fetch new stream info when we used all our credits
1788-
if (uniLeftOld == 0 || bidiLeftOld == 0) {
1812+
// Only fetch new stream info when we used all our credits. Also cover negative
1813+
// values: MAX_STREAMS can raise the peer's limit while the cached credits are
1814+
// still non-zero (this refresh only triggers once a direction hit 0), so the
1815+
// cache may lag behind quiche's real credits. createStream(...) then keeps
1816+
// succeeding on quiche's real credits while the cached count is decremented
1817+
// past zero, after which a == 0 check would never match again and the cached
1818+
// credits would be frozen below zero forever. The fail-fast check in
1819+
// connectStream(...) makes crossing zero impossible, so covering negatives
1820+
// here is a safety net that also recovers an already-negative cached value
1821+
// on the next received packet.
1822+
if (uniLeftOld <= 0 || bidiLeftOld <= 0) {
17891823
long uniLeft = Quiche.quiche_conn_peer_streams_left_uni(connAddr);
17901824
long bidiLeft = Quiche.quiche_conn_peer_streams_left_bidi(connAddr);
17911825
uniStreamsLeft = uniLeft;
17921826
bidiStreamsLeft = bidiLeft;
1827+
streamCreditsInitialized = true;
17931828
if (uniLeftOld != uniLeft || bidiLeftOld != bidiLeft) {
17941829
pipeline().fireUserEventTriggered(QuicStreamLimitChangedEvent.INSTANCE);
17951830
}
Collapse file

‎codec-classes-quic/src/test/java/io/netty/handler/codec/quic/QuicStreamIdGeneratorTest.java‎

Copy file name to clipboard
+66Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.handler.codec.quic;
17+
18+
import org.junit.jupiter.api.Test;
19+
import org.junit.jupiter.params.ParameterizedTest;
20+
import org.junit.jupiter.params.provider.ValueSource;
21+
22+
import static org.junit.jupiter.api.Assertions.assertEquals;
23+
import static org.junit.jupiter.api.Assertions.assertFalse;
24+
import static org.junit.jupiter.api.Assertions.assertTrue;
25+
26+
public class QuicStreamIdGeneratorTest {
27+
28+
@ParameterizedTest
29+
@ValueSource(booleans = {true, false})
30+
public void testRollbackRestoresMostRecentlyAllocatedIdAndReusesIt(boolean bidirectional) {
31+
QuicStreamIdGenerator generator = new QuicStreamIdGenerator(false);
32+
long streamId = generator.nextStreamId(bidirectional);
33+
34+
assertTrue(generator.rollbackStreamId(streamId, bidirectional));
35+
// After the rollback the same id must be handed out again, so a failed creation
36+
// does not permanently consume it.
37+
assertEquals(streamId, generator.nextStreamId(bidirectional));
38+
}
39+
40+
@ParameterizedTest
41+
@ValueSource(booleans = {true, false})
42+
public void testRollbackOfIdThatIsNotTheFrontierFails(boolean bidirectional) {
43+
QuicStreamIdGenerator generator = new QuicStreamIdGenerator(false);
44+
long first = generator.nextStreamId(bidirectional);
45+
long second = generator.nextStreamId(bidirectional);
46+
47+
// Only the most recently allocated id of a direction may be rolled back, as older
48+
// ids may already have an open stream in quiche.
49+
assertFalse(generator.rollbackStreamId(first, bidirectional));
50+
// A failed rollback must not move the frontier.
51+
assertEquals(second + 4, generator.nextStreamId(bidirectional));
52+
}
53+
54+
@Test
55+
public void testRollbackIsIndependentPerDirection() {
56+
QuicStreamIdGenerator generator = new QuicStreamIdGenerator(false);
57+
long uni = generator.nextStreamId(false);
58+
long bidi = generator.nextStreamId(true);
59+
60+
assertTrue(generator.rollbackStreamId(uni, false));
61+
// Rolling back the unidirectional frontier must not affect the bidirectional one,
62+
// which keeps advancing, while the rolled-back unidirectional id is handed out again.
63+
assertEquals(bidi + 4, generator.nextStreamId(true));
64+
assertEquals(uni, generator.nextStreamId(false));
65+
}
66+
}
Collapse file

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

Copy file name to clipboardExpand all lines: codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicStreamLimitTest.java
+101Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,107 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
124124
}
125125
}
126126

127+
@ParameterizedTest
128+
@MethodSource("newSslTaskExecutors")
129+
public void testStreamCreationSucceedsAfterFailedCreationAndLimitRestoredViaClientBidirectional(
130+
Executor executor) throws Throwable {
131+
testStreamCreationSucceedsAfterFailedCreationAndLimitRestoredViaClient(executor, QuicStreamType.BIDIRECTIONAL);
132+
}
133+
134+
@ParameterizedTest
135+
@MethodSource("newSslTaskExecutors")
136+
public void testStreamCreationSucceedsAfterFailedCreationAndLimitRestoredViaClientUnidirectional(
137+
Executor executor) throws Throwable {
138+
testStreamCreationSucceedsAfterFailedCreationAndLimitRestoredViaClient(executor, QuicStreamType.UNIDIRECTIONAL);
139+
}
140+
141+
private static void testStreamCreationSucceedsAfterFailedCreationAndLimitRestoredViaClient(
142+
Executor executor, QuicStreamType type) throws Throwable {
143+
QuicChannelValidationHandler serverHandler = new QuicChannelValidationHandler();
144+
Channel server = QuicTestUtils.newServer(
145+
QuicTestUtils.newQuicServerBuilder(executor).initialMaxStreamsBidirectional(1)
146+
.initialMaxStreamsUnidirectional(1),
147+
InsecureQuicTokenHandler.INSTANCE,
148+
serverHandler, new ChannelInboundHandlerAdapter() {
149+
@Override
150+
public boolean isSharable() {
151+
return true;
152+
}
153+
154+
@Override
155+
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
156+
if (evt == ChannelInputShutdownReadComplete.INSTANCE) {
157+
ctx.close();
158+
}
159+
}
160+
});
161+
InetSocketAddress address = (InetSocketAddress) server.localAddress();
162+
Channel channel = QuicTestUtils.newClient(executor);
163+
164+
CountDownLatch latch = new CountDownLatch(1);
165+
CountDownLatch latch2 = new CountDownLatch(1);
166+
QuicChannelValidationHandler clientHandler = new QuicChannelValidationHandler() {
167+
@Override
168+
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
169+
if (evt instanceof QuicStreamLimitChangedEvent) {
170+
if (latch.getCount() == 0) {
171+
latch2.countDown();
172+
} else {
173+
latch.countDown();
174+
}
175+
}
176+
super.userEventTriggered(ctx, evt);
177+
}
178+
};
179+
try {
180+
QuicChannel quicChannel = QuicTestUtils.newQuicChannelBootstrap(channel)
181+
.handler(clientHandler)
182+
.streamHandler(new ChannelInboundHandlerAdapter())
183+
.remoteAddress(address)
184+
.connect().get();
185+
latch.await();
186+
QuicStreamChannel stream = quicChannel.createStream(
187+
type, new ChannelInboundHandlerAdapter()).get();
188+
assertEquals(0, quicChannel.peerAllowedStreams(type));
189+
190+
// Second stream creation should fail as the limit is reached.
191+
Throwable cause = quicChannel.createStream(
192+
type, new ChannelInboundHandlerAdapter()).await().cause();
193+
assertInstanceOf(QuicException.class, cause);
194+
195+
// Repeated failed creations while the limit is exhausted must not consume
196+
// stream ids either: if they did, the creation below after the restore would
197+
// fail with STREAM_LIMIT_ERROR again because the stream id position moved
198+
// past the limit.
199+
for (int i = 0; i < 5; i++) {
200+
Throwable repeatedCause = quicChannel.createStream(
201+
type, new ChannelInboundHandlerAdapter()).await().cause();
202+
assertInstanceOf(QuicException.class, repeatedCause);
203+
}
204+
stream.close().sync();
205+
latch2.await();
206+
assertEquals(1, quicChannel.peerAllowedStreams(type));
207+
208+
// Once the limit is restored, creating a stream must succeed again: a failed
209+
// createStream(...) must not have permanently consumed a stream id. Otherwise
210+
// this and every later creation on the connection would keep failing with
211+
// STREAM_LIMIT_ERROR while peerAllowedStreams(...) reports capacity.
212+
QuicStreamChannel stream2 = quicChannel.createStream(
213+
type, new ChannelInboundHandlerAdapter()).get();
214+
stream2.close().sync();
215+
quicChannel.close().sync();
216+
217+
serverHandler.assertState();
218+
clientHandler.assertState();
219+
} finally {
220+
server.close().sync();
221+
// Close the parent Datagram channel as well.
222+
channel.close().sync();
223+
224+
shutdown(executor);
225+
}
226+
}
227+
127228
@ParameterizedTest
128229
@MethodSource("newSslTaskExecutors")
129230
public void testStreamLimitEnforcedWhenCreatingViaServerBidirectional(Executor executor) throws Throwable {

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.