Skip to content

Commit

Permalink
fix(replset): introduce a fixed-time server selection loop
Browse files Browse the repository at this point in the history
This is required because we are moving server selection to live
outside of topologies. The legacy topologies would use the
disconnectHandler to implement a form of server selection.
  • Loading branch information
mbroadst authored and daprahamian committed Aug 13, 2019
1 parent 097d3b9 commit cf53299
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions lib/core/topologies/replset.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const isRetryableWritesSupported = require('./shared').isRetryableWritesSupporte
const relayEvents = require('../utils').relayEvents;
const isRetryableError = require('../error').isRetryableError;
const BSON = retrieveBSON();
const calculateDurationInMs = require('../utils').calculateDurationInMs;

//
// States
Expand Down Expand Up @@ -1110,19 +1111,36 @@ ReplSet.prototype.selectServer = function(selector, options, callback) {
readPreference = options.readPreference || ReadPreference.primary;
}

const server = this.s.replicaSetState.pickServer(readPreference);
if (server == null) {
callback(new MongoError('server selection failed'));
return;
}
let lastError;
const start = process.hrtime();
const _selectServer = () => {
if (calculateDurationInMs(start) >= 10000) {
if (lastError != null) {
callback(lastError, null);
} else {
callback(new MongoError('Server selection timed out'));
}

if (!(server instanceof Server)) {
callback(server, null);
return;
}
return;
}

const server = this.s.replicaSetState.pickServer(readPreference);
if (server == null) {
setTimeout(_selectServer, 1000);
return;
}

if (!(server instanceof Server)) {
lastError = server;
setTimeout(_selectServer, 1000);
return;
}

if (this.s.debug) this.emit('pickedServer', options.readPreference, server);
callback(null, server);
};

if (this.s.debug) this.emit('pickedServer', options.readPreference, server);
callback(null, server);
_selectServer();
};

/**
Expand Down

0 comments on commit cf53299

Please sign in to comment.