Skip to content

Commit 27b8b0b

Browse files
martenrichteraduh95
authored andcommitted
quic: add option waitUntilAvailable to creating streams
We add an option to createBidirectionalStream and createUnidirectionalStream to fail immediately, if the flow control's stream budget does not allow stream creation. The behavior matches W3C webtransport's behavior. Fixes #65321 Signed-off-by: Marten Richter <marten.richter@freenet.de> PR-URL: #65331 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com>
1 parent b6d94f3 commit 27b8b0b

6 files changed

Lines changed: 83 additions & 21 deletions

File tree

‎doc/api/quic.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1365,6 +1365,11 @@ added: v23.8.0
13651365
will buffer before `writeSync()` returns `false`. When the buffered
13661366
data exceeds this limit, the caller should wait for drain before
13671367
writing more. **Default:** `65536` (64 KB).
1368+
* `waitUntilAvailable` {boolean} When true the promise will wait until flow
1369+
control will allow to open the stream. If set to false, the function
1370+
will return a rejected promise, if flow control will not allow to
1371+
open the stream immediately.
1372+
**Default:** `true`
13681373
* `onheaders` {Function} Callback for received initial response headers.
13691374
Called with `(headers)`.
13701375
* `ontrailers` {Function} Callback for received trailing headers.
@@ -1406,6 +1411,11 @@ added: v23.8.0
14061411
will buffer before `writeSync()` returns `false`. When the buffered
14071412
data exceeds this limit, the caller should wait for drain before
14081413
writing more. **Default:** `65536` (64 KB).
1414+
* `waitUntilAvailable` {boolean} When true the promise will wait until flow
1415+
control will allow to open the stream. If set to false, the function
1416+
will return a rejected promise, if flow control will not allow
1417+
to open the stream immediately.
1418+
**Default:** `true`
14091419
* `onheaders` {Function} Callback for received initial response headers.
14101420
Called with `(headers)`.
14111421
* `ontrailers` {Function} Callback for received trailing headers.

