Skip to content

Commit b3f7272

Browse files
committed
Fixed http2 ref passing logic which was failing when using auto protocolVersion
1 parent f701688 commit b3f7272

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

lib/http2/agent.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ class Http2Agent extends EventEmitter {
1818
const name = getConnectionName(_options)
1919
let connection = this.connections[name]
2020

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

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

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

81-
connection.ref()
82-
req.once('close', () => {
83-
connection.unref()
84-
})
85-
8685
return connection
8786
}
8887
}

lib/http2/request.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,17 @@ class Http2Request extends EventEmitter {
182182
.filter(([key]) => !connectionHeaders.includes(key.toLowerCase()))
183183
)
184184

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

189+
const unreferenceFn = () => {
190+
this._client.unref();
191+
this.stream.off('close', unreferenceFn);
192+
}
193+
194+
this.stream.on('close', unreferenceFn);
195+
187196
this.registerListeners()
188197

189198
this[kHeadersFlushed] = true

0 commit comments

Comments
 (0)