From d168bce602fc5db00bea4674e2313e37dd605611 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 11 Dec 2024 12:34:39 -0500 Subject: [PATCH] fix: avoid heartbeat check on LoadBalanced topologies, dont treat connection as heartbeat to avoid other cases where there is no heartbeat --- lib/connection.js | 12 ++++++++++++ lib/drivers/node-mongodb-native/connection.js | 3 --- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/connection.js b/lib/connection.js index 2e0caf5c59..eea265260d 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -106,6 +106,18 @@ Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype); Object.defineProperty(Connection.prototype, 'readyState', { get: function() { + // If connection thinks it is connected, but we haven't received a heartbeat in 2 heartbeat intervals, + // that likely means the connection is stale (potentially due to frozen AWS Lambda container) + if ( + this._readyState === STATES.connected && + this._lastHeartbeatAt != null && + // LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats, + // so we can't use this check in that case. + this.client?.topology?.s?.description?.type !== 'LoadBalanced' && + typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === 'number' && + Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) { + return STATES.disconnected; + } return this._readyState; }, set: function(val) { diff --git a/lib/drivers/node-mongodb-native/connection.js b/lib/drivers/node-mongodb-native/connection.js index 641703e4b1..a17fc64131 100644 --- a/lib/drivers/node-mongodb-native/connection.js +++ b/lib/drivers/node-mongodb-native/connection.js @@ -426,9 +426,6 @@ function _setClient(conn, client, options, dbName) { } conn.onOpen(); - if (client.topology?.s?.state === 'connected') { - conn._lastHeartbeatAt = Date.now(); - } for (const i in conn.collections) { if (utils.object.hasOwnProperty(conn.collections, i)) {