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
36 changes: 21 additions & 15 deletions lib/dispatcher/client-h2.js
Original file line number Diff line number Diff line change
Expand Up @@ -1117,7 +1117,7 @@ function writeH2 (client, request) {
const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout]
const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout]
const session = client[kHTTP2Session]
const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request
const { method, path, host, upgrade, expectContinue, protocol, headers: reqHeaders } = request

if (upgrade != null && upgrade !== 'websocket') {
util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`))
Expand All @@ -1129,6 +1129,13 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_AUTHORITY] = host || client[kHostAuthority]
headers[HTTP2_HEADER_METHOD] = method

// Owned by this request's stream. Aborting it makes Node destroy the stream
// with an AbortError, which submits RST_STREAM(CANCEL) before the stream is
// torn down, even while the request body is still queued behind flow control.
// The user's signal is not passed to session.request(): it is already wired
// to the abort handler below via request.onRequestStart().
const streamAbort = new AbortController()

// Single pre-shaped state object shared by all stream event handlers.
// All fields are declared up-front so the object keeps a stable hidden
// class for the whole request lifetime.
Expand Down Expand Up @@ -1165,18 +1172,17 @@ function writeH2 (client, request) {
if (state.stream != null) {
clearRequestStream(request)

// On Abort, we close the stream to send RST_STREAM frame.
// On Abort, cancel the stream through its signal so Node sends
// RST_STREAM(CANCEL) and destroys it in one step. stream.close() defers
// the RST_STREAM until the writable side finishes, which never happens
// while the peer withholds flow-control window for a queued body; a
// destroy after close() then drops the stream from Node while nghttp2
// keeps its data provider, and the session loops on empty DATA frames
// until the process runs out of memory (#6187).
const stream = state.stream
stream.close()

// close() alone leaves cleanup waiting on the 'close' event; on a busy,
// long-lived multiplexed session that event can fail to fire, leaving the
// native Http2Stream (and the whole request graph it pins) alive for the
// session's life. Destroy the stream synchronously to release the handle
// deterministically. Deferring the destroy (e.g. via setImmediate) leaks
// the same way when the event loop is stalled and the callback never runs
// under abort churn (#5558); close() has already queued the RST_STREAM
// frame on the native session, so a synchronous destroy still sends it.
streamAbort.abort()

// Destroy synchronously in case the signal did not (#5558).
if (!stream.destroyed) {
util.destroy(stream)
}
Expand Down Expand Up @@ -1233,7 +1239,7 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_SCHEME] = protocol === 'http:' ? 'http' : 'https'
}

stream = openStream(client, request, session, abort, headers, { endStream: false, signal })
stream = openStream(client, request, session, abort, headers, { endStream: false, signal: streamAbort.signal })
if (stream == null) {
unrefH2Session(session)
return false
Expand All @@ -1247,7 +1253,7 @@ function writeH2 (client, request) {
// will create a new stream. We trigger a request to create the stream and wait until
// `ready` event is triggered
// We disabled endStream to allow the user to write to the stream
stream = openStream(client, request, session, abort, headers, { endStream: false, signal })
stream = openStream(client, request, session, abort, headers, { endStream: false, signal: streamAbort.signal })
if (stream == null) {
unrefH2Session(session)
return false
Expand Down Expand Up @@ -1349,7 +1355,7 @@ function writeH2 (client, request) {
headers[HTTP2_HEADER_EXPECT] = '100-continue'
}

stream = openStream(client, request, session, abort, headers, { endStream: shouldEndStream, signal })
stream = openStream(client, request, session, abort, headers, { endStream: shouldEndStream, signal: streamAbort.signal })
if (stream == null) {
return false
}
Expand Down
166 changes: 165 additions & 1 deletion test/http2-abort.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

const { tspl } = require('@matteo.collina/tspl')
const { test, after } = require('node:test')
const { createSecureServer } = require('node:http2')
const { createSecureServer, constants } = require('node:http2')
const { once } = require('node:events')
const { Readable } = require('node:stream')

const pem = require('@metcoder95/https-pem')

Expand Down Expand Up @@ -126,6 +127,169 @@ test('#2364 - Concurrent aborts', async t => {
await client.close()
})

test('#6187 - abort while the request body is queued behind flow control sends RST_STREAM(CANCEL)', async t => {
t = tspl(t, { plan: 4 })

const server = createSecureServer(await pem.generate({ opts: { keySize: 2048 } }))
server.on('error', () => {})
server.on('session', session => {
session.on('error', () => {})
session.socket?.on('error', () => {})
})
server.on('secureConnection', socket => socket.on('error', () => {}))

let notifyStream
const streamReceived = new Promise(resolve => { notifyStream = resolve })
let notifyClose
const streamClosed = new Promise(resolve => { notifyClose = resolve })
let rstCode

server.on('stream', (stream, headers) => {
stream.on('error', () => {})

if (headers[':path'] === '/ok') {
stream.respond({
'content-type': 'text/plain; charset=utf-8',
':status': 200
})
stream.end('hello h2!')
return
}

// Never read the body: the upload stalls at the initial flow-control
// window with most of the 2 MiB body still queued on the client.
stream.on('close', () => {
rstCode = stream.rstCode
notifyClose()
})
notifyStream()
})

after(() => server.close())
await once(server.listen(0), 'listening')

const client = new Client(`https://localhost:${server.address().port}`, {
connect: {
rejectUnauthorized: false
},
allowH2: true
})
after(() => client.close().catch(() => {}))

