Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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