Skip to content

Commit

Permalink
fix(connection): ensure repeated close events from useUnifiedTopolo…
Browse files Browse the repository at this point in the history
…gy don't disconnect Mongoose from replica set

Fix #8224
Re: NODE-2251
  • Loading branch information
vkarpov15 committed Oct 16, 2019
1 parent be5e1fa commit 27cefad
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions lib/connection.js
Expand Up @@ -639,18 +639,28 @@ Connection.prototype.openUri = function(uri, options, callback) {
_this.db = db;

// `useUnifiedTopology` events
if (options.useUnifiedTopology &&
get(db, 's.topology.s.description.type') === 'Single') {
const server = Array.from(db.s.topology.s.servers.values())[0];
server.s.pool.on('reconnect', () => {
_handleReconnect();
});
server.s.pool.on('reconnectFailed', () => {
_this.emit('reconnectFailed');
});
server.s.pool.on('timeout', () => {
_this.emit('timeout');
});
const type = get(db, 's.topology.s.description.type', '');
if (options.useUnifiedTopology) {
if (type === 'Single') {
const server = Array.from(db.s.topology.s.servers.values())[0];
server.s.pool.on('reconnect', () => {
_handleReconnect();
});
server.s.pool.on('reconnectFailed', () => {
_this.emit('reconnectFailed');
});
server.s.pool.on('timeout', () => {
_this.emit('timeout');
});
} else if (type.startsWith('ReplicaSet')) {
db.on('close', function() {
const type = get(db, 's.topology.s.description.type', '');
if (type !== 'ReplicaSetWithPrimary') {
// Implicitly emits 'disconnected'
_this.readyState = STATES.disconnected;
}
});
}
}

// Backwards compat for mongoose 4.x
Expand All @@ -674,10 +684,12 @@ Connection.prototype.openUri = function(uri, options, callback) {
_this.emit('attemptReconnect');
});
}
db.on('close', function() {
// Implicitly emits 'disconnected'
_this.readyState = STATES.disconnected;
});
if (!options.useUnifiedTopology || !type.startsWith('ReplicaSet')) {
db.on('close', function() {
// Implicitly emits 'disconnected'
_this.readyState = STATES.disconnected;
});
}
client.on('left', function() {
if (_this.readyState === STATES.connected &&
get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') {
Expand Down

0 comments on commit 27cefad

Please sign in to comment.