Skip to content

Commit cf53299

Browse files
mbroadstdaprahamian
authored andcommitted
fix(replset): introduce a fixed-time server selection loop
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.
1 parent 097d3b9 commit cf53299

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

lib/core/topologies/replset.js

+29-11
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const isRetryableWritesSupported = require('./shared').isRetryableWritesSupporte
1919
const relayEvents = require('../utils').relayEvents;
2020
const isRetryableError = require('../error').isRetryableError;
2121
const BSON = retrieveBSON();
22+
const calculateDurationInMs = require('../utils').calculateDurationInMs;
2223

2324
//
2425
// States
@@ -1110,19 +1111,36 @@ ReplSet.prototype.selectServer = function(selector, options, callback) {
11101111
readPreference = options.readPreference || ReadPreference.primary;
11111112
}
11121113

1113-
const server = this.s.replicaSetState.pickServer(readPreference);
1114-
if (server == null) {
1115-
callback(new MongoError('server selection failed'));
1116-
return;
1117-
}
1114+
let lastError;
1115+
const start = process.hrtime();
1116+
const _selectServer = () => {
1117+
if (calculateDurationInMs(start) >= 10000) {
1118+
if (lastError != null) {
1119+
callback(lastError, null);
1120+
} else {
1121+
callback(new MongoError('Server selection timed out'));
1122+
}
11181123

1119-
if (!(server instanceof Server)) {
1120-
callback(server, null);
1121-
return;
1122-
}
1124+
return;
1125+
}
1126+
1127+
const server = this.s.replicaSetState.pickServer(readPreference);
1128+
if (server == null) {
1129+
setTimeout(_selectServer, 1000);
1130+
return;
1131+
}
1132+
1133+
if (!(server instanceof Server)) {
1134+
lastError = server;
1135+
setTimeout(_selectServer, 1000);
1136+
return;
1137+
}
1138+
1139+
if (this.s.debug) this.emit('pickedServer', options.readPreference, server);
1140+
callback(null, server);
1141+
};
11231142

1124-
if (this.s.debug) this.emit('pickedServer', options.readPreference, server);
1125-
callback(null, server);
1143+
_selectServer();
11261144
};
11271145

11281146
/**

0 commit comments

Comments
 (0)