‎lib/internal/quic/quic.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3229,6 +3229,7 @@ class QuicSession {
32293229
incremental = false,
32303230
budget = kDefaultBudget,
32313231
headers,
3232+
waitUntilAvailable = true,
32323233
onheaders,
32333234
ontrailers,
32343235
oninfo,
@@ -3237,10 +3238,10 @@ class QuicSession {
32373238

32383239
validateOneOf(priority, 'options.priority', ['default', 'low', 'high']);
32393240
validateBoolean(incremental, 'options.incremental');
3240-
3241+
validateBoolean(waitUntilAvailable, 'options.waitUntilAvailable');
32413242
const validatedBody = validateBody(body);
32423243

3243-
const handle = this.#handle.openStream(direction, validatedBody);
3244+
const handle = this.#handle.openStream(direction, waitUntilAvailable, validatedBody);
32443245
if (handle === undefined) {
32453246
throw new ERR_QUIC_OPEN_STREAM_FAILED();
32463247
}

‎src/quic/session.cc‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,17 +1181,26 @@ struct Session::Impl final : public MemoryRetainer {
11811181
}
11821182

11831183
DCHECK(args[0]->IsUint32());
1184+
DCHECK(args[1]->IsBoolean());
1185+
1186+
auto direction = FromV8Value<Direction>(args[0]);
1187+
if (!args[1].As<v8::Boolean>()->Value()) {
1188+
// This is waitUntilAvailable
1189+
if (!session->CanImmediatelyOpenStream(direction)) {
1190+
return THROW_ERR_INVALID_STATE(
1191+
env, "No new stream available within flow control");
1192+
}
1193+
}
11841194

11851195
// GetDataQueueFromSource handles type validation.
11861196
std::shared_ptr<DataQueue> data_source;
1187-
if (!Stream::GetDataQueueFromSource(env, args[1]).To(&data_source))
1197+
if (!Stream::GetDataQueueFromSource(env, args[2]).To(&data_source))
11881198
[[unlikely]] {
11891199
return THROW_ERR_INVALID_ARG_VALUE(env, "Invalid data source");
11901200
}
11911201

11921202
session->impl_->handshake_deferred_ = false;
11931203
SendPendingDataScope send_scope(session);
1194-
auto direction = FromV8Value<Direction>(args[0]);
11951204
Local<Object> stream;
11961205
if (session->OpenStream(direction, std::move(data_source)).ToLocal(&stream))
11971206
[[likely]] {
@@ -3239,6 +3248,14 @@ BaseObjectPtr<Stream> Session::CreateStream(
32393248
return {};
32403249
}
32413250

3251+
bool Session::CanImmediatelyOpenStream(Direction direction) {
3252+
if (direction == Direction::BIDIRECTIONAL) {
3253+
return max_local_streams_bidi() > 0;
3254+
} else {
3255+
return max_local_streams_uni() > 0;
3256+
}
3257+
}
3258+
32423259
MaybeLocal<Object> Session::OpenStream(Direction direction,
32433260
std::shared_ptr<DataQueue> data_source) {
32443261
// If can_create_streams() returns false, we are not able to open a stream
@@ -3544,13 +3561,12 @@ void Session::SetApplicationError(error_code app_error_code) {
35443561

35453562
uint64_t Session::max_local_streams_uni() const {
35463563
DCHECK(!is_destroyed());
3547-
return ngtcp2_conn_get_streams_uni_left(*this);
3564+
return ngtcp2_conn_get_streams_uni_left2(*this);
35483565
}
35493566

35503567
uint64_t Session::max_local_streams_bidi() const {
35513568
DCHECK(!is_destroyed());
3552-
return ngtcp2_conn_get_local_transport_params(*this)
3553-
->initial_max_streams_bidi;
3569+
return ngtcp2_conn_get_streams_bidi_left2(*this);
35543570
}
35553571

35563572
void Session::set_wrapped() {

‎src/quic/session.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,9 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
535535
size_t max_packet_size() const;
536536
void set_priority_supported(bool on = true);
537537

538+
// Check whether flow control permits opening another stream
539+
bool CanImmediatelyOpenStream(Direction direction);
540+
538541
// Open a new locally-initialized stream with the specified directionality.
539542
// If the session is not yet in a state where the stream can be opened --
540543
// such as when the handshake is not yet sufficiently far along and ORTT

‎test/parallel/test-quic-stream-limits-pending.mjs‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@ if (!hasQuic) {
1616

1717
const { listen, connect } = await import('../common/quic.mjs');
1818
const { bytes } = await import('stream/iter');
19+
const { setTimeout: sleep } = await import('timers/promises');
1920

2021
const encoder = new TextEncoder();
2122
const allDone = Promise.withResolvers();
23+
const twoDone = Promise.withResolvers();
2224
let serverStreamCount = 0;
2325

2426
// Server allows only 1 bidi stream at a time.
@@ -27,11 +29,17 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
2729
await bytes(stream);
2830
stream.writer.endSync();
2931
await stream.closed;
30-
if (++serverStreamCount === 2) {
31-
serverSession.close();
32+
++serverStreamCount;
33+
if (serverStreamCount === 2) {
34+
twoDone.resolve();
35+
}
36+
if (serverStreamCount === 3) {
3237
allDone.resolve();
3338
}
34-
}, 2);
39+
if (serverStreamCount === 4) {
40+
serverSession.close();
41+
}
42+
}, 3);
3543
}), {
3644
transportParams: { initialMaxStreamsBidi: 1 },
3745
});
@@ -51,27 +59,45 @@ s1.opened.then(() => {
5159
opened++;
5260
});
5361

54-
// Second stream is created but queued as pending because the
55-
// server only allows 1 concurrent bidi stream.
56-
const s2 = await clientSession.createBidirectionalStream({
57-
body: encoder.encode('stream 2'),
62+
let s2;
63+
await assert.rejects(
64+
async () => {
65+
// Second stream should not open, but throw.
66+
s2 = await clientSession.createBidirectionalStream({
67+
body: encoder.encode('stream 2a'),
68+
waitUntilAvailable: false,
69+
});
70+
// eslint-disable-next-line node-core/must-call-assert
71+
s2.opened.then(() => {
72+
opened++;
73+
});
74+
},
75+
{
76+
name: 'Error',
77+
message: 'No new stream available within flow control',
78+
},
79+
);
80+
// Ok try again a second second stream, that patiently waits
81+
s2 = await clientSession.createBidirectionalStream({
82+
body: encoder.encode('stream 2b')
5883
});
59-
6084
// eslint-disable-next-line node-core/must-call-assert
6185
s2.opened.then(() => {
6286
opened++;
6387
});
6488

89+
6590
// Third stream is created but queued as pending because the
6691
// server only allows 1 concurrent bidi stream.
6792
const s3 = await clientSession.createBidirectionalStream({
6893
body: encoder.encode('stream 3'),
6994
});
7095

7196

72-
// s2 should be pending until s1 closes and the server grants
97+
// s2 and s3 should be pending until s1 closes and the server grants
7398
// more stream credits.
7499
assert.strictEqual(s2.pending, true);
100+
assert.strictEqual(s3.pending, true);
75101
assert.strictEqual(opened, 1);
76102

77103
await dump(s1);
@@ -82,15 +108,20 @@ s3.destroy(err);
82108

83109
await Promise.all([assert.rejects(s3.opened, err), assert.rejects(s3.closed, err)]);
84110

85-
86-
// After s1 closes, the server sends MAX_STREAMS which opens s2.
111+
// After s1 closes, the server sends MAX_STREAMS which opens s3.
87112
// Wait for the server to receive both streams.
88-
await allDone.promise;
89-
assert.strictEqual(opened, 2);
90-
113+
await twoDone.promise;
91114
// s2 should no longer be pending.
92115
await dump(s2);
93116
await s2.closed;
94117

118+
await sleep(10); // We wait a bit, as we do not have a callback exposed to js
119+
// fourth stream should open immediately and not throw
120+
const s4 = await clientSession.createBidirectionalStream({
121+
body: encoder.encode('stream 4'),
122+
waitUntilAvailable: false
123+
});
124+
await Promise.all([s4.closed, allDone.promise]);
125+
95126
await clientSession.close();
96127
await serverEndpoint.close();

‎test/parallel/test-quic-stream-limits-uni.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ let opened = 0;
3939
// First uni stream opens immediately.
4040
const s1 = await clientSession.createUnidirectionalStream({
4141
body: encoder.encode('uni 1'),
42+
waitUntilAvailable: false,
4243
});
4344

4445
// eslint-disable-next-line node-core/must-call-assert

0 commit comments

Comments
 (0)