Skip to content

Commit

Permalink
fix: avoid heartbeat check on LoadBalanced topologies, dont treat con…
Browse files Browse the repository at this point in the history
…nection as heartbeat to avoid other cases where there is no heartbeat
  • Loading branch information
vkarpov15 committed Dec 11, 2024
1 parent 94f1bc8 commit d168bce
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
12 changes: 12 additions & 0 deletions lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
3 changes: 0 additions & 3 deletions lib/drivers/node-mongodb-native/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down

0 comments on commit d168bce

Please sign in to comment.