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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions doc/api/http2.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions lib/internal/http2/compat.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -59,6 +61,7 @@ const {
kRequest,
kProxySocket,
kIncomplete,
kLocalClose,
assertValidPseudoHeader,
getAuthority,
} = require('internal/http2/util');
Expand All @@ -76,6 +79,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;
Expand Down Expand Up @@ -191,10 +195,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
}
Expand Down Expand Up @@ -299,6 +319,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.
Expand Down Expand Up @@ -347,6 +370,7 @@ class Http2ServerRequest extends Readable {
this[kRawTrailers] = [];
this[kStream] = stream;
this[kAborted] = false;
this[kAbortController] = null;
stream[kProxySocket] = null;
stream[kRequest] = this;

Expand All @@ -365,6 +389,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 ||
Expand Down
20 changes: 20 additions & 0 deletions lib/internal/http2/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ const {
getSessionState,
getSettings,
getStreamState,
isStreamLocalClosed,
isPayloadMeaningless,
kAuthority,
kAutoEmptyTrailers,
Expand All @@ -159,6 +160,7 @@ const {
kSocket,
kRequest,
kIncomplete,
kLocalClose,
kProtocol,
kProxySocket,
MAX_ADDITIONAL_SETTINGS,
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -2287,6 +2303,7 @@ class Http2Stream extends Duplex {
this._readableState.readingMore = true;

this[kTimeout] = null;
this[kLocalClose] = false;

this[kState] = {
didRead: false,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions lib/internal/http2/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -996,6 +1004,7 @@ module.exports = {
getSessionState,
getSettings,
getStreamState,
isStreamLocalClosed,
isPayloadMeaningless,
kAuthority,
kAutoEmptyTrailers,
Expand All @@ -1005,6 +1014,7 @@ module.exports = {
kSocket,
kProtocol,
kIncomplete,
kLocalClose,
kProxySocket,
kRequest,
MAX_ADDITIONAL_SETTINGS,
Expand Down
Loading
Loading