quic: add stream idle timeout

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode:Opus 4.6
PR-URL: https://github.com/nodejs/node/pull/63483
Backport-PR-URL: https://github.com/nodejs/node/pull/64675
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-08-06 11:33:38 +02:00
1 parent e493f04214
commit 7652bd9c6d
18 files changed
+516 -34

No files matched your search

+22
View File
@@ -1659,6 +1659,11 @@ added: v23.8.0
* Type: {bigint}
### `sessionStats.streamsIdleTimedOut`
* Type: {bigint} The total number of peer-initiated streams destroyed by the
stream idle timeout. Read only.
## Class: `QuicError`
<!-- YAML
@@ -3026,6 +3031,23 @@ reported as lost via the `ondatagramstatus` callback.
This option is immutable after session creation.
#### `sessionOptions.streamIdleTimeout`
* Type: {bigint|number}
* **Default:** `30000` (30 seconds)
The maximum time in milliseconds that a peer-initiated stream can be idle
(no data received) before it is automatically destroyed. This protects
against slowloris-style attacks where a remote peer opens streams but never
sends data, holding server resources indefinitely. Only peer-initiated
streams are checked — locally-initiated streams are the application's
responsibility. Set to `0` to disable.
The idle check runs as part of the normal send processing loop, so it adds
no additional timers or event loop overhead. The
`session.stats.streamsIdleTimedOut` counter tracks how many streams have been
destroyed by this mechanism.
#### `sessionOptions.maxDatagramSendAttempts`
* Type: {number}
+14
View File
@@ -436,6 +436,7 @@ const endpointRegistry = new SafeSet();
* @property {number} [drainingPeriodMultiplier] Multiplier applied to the
* draining period (3 * PTO) used by ngtcp2. Range `3..255`.
* **Default:** `3`.
* @property {bigint|number} [streamIdleTimeout] Time in ms before idle peer-initiated streams are destroyed
* @property {number} [maxDatagramSendAttempts] Maximum number of times a
* datagram is retried before being abandoned. Range `1..255`.
* **Default:** `5`.
@@ -922,6 +923,17 @@ setCallbacks({
// from QuicError::ToV8Value. Convert to a proper Node.js Error.
if (error !== undefined) {
error = convertQuicError(error);
} else if (this[kOwner] && !this[kOwner].destroyed) {
// The stream is closing cleanly, but it may have been reset by the
// peer (ReceiveStreamReset) or locally (resetStream). The C++ side
// records the reset code in state.resetCode. If set, surface the
// reset as the close error so stream.closed rejects -- the reset
// was an abnormal termination even if the session closed cleanly.
const resetCode = getQuicStreamState(this[kOwner]).resetCode;
if (resetCode !== undefined && resetCode > 0n) {
error = new ERR_QUIC_APPLICATION_ERROR(
resetCode, `stream reset with code ${resetCode}`);
}
}
debug(`stream ${this[kOwner].id} closed callback with error: ${error}`);
this[kOwner][kFinishClose](error);
@@ -5015,6 +5027,7 @@ function processSessionOptions(options, config = kEmptyObject) {
datagramDropPolicy = 'drop-oldest',
drainingPeriodMultiplier = 3,
maxDatagramSendAttempts = 5,
streamIdleTimeout,
verifyPeer = 'auto',
// HTTP/3 application-specific options. Nested under `application`
// to separate protocol-specific settings from transport-level ones.
@@ -5136,6 +5149,7 @@ function processSessionOptions(options, config = kEmptyObject) {
datagramDropPolicy,
drainingPeriodMultiplier,
maxDatagramSendAttempts,
streamIdleTimeout,
application,
onerror,
onstream,
+13
View File
@@ -101,6 +101,7 @@ const {
IDX_STATS_SESSION_DATAGRAMS_SENT,
IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED,
IDX_STATS_SESSION_DATAGRAMS_LOST,
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT,
IDX_STATS_SESSION_COUNT,
IDX_STATS_STREAM_CREATED_AT,
@@ -169,6 +170,7 @@ assert(IDX_STATS_SESSION_DATAGRAMS_RECEIVED !== undefined);
assert(IDX_STATS_SESSION_DATAGRAMS_SENT !== undefined);
assert(IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED !== undefined);
assert(IDX_STATS_SESSION_DATAGRAMS_LOST !== undefined);
assert(IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT !== undefined);
assert(IDX_STATS_STREAM_CREATED_AT !== undefined);
assert(IDX_STATS_STREAM_OPENED_AT !== undefined);
assert(IDX_STATS_STREAM_RECEIVED_AT !== undefined);
@@ -689,6 +691,13 @@ class QuicSessionStats {
return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_LOST];
}
/** @type {bigint} */
get streamsIdleTimedOut() {
assertIsQuicSessionStats(this);
return this.#handle[this.#offset +
IDX_STATS_SESSION_STREAMS_IDLE_TIMED_OUT];
}
toString() {
return JSONStringify(this.toJSON());
}
@@ -726,6 +735,7 @@ class QuicSessionStats {
datagramsSent,
datagramsAcknowledged,
datagramsLost,
streamsIdleTimedOut,
} = this;
return {
__proto__: null,
@@ -762,6 +772,7 @@ class QuicSessionStats {
datagramsSent: `${datagramsSent}`,
datagramsAcknowledged: `${datagramsAcknowledged}`,
datagramsLost: `${datagramsLost}`,
streamsIdleTimedOut: `${streamsIdleTimedOut}`,
};
}
@@ -807,6 +818,7 @@ class QuicSessionStats {
datagramsSent,
datagramsAcknowledged,
datagramsLost,
streamsIdleTimedOut,
} = this;
return `QuicSessionStats ${inspect({
@@ -841,6 +853,7 @@ class QuicSessionStats {
datagramsSent,
datagramsAcknowledged,
datagramsLost,
streamsIdleTimedOut,
}, opts)}`;
}
+5 -2
View File
@@ -724,8 +724,11 @@ class DefaultApplication final : public Session::Application {
void EarlyDataRejected() override {
// Destroy all open streams — ngtcp2 has already discarded their
// internal state when it rejected the early data.
session().DestroyAllStreams(QuicError::ForApplication(0));
// internal state when it rejected the early data. Use the
// application's internal error code since this is an error
// condition (code 0 would be treated as a clean close).
session().DestroyAllStreams(
QuicError::ForApplication(GetInternalErrorCode()));
if (!session().is_destroyed()) {
session().EmitEarlyDataRejected();
}
+1
View File
@@ -113,6 +113,7 @@ class SessionManager;
V(max_connections_total, "maxConnectionsTotal") \
V(max_datagram_frame_size, "maxDatagramFrameSize") \
V(max_datagram_send_attempts, "maxDatagramSendAttempts") \
V(stream_idle_timeout, "streamIdleTimeout") \
V(max_field_section_size, "maxFieldSectionSize") \
V(max_header_length, "maxHeaderLength") \
V(max_header_pairs, "maxHeaderPairs") \
+5 -5
View File
@@ -365,12 +365,12 @@ std::optional<int> QuicError::get_crypto_error() const {
MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const {
if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) ||
(type() == Type::APPLICATION && code() == NGHTTP3_H3_NO_ERROR) ||
(type() == Type::APPLICATION &&
(code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) ||
type() == Type::IDLE_CLOSE) {
// Note that we only return undefined for *known* no-error application
// codes. It is possible that other application types use other specific
// no-error codes, but since we don't know which application is being used,
// we'll just return the error code value for those below.
// Application code 0 is the default no-error code for raw QUIC
// applications (DefaultApplication::GetNoErrorCode() returns 0).
// NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code.
// Idle close is always clean — the session timed out normally.
return Undefined(env->isolate());
}
+5 -2
View File
@@ -177,10 +177,13 @@ class Http3ApplicationImpl final : public Session::Application {
// When 0-RTT is rejected, destroy the nghttp3 connection and all
// open streams — ngtcp2 has discarded their internal state.
// Reset started_ so Start() is called again via on_receive_rx_key
// at 1RTT to recreate the nghttp3 connection.
// at 1RTT to recreate the nghttp3 connection. Use the
// application's internal error code since this is an error
// condition (code 0 would be treated as a clean close).
conn_.reset();
started_ = false;
session().DestroyAllStreams(QuicError::ForApplication(0));
session().DestroyAllStreams(
QuicError::ForApplication(GetInternalErrorCode()));
if (!session().is_destroyed()) {
session().EmitEarlyDataRejected();
}
+76 -16
View File
@@ -174,7 +174,8 @@ uint64_t MaxDatagramPayload(uint64_t max_frame_size) {
V(DATAGRAMS_RECEIVED, datagrams_received) \
V(DATAGRAMS_SENT, datagrams_sent) \
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
V(DATAGRAMS_LOST, datagrams_lost)
V(DATAGRAMS_LOST, datagrams_lost) \
V(STREAMS_IDLE_TIMED_OUT, streams_idle_timed_out)
#define NO_SIDE_EFFECT true
#define SIDE_EFFECT false
@@ -617,7 +618,8 @@ Maybe<Session::Options> Session::Options::From(Environment* env,
!SET(keep_alive_timeout) || !SET(max_stream_window) || !SET(max_window) ||
!SET(max_payload_size) || !SET(unacknowledged_packet_threshold) ||
!SET(cc_algorithm) || !SET(draining_period_multiplier) ||
!SET(max_datagram_send_attempts)) {
!SET(max_datagram_send_attempts) ||
!SET(stream_idle_timeout)) {
return Nothing<Options>();
}
@@ -2819,24 +2821,36 @@ void Session::ShutdownStream(stream_id id, QuicError error) {
DCHECK(!is_destroyed());
Debug(this, "Shutting down stream %" PRIi64 " with error %s", id, error);
SendPendingDataScope send_scope(this);
ngtcp2_conn_shutdown_stream(*this,
0,
id,
error.type() == QuicError::Type::APPLICATION
? error.code()
: application().GetNoErrorCode());
// STOP_SENDING and RESET_STREAM frames carry application-level error
// codes (RFC 9000 §19.4, §19.5). Map the QuicError to an appropriate
// application code: APPLICATION errors pass through directly; transport
// no-error maps to the application's no-error code; any other error
// maps to the application's internal error code.
error_code code;
if (error.type() == QuicError::Type::APPLICATION) {
code = error.code();
} else if (error.code() == NGTCP2_NO_ERROR) {
code = application().GetNoErrorCode();
} else {
code = application().GetInternalErrorCode();
}
ngtcp2_conn_shutdown_stream(*this, 0, id, code);
}
void Session::ShutdownStreamWrite(stream_id id, QuicError code) {
void Session::ShutdownStreamWrite(stream_id id, QuicError error) {
DCHECK(!is_destroyed());
Debug(this, "Shutting down stream %" PRIi64 " write with error %s", id, code);
Debug(this, "Shutting down stream %" PRIi64 " write with error %s",
id, error);
SendPendingDataScope send_scope(this);
ngtcp2_conn_shutdown_stream_write(*this,
0,
id,
code.type() == QuicError::Type::APPLICATION
? code.code()
: application().GetNoErrorCode());
error_code code;
if (error.type() == QuicError::Type::APPLICATION) {
code = error.code();
} else if (error.code() == NGTCP2_NO_ERROR) {
code = application().GetNoErrorCode();
} else {
code = application().GetInternalErrorCode();
}
ngtcp2_conn_shutdown_stream_write(*this, 0, id, code);
}
void Session::StreamDataBlocked(stream_id id) {
@@ -3035,6 +3049,41 @@ void Session::UpdateDataStats() {
std::max(STAT_GET(Stats, max_bytes_in_flight), info.bytes_in_flight));
}
void Session::CheckStreamIdleTimeout(uint64_t now) {
if (is_destroyed()) return;
uint64_t timeout = options().stream_idle_timeout;
if (timeout == 0) return;
uint64_t timeout_ns = timeout * NGTCP2_MILLISECONDS;
auto all_streams = streams();
for (const auto& [id, stream] : all_streams) {
if (!stream) continue;
// Only check peer-initiated streams. Locally-initiated streams
// that haven't been written to are the application's concern.
if (ngtcp2_conn_is_local_stream(*this, id)) continue;
uint64_t last_activity = stream->last_activity_timestamp();
if (last_activity > 0 && (now - last_activity) > timeout_ns) {
Debug(this,
"Stream %" PRId64 " idle timeout exceeded, destroying",
id);
// Notify the peer before destroying. ShutdownStream sends both
// STOP_SENDING and RESET_STREAM as appropriate, using the
// application's no-error code for non-APPLICATION errors (since
// these frames carry application-level error codes per RFC 9000).
// Without this, the peer's stream sits orphaned until the
// session closes.
auto error = QuicError::ForTransport(NGTCP2_ERR_PROTO,
"stream idle timeout");
ShutdownStream(id, error);
stream->Destroy(error);
STAT_INCREMENT(Stats, streams_idle_timed_out);
}
}
}
void Session::SendConnectionClose() {
// Method is a non-op if the session is already destroyed or the
// endpoint cannot send. Note: we intentionally do NOT check
@@ -3119,6 +3168,8 @@ void Session::OnTimeout() {
if (is_destroyed()) return;
if (NGTCP2_OK(ret) && !is_in_closing_period() && !is_in_draining_period()) {
application().SendPendingData();
if (is_destroyed()) return;
CheckStreamIdleTimeout(uv_hrtime());
return;
}
if (is_destroyed()) return;
@@ -3165,6 +3216,15 @@ void Session::UpdateTimer() {
auto timeout = (expiry - now) / NGTCP2_MILLISECONDS;
Debug(this, "Updating timeout to %zu milliseconds", timeout);
// If a stream idle timeout is configured, ensure the timer fires at
// least that often so CheckStreamIdleTimeout runs. Without this, an
// idle session with idle streams might not fire the timer until the
// connection idle timeout, which could be much longer.
uint64_t stream_idle = options().stream_idle_timeout;
if (stream_idle > 0 && timeout > stream_idle) {
timeout = stream_idle;
}
// If timeout is zero here, it means our timer is less than a millisecond
// off from expiry. Let's bump the timer to 1.
impl_->timer_.Update(timeout == 0 ? 1 : timeout);
+9
View File
@@ -227,6 +227,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
// 10.2 requires at least 3x PTO. Range: 3-255. Default: 3.
uint8_t draining_period_multiplier = 3;
// The amount of time (in milliseconds) that a stream can be idle
// (no data received) before it is automatically destroyed. This
// protects against slowloris-style attacks where a peer opens streams
// but never sends data, holding server resources indefinitely.
// Only applies to peer-initiated streams. Set to 0 to disable.
static constexpr uint64_t DEFAULT_STREAM_IDLE_TIMEOUT = 30'000;
uint64_t stream_idle_timeout = DEFAULT_STREAM_IDLE_TIMEOUT;
// An optional NEW_TOKEN from a previous connection to the same
// server. When set, the token is included in the Initial packet
// to skip address validation. Client-side only.
@@ -569,6 +577,7 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
// Has to be called after certain operations that generate packets.
void UpdatePacketTxTime();
void UpdateDataStats();
void CheckStreamIdleTimeout(uint64_t now);
void UpdatePath(const PathStorage& path);
void ProcessPendingBidiStreams();
+8 -1
View File
@@ -1270,7 +1270,8 @@ void Stream::NotifyStreamOpened(stream_id id) {
// Headers were enqueued while the application was not yet known
// (headers_supported == 0), and the negotiated application does
// not support headers. This is a fatal mismatch.
Destroy(QuicError::ForApplication(0));
Destroy(QuicError::ForApplication(
session().application().GetInternalErrorCode()));
return;
}
decltype(pending_headers_queue_) queue;
@@ -1347,6 +1348,11 @@ Session& Stream::session() const {
return *session_;
}
uint64_t Stream::last_activity_timestamp() const {
uint64_t ts = stats()->received_at;
return ts != 0 ? ts : stats()->created_at;
}
bool Stream::is_local_unidirectional() const {
return direction() == Direction::UNIDIRECTIONAL &&
ngtcp2_conn_is_local_stream(*session_, id());
@@ -1625,6 +1631,7 @@ void Stream::EndReadable(std::optional<uint64_t> maybe_final_size) {
void Stream::Destroy(QuicError error) {
if (stats()->destroyed_at != 0) return;
// Record the destroyed at timestamp before notifying the JavaScript side
// that the stream is being destroyed.
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);
+5
View File
@@ -258,6 +258,11 @@ class Stream final : public AsyncWrap,
Session& session() const;
// Returns the most recent activity timestamp for this stream in
// nanoseconds (uv_hrtime). Uses received_at if data has been received,
// otherwise falls back to created_at. Returns 0 if neither is set.
uint64_t last_activity_timestamp() const;
// True if this stream was created in a pending state and is still waiting
// to be created.
bool is_pending() const;
@@ -0,0 +1,185 @@
// Flags: --experimental-quic --experimental-stream-iter --no-warnings
// Test: HTTP/3 stream idle timeout.
// Peer-initiated streams that receive no data within the configured
// timeout are automatically destroyed. This test verifies the behavior
// with HTTP/3 bidirectional streams, where ShutdownStream maps
// transport errors to the application's internal error code
// (NGHTTP3_H3_INTERNAL_ERROR = 0x102) on the wire.
import { hasQuic, skip, mustCall } from '../common/index.mjs';
import assert from 'node:assert';
import { setTimeout } from 'node:timers/promises';
import * as fixtures from '../common/fixtures.mjs';
import { text } from 'node:stream/iter';
const { rejects, strictEqual } = assert;
const { readKey } = fixtures;
if (!hasQuic) {
skip('QUIC is not enabled');
}
const { listen, connect } = await import('node:quic');
const { createPrivateKey } = await import('node:crypto');
const key = createPrivateKey(readKey('agent1-key.pem'));
const cert = readKey('agent1-cert.pem');
const encoder = new TextEncoder();
// --- H3 stream destroyed after idle timeout ---
{
const streamDestroyed = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
// Don't read — let the stream sit idle after the initial headers.
// The stream idle timeout should destroy it, rejecting stream.closed.
await rejects(stream.closed, {
code: 'ERR_QUIC_TRANSPORT_ERROR',
});
streamDestroyed.resolve();
});
}), {
sni: { '*': { keys: [key], certs: [cert] } },
streamIdleTimeout: 100,
onheaders() {
// Receive headers but do nothing — let the stream go idle.
},
});
const clientSession = await connect(serverEndpoint.address, {
servername: 'localhost',
verifyPeer: 'manual',
transportParams: { maxIdleTimeout: 1 },
});
await clientSession.opened;
// Send a POST request with a body byte so the server creates the
// stream, then stop sending (don't end the write side).
const stream = await clientSession.createBidirectionalStream({
headers: {
':method': 'POST',
':path': '/',
':scheme': 'https',
':authority': 'localhost',
},
onheaders() {},
});
const writer = stream.writer;
writer.writeSync(encoder.encode('x'));
// Wait for the server to destroy the idle stream.
await streamDestroyed.promise;
// The server sent STOP_SENDING / RESET_STREAM when it destroyed the
// idle stream. ShutdownStream maps the transport error to the H3
// internal error code (0x102) on the wire.
await rejects(stream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
await clientSession.close();
await serverEndpoint.close();
}
// --- H3 stream with ongoing data is NOT destroyed ---
{
const serverGotData = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
const data = await text(stream);
strictEqual(data, 'xy');
serverGotData.resolve();
await serverSession.close();
});
}), {
sni: { '*': { keys: [key], certs: [cert] } },
streamIdleTimeout: 500,
onheaders: mustCall(function(headers) {
strictEqual(headers[':method'], 'POST');
// Send response headers so the stream is fully established.
this.sendHeaders({ ':status': '200' }, { terminal: true });
}),
});
const clientSession = await connect(serverEndpoint.address, {
servername: 'localhost',
verifyPeer: 'manual',
});
await clientSession.opened;
const stream = await clientSession.createBidirectionalStream({
onheaders() {},
});
stream.sendHeaders({
':method': 'POST',
':path': '/',
':scheme': 'https',
':authority': 'localhost',
'content-length': '2',
}, { terminal: false });
const writer = stream.writer;
writer.writeSync(encoder.encode('x'));
// Wait less than the 500ms idle timeout, then send more data.
await setTimeout(300);
writer.writeSync(encoder.encode('y'));
writer.endSync();
await Promise.all([serverGotData.promise, clientSession.closed]);
await serverEndpoint.close();
}
// --- Disabled when set to 0 ---
{
const streamSurvived = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
const data = await text(stream);
strictEqual(data, 'xy');
streamSurvived.resolve();
});
await setTimeout(700);
await serverSession.close();
}), {
sni: { '*': { keys: [key], certs: [cert] } },
streamIdleTimeout: 0, // Disabled
onheaders: mustCall(function(headers) {
this.sendHeaders({ ':status': '200' }, { terminal: true });
}),
});
const clientSession = await connect(serverEndpoint.address, {
servername: 'localhost',
verifyPeer: 'manual',
});
await clientSession.opened;
const stream = await clientSession.createBidirectionalStream({
onheaders() {},
});
stream.sendHeaders({
':method': 'POST',
':path': '/',
':scheme': 'https',
':authority': 'localhost',
}, { terminal: false });
const writer = stream.writer;
writer.writeSync(encoder.encode('x'));
// Pause beyond any reasonable idle timeout to verify it's disabled.
await setTimeout(600);
writer.writeSync(encoder.encode('y'));
writer.endSync();
await Promise.all([streamSurvived.promise, clientSession.closed]);
await serverEndpoint.close();
}
@@ -231,6 +231,7 @@ strictEqual(typeof sessionStats.datagramsReceived, 'bigint');
strictEqual(typeof sessionStats.datagramsSent, 'bigint');
strictEqual(typeof sessionStats.datagramsAcknowledged, 'bigint');
strictEqual(typeof sessionStats.datagramsLost, 'bigint');
strictEqual(typeof sessionStats.streamsIdleTimedOut, 'bigint');
strictEqual(typeof sessionStats.toJSON(), 'object');
strictEqual(typeof inspect(sessionStats), 'string');
streamStats[kFinishClose]();
@@ -28,11 +28,7 @@ const { listen, connect } = await import('../common/quic.mjs');
const serverResetSeen = Promise.withResolvers();
const serverEndpoint = await listen(mustCall((serverSession) => {
serverSession.onstream = mustCall((stream) => {
// The cascade-driven destroy of the server-side stream after the
// peer reset rejects `stream.closed` with the wire error; the
// test does not assert on its specific shape, only that `onreset`
// fired with the expected code.
serverSession.onstream = mustCall(async (stream) => {
stream.onreset = mustCall((err) => {
strictEqual(err.code, 'ERR_QUIC_APPLICATION_ERROR');
// The DefaultApplication's internal error code is 0x1n, which
@@ -41,6 +37,12 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
`expected '1n' in message, got: ${err.message}`);
serverResetSeen.resolve();
});
// The peer's reset causes stream.closed to reject with the reset
// error code.
await rejects(stream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
});
}));
@@ -35,7 +35,7 @@ const { listen, connect } = await import('../common/quic.mjs');
const serverObservation = Promise.withResolvers();
const serverEndpoint = await listen(mustCall((serverSession) => {
serverSession.onstream = mustCall((stream) => {
serverSession.onstream = mustCall(async (stream) => {
const writer = stream.writer;
// Sanity: the writer is active before the peer tears the stream
// down, so desiredSize is a number reflecting the initial
@@ -58,6 +58,11 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
serverObservation.resolve(writer.desiredSize);
});
});
// The peer's reset causes stream.closed to reject.
await assert.rejects(stream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
});
}));
@@ -24,13 +24,19 @@ const { listen, connect } = await import('../common/quic.mjs');
const serverResetSeen = Promise.withResolvers();
const serverEndpoint = await listen(mustCall((serverSession) => {
serverSession.onstream = mustCall((stream) => {
serverSession.onstream = mustCall(async (stream) => {
stream.onreset = mustCall((err) => {
strictEqual(err.code, 'ERR_QUIC_APPLICATION_ERROR');
ok(err.message.includes('66n'),
`expected '66n' in message, got: ${err.message}`);
serverResetSeen.resolve();
});
// The peer's reset causes stream.closed to reject with the reset
// error code.
await rejects(stream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
});
}));
@@ -0,0 +1,141 @@
// Flags: --experimental-quic --experimental-stream-iter --no-warnings
// Test: stream idle timeout.
// Peer-initiated streams that receive no data within the configured
// timeout are automatically destroyed.
import { hasQuic, skip, mustCall } from '../common/index.mjs';
import assert from 'node:assert';
import { setTimeout } from 'node:timers/promises';
import { text } from 'node:stream/iter';
const { rejects, strictEqual } = assert;
if (!hasQuic) {
skip('QUIC is not enabled');
}
const { listen, connect } = await import('../common/quic.mjs');
// --- Stream destroyed after idle timeout ---
{
const streamDestroyed = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
// Don't read — let the stream sit idle after the initial data.
// The stream idle timeout should destroy it, rejecting stream.closed.
await rejects(stream.closed, {
code: 'ERR_QUIC_TRANSPORT_ERROR',
});
streamDestroyed.resolve();
});
}), {
// Short idle timeout for the test — 500ms.
streamIdleTimeout: 100,
});
const clientSession = await connect(serverEndpoint.address, {
verifyPeer: 'manual',
transportParams: { maxIdleTimeout: 1 },
});
await clientSession.opened;
// Open a stream and send one byte so the server creates the
// peer-initiated stream, then stop sending.
const clientStream = await clientSession.createUnidirectionalStream();
const writer = clientStream.writer;
writer.writeSync('x');
// Wait for the server to destroy the idle stream.
await streamDestroyed.promise;
// The server sent STOP_SENDING when it destroyed the idle stream.
// ShutdownStream maps the transport error to the application's
// internal error code on the wire, so the client sees an application
// error indicating the server rejected the stream.
await rejects(clientStream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
await clientSession.close();
await serverEndpoint.close();
}
// --- Stream with data is NOT destroyed ---
{
const encoder = new TextEncoder();
const serverGotData = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
const data = await text(stream);
strictEqual(data, 'xy');
serverGotData.resolve();
await serverSession.close();
});
}), {
streamIdleTimeout: 500,
});
const clientSession = await connect(serverEndpoint.address, {
verifyPeer: 'manual',
});
await clientSession.opened;
// Open a stream and send data immediately.
const clientStrema = await clientSession.createUnidirectionalStream();
const writer = clientStrema.writer;
writer.writeSync(encoder.encode('x'));
// Less than the 500ms idle timeout.
await setTimeout(300);
writer.writeSync(encoder.encode('y'));
writer.endSync();
await Promise.all([serverGotData.promise, clientSession.closed]);
await serverEndpoint.close();
}
// --- Disabled when set to 0 ---
{
const streamSurvived = Promise.withResolvers();
const serverEndpoint = await listen(mustCall(async (serverSession) => {
serverSession.onstream = mustCall(async (stream) => {
// Do not await this yet.
const data = await text(stream);
// We should receive all the data, even though it is sent with a pause
// longer than the default idle timeout.
strictEqual(data, 'xy');
streamSurvived.resolve();
});
await setTimeout(700);
await serverSession.close();
}), {
streamIdleTimeout: 0, // Disabled
});
const clientSession = await connect(serverEndpoint.address);
await clientSession.opened;
// Send one byte so the server creates the stream, then stop.
const clientStream = await clientSession.createUnidirectionalStream();
const writer = clientStream.writer;
writer.writeSync('x');
// Now pause beyond the 500ms default timeout to verify the stream is not
// killed by idle timeout.
await setTimeout(600);
writer.writeSync('y');
writer.endSync();
await Promise.all([streamSurvived.promise, clientSession.closed]);
await serverEndpoint.close();
}
@@ -60,7 +60,7 @@ const allDone = Promise.withResolvers();
const observed = [];
const serverEndpoint = await listen(mustCall((serverSession) => {
serverSession.onstream = mustCall((stream) => {
serverSession.onstream = mustCall(async (stream) => {
const i = nextStreamIndex++;
stream.onreset = mustCall((err) => {
observed[i] = wireCodeOf(err);
@@ -69,6 +69,11 @@ const serverEndpoint = await listen(mustCall((serverSession) => {
allDone.resolve();
}
});
// The peer's reset causes stream.closed to reject.
await assert.rejects(stream.closed, {
code: 'ERR_QUIC_APPLICATION_ERROR',
});
}, 2);
}));