Skip to content

Commit

Permalink
Do not block Node.js from exiting on an idle HTTP/2 connection (#716)
Browse files Browse the repository at this point in the history
  • Loading branch information
timostamm authored Jul 12, 2023
1 parent ef8b7fa commit 002633f
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions packages/connect-node/src/http2-session-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,11 @@ function ready(
// "connecting" state.
assertSessionOpen(conn);

// Do not block Node.js from exiting on an idle connection.
// Note that we ref() again for the first stream to open, and unref() again
// for the last stream to close.
conn.unref();

// the last time we were sure that the connection is alive, via a PING
// response, or via received response bytes
let lastAliveAt = Date.now();
Expand Down Expand Up @@ -580,6 +585,7 @@ function ready(
registerRequest(stream: http2.ClientHttp2Stream): void {
streamCount++;
if (streamCount == 1) {
conn.ref();
resetPingInterval(); // reset to ping with the appropriate interval for "open"
stopIdleTimeout();
}
Expand All @@ -590,6 +596,7 @@ function ready(
stream.once("close", () => {
streamCount--;
if (streamCount == 0) {
conn.unref();
resetPingInterval(); // reset to ping with the appropriate interval for "idle"
resetIdleTimeout();
}
Expand Down Expand Up @@ -776,7 +783,8 @@ function ready(

/**
* setTimeout(), but simply ignores values larger than the maximum supported
* value (signed 32-bit integer) instead of calling the callback right away.
* value (signed 32-bit integer) instead of calling the callback right away,
* and does not block Node.js from exiting.
*/
function safeSetTimeout(
callback: () => void,
Expand All @@ -785,7 +793,7 @@ function safeSetTimeout(
if (ms > 0x7fffffff) {
return;
}
return setTimeout(callback, ms);
return setTimeout(callback, ms).unref();
}

function assertSessionOpen(conn: http2.ClientHttp2Session) {
Expand Down

0 comments on commit 002633f

Please sign in to comment.