const ac = new AbortController()
const requestPromise = client.request({
path: '/',
method: 'POST',
body: Buffer.alloc(2 * 1024 * 1024),
signal: ac.signal
})

// Abort only once the server has the stream, so the body is already
// queued behind flow control when the abort lands.
await streamReceived
ac.abort()

const err = await requestPromise.then(() => null, err => err)
t.ok(err, 'the aborted request rejects')

// The fix submits RST_STREAM synchronously with the abort, so 2 s is a
// generous bound. Without it, close() defers the reset until the queued
// body flushes, and the server only sees the stream go away seconds later
// (or, once it grants window, not at all: the session loops instead).
let timer
const closed = await Promise.race([
streamClosed.then(() => true),
new Promise(resolve => { timer = setTimeout(() => resolve(false), 2000) })
]).finally(() => clearTimeout(timer))
t.strictEqual(closed, true, 'the server sees the stream close promptly after the abort')
t.strictEqual(rstCode, constants.NGHTTP2_CANCEL, 'the server receives RST_STREAM(CANCEL)')

// The orphaned stream must not wedge the session: a follow-up request on
// the same client still succeeds.
const res = await client.request({ path: '/ok', method: 'GET' })
t.strictEqual(res.statusCode, 200)
await res.body.text()

await t.completed
await client.close()
})

test('#6187 - abort while a streaming body is still being piped sends RST_STREAM(CANCEL)', async t => {
t = tspl(t, { plan: 3 })

const server = createSecureServer(await pem.generate({ opts: { keySize: 2048 } }))
server.on('error', () => {})
server.on('session', session => {
session.on('error', () => {})
session.socket?.on('error', () => {})
})
server.on('secureConnection', socket => socket.on('error', () => {}))

let notifyStream
const streamReceived = new Promise(resolve => { notifyStream = resolve })
let notifyClose
const streamClosed = new Promise(resolve => { notifyClose = resolve })
let rstCode

server.on('stream', (stream) => {
stream.on('error', () => {})
// Never read: the piped body stalls behind flow control mid-upload.
stream.on('close', () => {
rstCode = stream.rstCode
notifyClose()
})
notifyStream()
})

after(() => server.close())
await once(server.listen(0), 'listening')

const client = new Client(`https://localhost:${server.address().port}`, {
connect: {
rejectUnauthorized: false
},
allowH2: true
})
after(() => client.close().catch(() => {}))

// 2 MiB in 64 KiB chunks, then the source stalls without ending, so the
// request is still uploading when the abort lands.
let pushed = 0
const body = new Readable({
read () {
if (pushed < 32) {
this.push(Buffer.alloc(64 * 1024))
pushed++
}
}
})

const ac = new AbortController()
const requestPromise = client.request({
path: '/',
method: 'POST',
body,
signal: ac.signal
})

await streamReceived
ac.abort()

const err = await requestPromise.then(() => null, err => err)
t.ok(err, 'the aborted request rejects')

let timer
const closed = await Promise.race([
streamClosed.then(() => true),
new Promise(resolve => { timer = setTimeout(() => resolve(false), 2000) })
]).finally(() => clearTimeout(timer))
t.strictEqual(closed, true, 'the server sees the stream close promptly after the abort')
t.strictEqual(rstCode, constants.NGHTTP2_CANCEL, 'the server receives RST_STREAM(CANCEL)')

await t.completed
await client.close()
})

test('#2364 - Concurrent aborts (2nd variant)', async t => {
t = tspl(t, { plan: 10 })

Expand Down