Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions benchmark/quic/h3-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
'use strict';

// Measures a complete HTTP/3 exchange: establish a session, send one request
// and read the whole response. Run in two modes, so the cost of a resumed
// 0-RTT session can be compared against a full handshake.
//
// The 0-RTT mode needs a session ticket, which can only come from an earlier
// connection. That first connection is made during warmup, outside the
// measured region, so what is timed is only the resumed exchange.

const common = require('../common.js');
const fixtures = require('../../test/common/fixtures');
const { createPrivateKey } = require('crypto');

const bench = common.createBenchmark(main, {
// '0rtt' resumes from a ticket and sends the request in the very first
// flight; '1rtt' is a fresh session each time. 0-RTT is listed first so
// that it is the mode the benchmark CI test exercises.
mode: ['0rtt', '1rtt'],
n: [500],
}, { flags: ['--experimental-quic', '--experimental-stream-iter',
'--no-warnings'] });

async function main({ mode, n }) {
const { listen, connect } = require('node:quic');
const { bytes } = require('stream/iter');

const key = createPrivateKey(fixtures.readKey('agent1-key.pem'));
const cert = fixtures.readKey('agent1-cert.pem');
const body = new TextEncoder().encode('x'.repeat(256));
const decoder = new TextDecoder();

const request = {
':method': 'GET',
':path': '/',
':scheme': 'https',
':authority': 'localhost',
};

const endpoint = await listen((session) => {
session.opened.catch(() => {});
session.closed.catch(() => {});
session.onstream = (stream) => { stream.closed.catch(() => {}); };
}, {
sni: { '*': { keys: [key], certs: [cert] } },
onheaders() {
this.sendHeaders({ ':status': '200' });
this.writer.writeSync(body);
this.writer.endSync();
},
endpoint: {
maxConnectionsPerHost: 0xFFFF,
maxConnectionsTotal: 0xFFFF,
sessionCreationRate: 1_000_000,
sessionCreationBurst: 1_000_000,
},
});

const address = endpoint.address;
let received = 0;
const onheaders = () => { received++; };

// A full handshake, one request, one response. When resume is supplied the
// request goes out in the first flight, before the handshake completes.
async function exchange(resume) {
const session = await connect(address, {
servername: 'localhost',
verifyPeer: 'manual',
alpn: 'h3',
...resume,
});
const stream = await session.createBidirectionalStream({
headers: request,
onheaders,
});
if (resume === undefined) await session.opened;
const response = decoder.decode(await bytes(stream));
if (response.length !== body.length) {
throw new Error(`short response: ${response.length}`);
}
session.close();
await session.closed.catch(() => {});
return session;
}

// Collect a ticket for the 0-RTT mode from a connection that is not timed.
let resume;
if (mode === '0rtt') {
const { promise, resolve } = Promise.withResolvers();
let ticket;
let token;
const session = await connect(address, {
servername: 'localhost',
verifyPeer: 'manual',
alpn: 'h3',
onsessionticket(value) {
ticket ??= value;
if (token !== undefined) resolve();
},
onnewtoken(value) {
token ??= value;
if (ticket !== undefined) resolve();
},
});
await session.opened;
await promise;
session.close();
await session.closed.catch(() => {});
resume = { sessionTicket: ticket, token };
}

// The timed 0-RTT exchanges deliberately never await session.opened, since
// waiting for the handshake is exactly what 0-RTT avoids. That leaves no
// opportunity to notice early data being refused, so check separately -
// otherwise a ticket the server stopped accepting would quietly turn this
// into a measurement of the 1-RTT path.
async function checkEarlyDataAccepted() {
const session = await connect(address, {
servername: 'localhost',
verifyPeer: 'manual',
alpn: 'h3',
...resume,
});
const stream = await session.createBidirectionalStream({
headers: request,
onheaders,
});
const info = await session.opened;
await bytes(stream);
session.close();
await session.closed.catch(() => {});
if (!info.earlyDataAccepted) {
throw new Error('0-RTT was not accepted, benchmark would be invalid');
}
}

for (let i = 0; i < 20; i++) await exchange(resume);
if (mode === '0rtt') await checkEarlyDataAccepted();

received = 0;
bench.start();
for (let i = 0; i < n; i++) await exchange(resume);
bench.end(n);

if (received !== n) throw new Error(`missing responses: ${received}/${n}`);
// The ticket is reused for every iteration, so confirm it was still being
// accepted at the end of the run and not just at the start.
if (mode === '0rtt') await checkEarlyDataAccepted();
await endpoint.close();
}
74 changes: 74 additions & 0 deletions benchmark/quic/handshake.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
'use strict';

