Skip to content

Commit

Permalink
fix(teardown): properly destroy a topology when initial connect fails
Browse files Browse the repository at this point in the history
Fixes NODE-1595
  • Loading branch information
daprahamian committed Aug 2, 2018
1 parent 64027e8 commit b8d2f1d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
5 changes: 3 additions & 2 deletions lib/mongo_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,9 @@ MongoClient.prototype.close = function(force, callback) {
if (typeof force === 'function') (callback = force), (force = false);

// Close the topology connection
this.topology.close(force);

if (this.topology) {
this.topology.close(force);
}
// Emit close event
this.emit('close', this);

Expand Down
20 changes: 14 additions & 6 deletions lib/operations/mongo_client_ops.js
Original file line number Diff line number Diff line change
Expand Up @@ -334,16 +334,21 @@ function createServer(mongoClient, options, callback) {
// Propagate the events to the client
const collectedEvents = collectEvents(mongoClient, servers[0]);

const server = servers[0];

// Connect to topology
servers[0].connect(options, (err, topology) => {
if (err) return callback(err);
server.connect(options, (err, topology) => {
if (err) {
server.close(true);
return callback(err);
}
// Clear out all the collected event listeners
clearAllEvents(servers[0]);
clearAllEvents(server);

// Relay all the events
relayEvents(mongoClient, servers[0]);
relayEvents(mongoClient, server);
// Add listeners
addListeners(mongoClient, servers[0]);
addListeners(mongoClient, server);
// Check if we are really speaking to a mongos
const ismaster = topology.lastIsMaster();

Expand Down Expand Up @@ -388,7 +393,10 @@ function createTopology(mongoClient, topologyType, options, callback) {

// Open the connection
topology.connect(options, (err, topology) => {
if (err) return callback(err);
if (err) {
topology.close(true);
return callback(err);
}

assignTopology(mongoClient, topology);
callback(null, topology);
Expand Down

0 comments on commit b8d2f1d

Please sign in to comment.