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
48 changes: 41 additions & 7 deletions lib/dispatcher/client-h2.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,36 @@ function onHttp2SessionEnd () {
* @this {import('http2').ClientHttp2Session}
* @param {number} errorCode
*/
// Backport of #5410 and #5569. HTTP/2 multiplexes, so requests complete out of
// order; advancing kRunningIdx blindly retired whichever request happened to
// sit at the head instead of the one that actually finished, which both lost
// requests and left phantom running slots behind.
function completeRequest (client, request, resetPendingIdx = false) {
const queue = client[kQueue]
const runningIdx = client[kRunningIdx]

// In-order completion: clear the request and advance without splicing.
// The client's resume loop compacts cleared slots once the index grows.
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
queue[runningIdx] = null
client[kRunningIdx] = runningIdx + 1
return
}

const index = queue.indexOf(request, runningIdx)

if (index === -1 || index >= client[kPendingIdx]) {
return
}

queue.splice(index, 1)
client[kPendingIdx]--

if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
client[kPendingIdx] = client[kRunningIdx]
}
}

function onHttp2SessionGoAway (errorCode) {
// TODO(mcollina): Verify if GOAWAY implements the spec correctly:
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.8
Expand All @@ -335,7 +365,9 @@ function onHttp2SessionGoAway (errorCode) {
if (client[kRunningIdx] < client[kQueue].length) {
const request = client[kQueue][client[kRunningIdx]]
client[kQueue][client[kRunningIdx]++] = null
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
client[kPendingIdx] = client[kRunningIdx]
}

Expand Down Expand Up @@ -368,7 +400,9 @@ function onHttp2SessionClose () {
const requests = client[kQueue].splice(client[kRunningIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
}
}
}
Expand Down Expand Up @@ -483,6 +517,7 @@ function writeH2 (client, request) {

// We move the running index to the next request
client[kOnError](err)
completeRequest(client, request)
client[kResume]()
}

Expand Down Expand Up @@ -537,7 +572,7 @@ function writeH2 (client, request) {
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)

++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
})

stream.on('error', () => {
Expand Down Expand Up @@ -570,7 +605,7 @@ function writeH2 (client, request) {

request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
})
stream.once('close', () => {
session[kOpenStreams] -= 1
Expand Down Expand Up @@ -720,14 +755,13 @@ function writeH2 (client, request) {
request.onComplete({})
}

client[kQueue][client[kRunningIdx]++] = null
completeRequest(client, request)
client[kResume]()
} else {
// Stream ended without receiving a response - this is an error
// (e.g., server destroyed the stream before sending headers)
abort(new InformationalError('HTTP/2: stream half-closed (remote)'))
client[kQueue][client[kRunningIdx]++] = null
client[kPendingIdx] = client[kRunningIdx]
completeRequest(client, request, true)
client[kResume]()
}
})
Expand Down
8 changes: 6 additions & 2 deletions lib/dispatcher/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,9 @@ class Client extends DispatcherBase {
const requests = this[kQueue].splice(this[kPendingIdx])
for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(this, request, err)
if (request != null) {
util.errorRequest(this, request, err)
}
}

const callback = () => {
Expand Down Expand Up @@ -413,7 +415,9 @@ function onError (client, err) {

for (let i = 0; i < requests.length; i++) {
const request = requests[i]
util.errorRequest(client, request, err)
if (request != null) {
util.errorRequest(client, request, err)
}
}
assert(client[kSize] === 0)
}
Expand Down
73 changes: 73 additions & 0 deletions test/issue-5404.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
'use strict'

const { test } = require('node:test')
const assert = require('node:assert')
const { once } = require('node:events')
const { createServer } = require('node:http2')

const { Client } = require('..')
const { kQueue } = require('../lib/core/symbols')

// Backported from #5410.
//
// Regression test for https://github.com/nodejs/undici/issues/5404.
// HTTP/2 streams can complete out of order. Completing the second stream first
// must not clear the first request's queue slot; otherwise destroying the
// client can lose or mis-error the still-running request.
test('h2: out-of-order completion preserves running requests during destroy', async () => {
const server = createServer()
let firstStream

server.on('sessionError', () => {})
server.on('stream', (stream, headers) => {
switch (headers[':path']) {
case '/first':
firstStream = stream
break
case '/second':
stream.respond({ ':status': 200 })
stream.end('second')
break
case '/third':
stream.respond({ ':status': 200 })
stream.end('third')
break
default:
stream.respond({ ':status': 404 })
stream.end()
}
})

await once(server.listen(0), 'listening')

const client = new Client(`http://localhost:${server.address().port}`, {
allowH2: true,
useH2c: true,
maxConcurrentStreams: 2,
// h2 only dispatches concurrently up to `pipelining`, which defaults to 1.
pipelining: 2
})

try {
const first = client.request({ path: '/first', method: 'GET' })
const firstError = first.then(
() => null,
err => err
)

const second = await client.request({ path: '/second', method: 'GET' })
assert.strictEqual(await second.body.text(), 'second')

const third = await client.request({ path: '/third', method: 'GET' })
assert.strictEqual(await third.body.text(), 'third')

assert.strictEqual(firstStream.destroyed, false)
assert.deepStrictEqual(client[kQueue].map(request => request?.path), ['/first'])

await client.destroy(new Error('boom'))
assert.strictEqual((await firstError).message, 'boom')
} finally {
await client.destroy().catch(() => {})
server.close()
}
})
Loading