Skip to content

Commit

Permalink
Fixed http2 ref passing logic which was failing when using auto proto…
Browse files Browse the repository at this point in the history
…colVersion
  • Loading branch information
parthverma1 committed Aug 19, 2024
1 parent f701688 commit b3f7272
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
11 changes: 5 additions & 6 deletions lib/http2/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class Http2Agent extends EventEmitter {
const name = getConnectionName(_options)
let connection = this.connections[name]

if (!connection || connection.destroyed || connection.closed) {
// Force create a new connection if the connection is destroyed or closed or a new socket object is supplied
if (!connection || connection.destroyed || connection.closed || socket) {
const connectionOptions = {
..._options,
port: _options.port || 443,
Expand All @@ -33,6 +34,9 @@ class Http2Agent extends EventEmitter {
}

connection = http2.connect(uri, connectionOptions)
// Connection is created in an unreferenced state and is referenced when a stream is created
// This is to prevent the connection from keeping the event loop alive
connection.unref()

// Counting semaphore, but since node is single-threaded, this is just a counter
// Multiple streams can be active on a connection
Expand Down Expand Up @@ -78,11 +82,6 @@ class Http2Agent extends EventEmitter {
this.connections[name] = connection
}

connection.ref()
req.once('close', () => {
connection.unref()
})

return connection
}
}
Expand Down
9 changes: 9 additions & 0 deletions lib/http2/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,17 @@ class Http2Request extends EventEmitter {
.filter(([key]) => !connectionHeaders.includes(key.toLowerCase()))
)

// The client was created in an unreferenced state and is referenced when a stream is created
this._client.ref();
this.stream = this._client.request(this.requestHeaders, {endStream})

const unreferenceFn = () => {
this._client.unref();
this.stream.off('close', unreferenceFn);
}

this.stream.on('close', unreferenceFn);

this.registerListeners()

this[kHeadersFlushed] = true
Expand Down

0 comments on commit b3f7272

Please sign in to comment.