// Measures the cost of establishing QUIC sessions: how many complete
// handshakes per second a single endpoint can serve, for raw QUIC and for
// HTTP/3. Nothing is sent on the session beyond what the protocol itself
// requires, so this isolates connection setup rather than data transfer.

const common = require('../common.js');
const fixtures = require('../../test/common/fixtures');
const { createPrivateKey } = require('crypto');

const bench = common.createBenchmark(main, {
// 'raw' negotiates a non-HTTP ALPN and does no application work.
// 'h3' negotiates HTTP/3, so the server also builds an nghttp3 connection
// and its control/QPACK streams for every session.
protocol: ['raw', 'h3'],
concurrency: [1, 10],
n: [1000],
}, { flags: ['--experimental-quic', '--no-warnings'] });

async function main({ protocol, concurrency, n }) {
const { listen, connect } = require('node:quic');

const key = createPrivateKey(fixtures.readKey('agent1-key.pem'));
const cert = fixtures.readKey('agent1-cert.pem');
const alpn = protocol === 'h3' ? 'h3' : 'quic-bench';

const endpoint = await listen((session) => {
// A benchmark peer never reads these; swallow so a torn-down session
// cannot produce an unhandled rejection.
session.opened.catch(() => {});
session.closed.catch(() => {});
}, {
sni: { '*': { keys: [key], certs: [cert] } },
alpn: [alpn],
// The defaults rate-limit session creation per host, which a benchmark
// hammering a single address would otherwise trip.
endpoint: {
maxConnectionsPerHost: 0xFFFF,
maxConnectionsTotal: 0xFFFF,
sessionCreationRate: 1_000_000,
sessionCreationBurst: 1_000_000,
},
});

const address = endpoint.address;

async function handshake() {
const session = await connect(address, {
servername: 'localhost',
verifyPeer: 'manual',
alpn,
});
await session.opened;
session.close();
await session.closed.catch(() => {});
}

async function run(count) {
for (let i = 0; i < count; i += concurrency) {
const batch = Math.min(concurrency, count - i);
await Promise.all(Array.from({ length: batch }, handshake));
}
}

// Warm up the TLS and QUIC machinery before measuring.
await run(Math.min(100, n));

bench.start();
await run(n);
bench.end(n);

await endpoint.close();
}
8 changes: 4 additions & 4 deletions doc/api/quic.md
Original file line number Diff line number Diff line change
Expand Up @@ -2954,10 +2954,10 @@ The ALPN (Application-Layer Protocol Negotiation) identifier(s).
For **client** sessions, this is a single string specifying the protocol
the client wants to use (e.g. `'h3'`).

For **server** sessions, this is an array of protocol names in preference
order that the server supports (e.g. `['h3', 'h3-29']`). During the TLS
handshake, the server selects the first protocol from its list that the
client also supports.
For **server** sessions, this is a non-empty array of protocol names in
preference order that the server supports (e.g. `['h3', 'h3-29']`).
During the TLS handshake, the server selects the first protocol from its
list that the client also supports.

The negotiated ALPN determines which Application implementation is used
for the session. `'h3'` and `'h3-*'` variants select the HTTP/3
Expand Down
6 changes: 6 additions & 0 deletions lib/internal/quic/quic.js
Original file line number Diff line number Diff line change
Expand Up @@ -5144,6 +5144,12 @@ function processTlsOptions(tls, forServer) {
if (!forServer) {
validateString(alpn, 'options.alpn');
}
// QUIC has no default application protocol: a server that offers none
// cannot complete a handshake with anyone.
if (protocols.length === 0) {
throw new ERR_INVALID_ARG_VALUE('options.alpn', alpn,
'must offer at least one protocol');
}
Comment thread
pimterry marked this conversation as resolved.
let totalLen = 0;
for (let i = 0; i < protocols.length; i++) {
validateString(protocols[i], `options.alpn[${i}]`);
Expand Down
2 changes: 2 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@
'src/crypto/crypto_sig.cc',
'src/crypto/crypto_timing.cc',
'src/crypto/crypto_cipher.cc',
'src/crypto/crypto_client_hello.cc',
'src/crypto/crypto_context.cc',
'src/crypto/crypto_tls_certificates.cc',
'src/crypto/crypto_ec.cc',
Expand Down Expand Up @@ -420,6 +421,7 @@
'src/crypto/crypto_spkac.h',
'src/crypto/crypto_util.h',
'src/crypto/crypto_cipher.h',
'src/crypto/crypto_client_hello.h',
'src/crypto/crypto_common.h',
'src/crypto/crypto_dsa.h',
'src/crypto/crypto_hash.h',
Expand Down
Loading
Loading