Commit d8333204b67 for nodejs
commit d8333204b67dee34e1d97b2b2cfe123d2df2305d
Author: Yuya Inoue <65857152+inoway46@users.noreply.github.com>
Date: Fri Nov 27 21:32:01 2026 +0900
http2: add signal to compat request
Add `request.signal` to `Http2ServerRequest`, matching
`message.signal` in HTTP/1. The signal follows the stream, not the
socket: it is aborted when the stream closes before the response has
been sent completely.
Refs: https://github.com/nodejs/node/pull/62541
Refs: https://github.com/nodejs/node/pull/64392
Signed-off-by: inoway46 <inoueyuya416@gmail.com>
Assisted-by: Claude Code
PR-URL: https://github.com/nodejs/node/pull/67774
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
diff --git a/doc/api/http2.md b/doc/api/http2.md
index 23b2d5388b8..a3c1f1cbf02 100644
--- a/doc/api/http2.md
+++ b/doc/api/http2.md
@@ -4490,6 +4490,53 @@ the server, then [`Http2Stream`][]s are destroyed when they time out. If a
handler is assigned to the request, the response, or the server's `'timeout'`
events, timed out sockets must be handled explicitly.
+#### `request.signal`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* Type: {AbortSignal}
+
+An {AbortSignal} that is aborted when the underlying [`Http2Stream`][] is
+closed before the response has been sent completely. Other streams on the
+same session do not affect the signal.
+The signal is created lazily on first access — no {AbortController} is
+allocated for requests that never use this property.
+
+This is useful for cancelling downstream asynchronous work such as database
+queries or `fetch` calls when a client cancels the request.
+
+```mjs
+import http2 from 'node:http2';
+
+http2.createServer(async (req, res) => {
+ try {
+ const data = await fetch('https://example.com/api', { signal: req.signal });
+ res.end(JSON.stringify(await data.json()));
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ res.statusCode = 500;
+ res.end('Internal Server Error');
+ }
+}).listen(3000);
+```
+
+```cjs
+const http2 = require('node:http2');
+
+http2.createServer(async (req, res) => {
+ try {
+ const data = await fetch('https://example.com/api', { signal: req.signal });
+ res.end(JSON.stringify(await data.json()));
+ } catch (err) {
+ if (err.name === 'AbortError') return;
+ res.statusCode = 500;
+ res.end('Internal Server Error');
+ }
+}).listen(3000);
+```
+
#### `request.socket`
<!-- YAML
diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js
index e7ff3bc1f0c..7b7054b072e 100644
--- a/lib/internal/http2/compat.js
+++ b/lib/internal/http2/compat.js
@@ -11,6 +11,8 @@ const {
Symbol,
} = primordials;
+const { AbortController } = require('internal/abort_controller');
+
const assert = require('internal/assert');
const Stream = require('stream');
const { Readable } = Stream;
@@ -60,6 +62,7 @@ const {
kRequest,
kProxySocket,
kIncomplete,
+ kLocalClose,
assertValidPseudoHeader,
getAuthority,
} = require('internal/http2/util');
@@ -77,6 +80,7 @@ const kRawTrailers = Symbol('rawTrailers');
const kSetHeader = Symbol('setHeader');
const kAppendHeader = Symbol('appendHeader');
const kAborted = Symbol('aborted');
+const kAbortController = Symbol('kAbortController');
let statusMessageWarned = false;
let statusConnectionHeaderWarned = false;
@@ -192,10 +196,26 @@ function onStreamAbortedRequest() {
const request = this[kRequest];
if (request !== undefined && request[kState].closed === false) {
request[kAborted] = true;
+ // Abort before emitting so that 'aborted' listeners observe an aborted
+ // signal whether or not it was accessed before.
+ abortRequestSignal(request);
request.emit('aborted');
}
}
+// Like HTTP/1, where the signal is detached once the response finishes, a
+// stream that closes after the whole response was sent completed normally.
+// The response is complete once the frame that ends the stream was sent.
+function isResponseComplete(stream) {
+ return stream[kLocalClose];
+}
+
+function abortRequestSignal(request) {
+ const ac = request[kAbortController];
+ if (ac !== null)
+ ac.abort();
+}
+
function onStreamAbortedResponse() {
// non-op for now
}
@@ -300,6 +320,9 @@ function onStreamCloseRequest() {
this[kProxySocket] = null;
this[kRequest] = undefined;
+ if (!isResponseComplete(this))
+ abortRequestSignal(req);
+
// The peer closed the stream before END_STREAM, so the request body is
// incomplete. Like http1's IncomingMessage on abort, destroy the request
// instead of ending it, so 'end' is not emitted for a truncated body.
@@ -348,6 +371,7 @@ class Http2ServerRequest extends Readable {
this[kRawTrailers] = [];
this[kStream] = stream;
this[kAborted] = false;
+ this[kAbortController] = null;
stream[kProxySocket] = null;
stream[kRequest] = this;
@@ -366,6 +390,18 @@ class Http2ServerRequest extends Readable {
return this[kAborted];
}
+ get signal() {
+ let ac = this[kAbortController];
+ if (ac === null) {
+ ac = this[kAbortController] = new AbortController();
+ if (this[kAborted] ||
+ (this[kState].closed && !isResponseComplete(this[kStream]))) {
+ ac.abort();
+ }
+ }
+ return ac.signal;
+ }
+
get complete() {
return this[kAborted] ||
this.readableEnded ||
diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js
index 8ec7ac3aa01..2290af5d998 100644
--- a/lib/internal/http2/core.js
+++ b/lib/internal/http2/core.js
@@ -150,6 +150,7 @@ const {
getSessionState,
getSettings,
getStreamState,
+ isStreamLocalClosed,
isPayloadMeaningless,
kAuthority,
kAutoEmptyTrailers,
@@ -159,6 +160,7 @@ const {
kSocket,
kRequest,
kIncomplete,
+ kLocalClose,
kProtocol,
kProxySocket,
MAX_ADDITIONAL_SETTINGS,
@@ -623,6 +625,18 @@ function maybeDestroyNaturalClose() {
this.destroy();
}
+// The compat layer needs to know whether the response was sent completely
+// when the stream closes. The writable state cannot tell, because the frame
+// that ends the stream (the last DATA frame or the trailers) may still be
+// pending after the writable side has finished. Ask nghttp2 while the handle
+// is still around. Only streams with a compat request pay for this.
+function recordLocalClose(stream, handle) {
+ if (stream[kRequest] !== undefined && !stream[kLocalClose] &&
+ isStreamLocalClosed(handle)) {
+ stream[kLocalClose] = true;
+ }
+}
+
// Fired by C++ when nghttp2's on_stream_close fires. `peerReset` is
// true when the peer sent a RST_STREAM frame - peer RST_STREAM(NO_ERROR)
// is otherwise indistinguishable from a clean END_STREAM exchange at
@@ -642,6 +656,8 @@ function onStreamClose(code, peerReset) {
if (!stream || stream.destroyed)
return false;
+ recordLocalClose(stream, this);
+
debugStreamObj(
stream, 'closed code=%d peerReset=%s closed=%s',
code, peerReset, stream.closed,
@@ -2287,6 +2303,7 @@ class Http2Stream extends Duplex {
this._readableState.readingMore = true;
this[kTimeout] = null;
+ this[kLocalClose] = false;
this[kState] = {
didRead: false,
@@ -2732,6 +2749,9 @@ class Http2Stream extends Duplex {
const sessionState = session[kState];
const sessionCode = sessionState.goawayCode || sessionState.destroyCode;
+ if (handle !== undefined)
+ recordLocalClose(this, handle);
+
// If a stream has already closed successfully, there is no error
// to report from this stream, even if the session has errored.
// This can happen if the stream was already in process of destroying
diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js
index 4d5db68ac23..ab50ef48b15 100644
--- a/lib/internal/http2/util.js
+++ b/lib/internal/http2/util.js
@@ -47,6 +47,7 @@ const kProtocol = Symbol('protocol');
const kProxySocket = Symbol('proxySocket');
const kRequest = Symbol('request');
const kIncomplete = Symbol('incomplete');
+const kLocalClose = Symbol('localClose');
const {
NGHTTP2_NV_FLAG_NONE,
@@ -588,6 +589,13 @@ function getStreamState(stream) {
};
}
+// Whether the local side of the stream is closed at the protocol level, that
+// is, whether a frame with the END_STREAM flag has been sent.
+function isStreamLocalClosed(stream) {
+ stream.refreshState();
+ return streamState[IDX_STREAM_STATE_LOCAL_CLOSE] === 1;
+}
+
function isIllegalConnectionSpecificHeader(name, value) {
switch (name) {
case HTTP2_HEADER_CONNECTION:
@@ -996,6 +1004,7 @@ module.exports = {
getSessionState,
getSettings,
getStreamState,
+ isStreamLocalClosed,
isPayloadMeaningless,
kAuthority,
kAutoEmptyTrailers,
@@ -1005,6 +1014,7 @@ module.exports = {
kSocket,
kProtocol,
kIncomplete,
+ kLocalClose,
kProxySocket,
kRequest,
MAX_ADDITIONAL_SETTINGS,
diff --git a/test/parallel/test-http2-compat-serverrequest-signal.js b/test/parallel/test-http2-compat-serverrequest-signal.js
new file mode 100644
index 00000000000..27ffca5602a
--- /dev/null
+++ b/test/parallel/test-http2-compat-serverrequest-signal.js
@@ -0,0 +1,337 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+ common.skip('missing crypto');
+const assert = require('assert');
+const http2 = require('http2');
+
+const { NGHTTP2_CANCEL } = http2.constants;
+
+function getAbortController(req) {
+ const sym = Object.getOwnPropertySymbols(req)
+ .find((s) => s.description === 'kAbortController');
+ return req[sym];
+}
+
+function withServer(onRequest, onListen) {
+ const server = http2.createServer(onRequest);
+ server.listen(0, common.mustCall(() => {
+ const client = http2.connect(`http://localhost:${server.address().port}`);
+ onListen(server, client);
+ }));
+}
+
+// The signal is created lazily, the same object is returned on every access,
+// and it is not aborted when the request and response complete normally.
+{
+ const body = 'hello world';
+ withServer(common.mustCall((req, res) => {
+ assert.strictEqual(getAbortController(req), null);
+ const { signal } = req;
+ assert.ok(signal instanceof AbortSignal);
+ assert.strictEqual(req.signal, signal);
+ assert.strictEqual(signal.aborted, false);
+ signal.onabort = common.mustNotCall();
+
+ let data = '';
+ req.setEncoding('utf8');
+ req.on('data', (chunk) => data += chunk);
+ req.on('end', common.mustCall(() => {
+ assert.strictEqual(data, body);
+ assert.strictEqual(signal.aborted, false);
+ res.end('ok');
+ }));
+ req.on('close', common.mustCall(() => {
+ assert.strictEqual(req.aborted, false);
+ assert.strictEqual(signal.aborted, false);
+ }));
+ }), common.mustCall((server, client) => {
+ const req = client.request({ ':method': 'POST' });
+ req.resume();
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ req.end(body);
+ }));
+}
+
+// A signal first accessed after the stream completed normally is not aborted.
+{
+ withServer(common.mustCall((req, res) => {
+ req.on('close', common.mustCall(() => {
+ assert.strictEqual(req.signal.aborted, false);
+ }));
+ res.end();
+ }), common.mustCall((server, client) => {
+ const req = client.request();
+ req.resume();
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// The signal is not aborted when the stream is reset after the response was
+// sent completely, even though the request body is incomplete. In HTTP/1 the
+// signal is likewise detached once the response finishes.
+{
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustNotCall();
+ req.on('close', common.mustCall(() => {
+ assert.strictEqual(req.signal.aborted, false);
+ }));
+ res.end();
+ }), common.mustCall((server, client) => {
+ const req = client.request({ ':method': 'POST' });
+ req.write('partial');
+ req.resume();
+ req.on('response', common.mustCall());
+ req.on('end', common.mustCall(() => {
+ req.close(NGHTTP2_CANCEL);
+ }));
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// Resetting one stream aborts only that stream's signal, not the signal of
+// another stream on the same session.
+{
+ const requests = [];
+ withServer(common.mustCall((req, res) => {
+ requests.push({ req, res });
+ if (requests.length < 2)
+ return;
+
+ const [cancelled, other] = requests;
+ other.req.signal.onabort = common.mustNotCall();
+ cancelled.req.signal.onabort = common.mustCall(() => {
+ assert.strictEqual(other.req.signal.aborted, false);
+ other.res.end('ok');
+ });
+ cancelled.req.on('close', common.mustCall(() => {
+ assert.strictEqual(cancelled.req.aborted, true);
+ assert.strictEqual(cancelled.req.signal.aborted, true);
+ }));
+ cancelled.res.on('close', common.mustCall());
+ cancelled.req.stream.session.emit('both-received');
+ }, 2), common.mustCall((server, client) => {
+ const cancelled = client.request({ ':path': '/cancelled' });
+ cancelled.on('error', common.mustNotCall());
+ cancelled.on('close', common.mustCall(() => {
+ assert.strictEqual(cancelled.rstCode, NGHTTP2_CANCEL);
+ }));
+
+ const other = client.request({ ':path': '/other' });
+ other.resume();
+ other.on('response', common.mustCall((headers) => {
+ assert.strictEqual(headers[':status'], 200);
+ }));
+ other.on('close', common.mustCall(() => {
+ assert.strictEqual(other.rstCode, 0);
+ client.close();
+ server.close();
+ }));
+
+ server.once('session', common.mustCall((session) => {
+ session.once('both-received', common.mustCall(() => {
+ cancelled.close(NGHTTP2_CANCEL);
+ }));
+ }));
+ }));
+}
+
+// An 'aborted' listener observes an aborted signal, whether the signal was
+// accessed before the stream was reset or is first accessed in the listener.
+{
+ let pending = 2;
+ withServer(common.mustCall((req, res) => {
+ if (req.url === '/early')
+ assert.strictEqual(req.signal.aborted, false);
+ req.on('aborted', common.mustCall(() => {
+ assert.strictEqual(req.signal.aborted, true);
+ }));
+ req.stream.session.emit('received', req.url);
+ }, 2), common.mustCall((server, client) => {
+ const requests = {
+ '/early': client.request({ ':path': '/early' }),
+ '/late': client.request({ ':path': '/late' }),
+ };
+ for (const req of Object.values(requests)) {
+ req.on('close', common.mustCall(() => {
+ if (--pending === 0) {
+ client.close();
+ server.close();
+ }
+ }));
+ }
+ server.once('session', common.mustCall((session) => {
+ session.on('received', common.mustCall((url) => {
+ requests[url].close(NGHTTP2_CANCEL);
+ }, 2));
+ }));
+ }));
+}
+
+// The signal is not aborted when the response completes with trailers, or
+// when the headers are flushed before the response is ended.
+{
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustNotCall();
+ req.on('close', common.mustCall(() => {
+ assert.strictEqual(req.signal.aborted, false);
+ }));
+ if (req.url === '/trailers') {
+ res.addTrailers({ 'x-trailer': 'value' });
+ res.end('body');
+ } else {
+ res.flushHeaders();
+ res.end('body');
+ }
+ }, 2), common.mustCall((server, client) => {
+ const withTrailers = client.request({ ':path': '/trailers' });
+ withTrailers.resume();
+ withTrailers.on('trailers', common.mustCall((trailers) => {
+ assert.strictEqual(trailers['x-trailer'], 'value');
+ }));
+ withTrailers.on('close', common.mustCall(() => {
+ const flushed = client.request({ ':path': '/flushed' });
+ flushed.resume();
+ flushed.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+ }));
+}
+
+// The signal is aborted when the stream is destroyed after the writable side
+// finished but before the frame that ends the stream was sent: with a body
+// and trailers, with trailers only, and with neither.
+{
+ const cases = {
+ '/body-and-trailers'(res, cb) {
+ res.addTrailers({ 'x-trailer': 'value' });
+ res.end('body', cb);
+ },
+ '/trailers-only'(res, cb) {
+ res.flushHeaders();
+ res.addTrailers({ 'x-trailer': 'value' });
+ res.end(cb);
+ },
+ '/empty'(res, cb) {
+ res.flushHeaders();
+ res.end(cb);
+ },
+ };
+ const paths = Object.keys(cases);
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustCall();
+ cases[req.url](res, common.mustCall(() => {
+ assert.strictEqual(res.stream.writableFinished, true);
+ assert.strictEqual(req.signal.aborted, false);
+ res.destroy();
+ }));
+ }, paths.length), common.mustCall((server, client) => {
+ let pending = paths.length;
+ for (const path of paths) {
+ const req = client.request({ ':path': path });
+ req.resume();
+ req.on('trailers', common.mustNotCall());
+ req.on('error', () => {});
+ req.on('close', common.mustCall(() => {
+ if (--pending === 0) {
+ client.close();
+ server.close();
+ }
+ }));
+ }
+ }));
+}
+
+// A signal first accessed after the stream was reset is already aborted.
+{
+ withServer(common.mustCall((req, res) => {
+ req.on('close', common.mustCall(() => {
+ assert.strictEqual(req.signal.aborted, true);
+ }));
+ req.stream.session.emit('received');
+ }), common.mustCall((server, client) => {
+ const req = client.request();
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ server.once('session', common.mustCall((session) => {
+ session.once('received', common.mustCall(() => {
+ req.close(NGHTTP2_CANCEL);
+ }));
+ }));
+ }));
+}
+
+// Destroying the response before it completes aborts the signal.
+{
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustCall();
+ res.destroy();
+ }), common.mustCall((server, client) => {
+ const req = client.request();
+ req.on('error', () => {});
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ }));
+}
+
+// A HEAD request reset before the response is sent aborts the signal.
+{
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustCall();
+ req.stream.session.emit('received');
+ }), common.mustCall((server, client) => {
+ const req = client.request({ ':method': 'HEAD' });
+ req.on('close', common.mustCall(() => {
+ client.close();
+ server.close();
+ }));
+ server.once('session', common.mustCall((session) => {
+ session.once('received', common.mustCall(() => {
+ req.close(NGHTTP2_CANCEL);
+ }));
+ }));
+ }));
+}
+
+// When the connection is lost, the signals of all pending streams on it are
+// aborted.
+{
+ const aborted = [];
+ withServer(common.mustCall((req, res) => {
+ req.signal.onabort = common.mustCall(() => {
+ aborted.push(req.url);
+ if (aborted.length === 2)
+ req.stream.session.emit('all-aborted');
+ });
+ if (req.url === '/second')
+ req.stream.session.emit('both-received');
+ }, 2), common.mustCall((server, client) => {
+ client.request({ ':path': '/first' }).on('error', () => {});
+ client.request({ ':path': '/second' }).on('error', () => {});
+ server.once('session', common.mustCall((session) => {
+ session.once('both-received', common.mustCall(() => {
+ client.destroy();
+ }));
+ session.once('all-aborted', common.mustCall(() => {
+ assert.deepStrictEqual(aborted.sort(), ['/first', '/second']);
+ server.close();
+ }));
+ }));
+ }));
+}