connect.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. 'use strict';
  2. const deprecate = require('util').deprecate;
  3. const Logger = require('../core').Logger;
  4. const MongoCredentials = require('../core').MongoCredentials;
  5. const MongoError = require('../core').MongoError;
  6. const Mongos = require('../topologies/mongos');
  7. const NativeTopology = require('../topologies/native_topology');
  8. const parse = require('../core').parseConnectionString;
  9. const ReadConcern = require('../read_concern');
  10. const ReadPreference = require('../core').ReadPreference;
  11. const ReplSet = require('../topologies/replset');
  12. const Server = require('../topologies/server');
  13. const ServerSessionPool = require('../core').Sessions.ServerSessionPool;
  14. const emitDeprecationWarning = require('../utils').emitDeprecationWarning;
  15. const fs = require('fs');
  16. const BSON = require('../core/connection/utils').retrieveBSON();
  17. const CMAP_EVENT_NAMES = require('../cmap/events').CMAP_EVENT_NAMES;
  18. let client;
  19. function loadClient() {
  20. if (!client) {
  21. client = require('../mongo_client');
  22. }
  23. return client;
  24. }
  25. const legacyParse = deprecate(
  26. require('../url_parser'),
  27. 'current URL string parser is deprecated, and will be removed in a future version. ' +
  28. 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.'
  29. );
  30. const AUTH_MECHANISM_INTERNAL_MAP = {
  31. DEFAULT: 'default',
  32. 'MONGODB-CR': 'mongocr',
  33. PLAIN: 'plain',
  34. 'MONGODB-X509': 'x509',
  35. 'SCRAM-SHA-1': 'scram-sha-1',
  36. 'SCRAM-SHA-256': 'scram-sha-256'
  37. };
  38. const monitoringEvents = [
  39. 'timeout',
  40. 'close',
  41. 'serverOpening',
  42. 'serverDescriptionChanged',
  43. 'serverHeartbeatStarted',
  44. 'serverHeartbeatSucceeded',
  45. 'serverHeartbeatFailed',
  46. 'serverClosed',
  47. 'topologyOpening',
  48. 'topologyClosed',
  49. 'topologyDescriptionChanged',
  50. 'commandStarted',
  51. 'commandSucceeded',
  52. 'commandFailed',
  53. 'joined',
  54. 'left',
  55. 'ping',
  56. 'ha',
  57. 'all',
  58. 'fullsetup',
  59. 'open'
  60. ];
  61. const VALID_AUTH_MECHANISMS = new Set([
  62. 'DEFAULT',
  63. 'MONGODB-CR',
  64. 'PLAIN',
  65. 'MONGODB-X509',
  66. 'SCRAM-SHA-1',
  67. 'SCRAM-SHA-256',
  68. 'GSSAPI'
  69. ]);
  70. const validOptionNames = [
  71. 'poolSize',
  72. 'ssl',
  73. 'sslValidate',
  74. 'sslCA',
  75. 'sslCert',
  76. 'sslKey',
  77. 'sslPass',
  78. 'sslCRL',
  79. 'autoReconnect',
  80. 'noDelay',
  81. 'keepAlive',
  82. 'keepAliveInitialDelay',
  83. 'connectTimeoutMS',
  84. 'family',
  85. 'socketTimeoutMS',
  86. 'reconnectTries',
  87. 'reconnectInterval',
  88. 'ha',
  89. 'haInterval',
  90. 'replicaSet',
  91. 'secondaryAcceptableLatencyMS',
  92. 'acceptableLatencyMS',
  93. 'connectWithNoPrimary',
  94. 'authSource',
  95. 'w',
  96. 'wtimeout',
  97. 'j',
  98. 'forceServerObjectId',
  99. 'serializeFunctions',
  100. 'ignoreUndefined',
  101. 'raw',
  102. 'bufferMaxEntries',
  103. 'readPreference',
  104. 'pkFactory',
  105. 'promiseLibrary',
  106. 'readConcern',
  107. 'maxStalenessSeconds',
  108. 'loggerLevel',
  109. 'logger',
  110. 'promoteValues',
  111. 'promoteBuffers',
  112. 'promoteLongs',
  113. 'domainsEnabled',
  114. 'checkServerIdentity',
  115. 'validateOptions',
  116. 'appname',
  117. 'auth',
  118. 'user',
  119. 'password',
  120. 'authMechanism',
  121. 'compression',
  122. 'fsync',
  123. 'readPreferenceTags',
  124. 'numberOfRetries',
  125. 'auto_reconnect',
  126. 'minSize',
  127. 'monitorCommands',
  128. 'retryWrites',
  129. 'retryReads',
  130. 'useNewUrlParser',
  131. 'useUnifiedTopology',
  132. 'serverSelectionTimeoutMS',
  133. 'useRecoveryToken',
  134. 'autoEncryption',
  135. 'driverInfo',
  136. 'tls',
  137. 'tlsInsecure',
  138. 'tlsinsecure',
  139. 'tlsAllowInvalidCertificates',
  140. 'tlsAllowInvalidHostnames',
  141. 'tlsCAFile',
  142. 'tlsCertificateFile',
  143. 'tlsCertificateKeyFile',
  144. 'tlsCertificateKeyFilePassword',
  145. 'minHeartbeatFrequencyMS',
  146. 'heartbeatFrequencyMS',
  147. 'waitQueueTimeoutMS'
  148. ];
  149. const ignoreOptionNames = ['native_parser'];
  150. const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db'];
  151. // Validate options object
  152. function validOptions(options) {
  153. const _validOptions = validOptionNames.concat(legacyOptionNames);
  154. for (const name in options) {
  155. if (ignoreOptionNames.indexOf(name) !== -1) {
  156. continue;
  157. }
  158. if (_validOptions.indexOf(name) === -1) {
  159. if (options.validateOptions) {
  160. return new MongoError(`option ${name} is not supported`);
  161. } else {
  162. console.warn(`the options [${name}] is not supported`);
  163. }
  164. }
  165. if (legacyOptionNames.indexOf(name) !== -1) {
  166. console.warn(
  167. `the server/replset/mongos/db options are deprecated, ` +
  168. `all their options are supported at the top level of the options object [${validOptionNames}]`
  169. );
  170. }
  171. }
  172. }
  173. const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => {
  174. obj[name.toLowerCase()] = name;
  175. return obj;
  176. }, {});
  177. function addListeners(mongoClient, topology) {
  178. topology.on('authenticated', createListener(mongoClient, 'authenticated'));
  179. topology.on('error', createListener(mongoClient, 'error'));
  180. topology.on('timeout', createListener(mongoClient, 'timeout'));
  181. topology.on('close', createListener(mongoClient, 'close'));
  182. topology.on('parseError', createListener(mongoClient, 'parseError'));
  183. topology.once('open', createListener(mongoClient, 'open'));
  184. topology.once('fullsetup', createListener(mongoClient, 'fullsetup'));
  185. topology.once('all', createListener(mongoClient, 'all'));
  186. topology.on('reconnect', createListener(mongoClient, 'reconnect'));
  187. }
  188. function assignTopology(client, topology) {
  189. client.topology = topology;
  190. if (!(topology instanceof NativeTopology)) {
  191. topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology);
  192. }
  193. }
  194. // Clear out all events
  195. function clearAllEvents(topology) {
  196. monitoringEvents.forEach(event => topology.removeAllListeners(event));
  197. }
  198. // Collect all events in order from SDAM
  199. function collectEvents(mongoClient, topology) {
  200. let MongoClient = loadClient();
  201. const collectedEvents = [];
  202. if (mongoClient instanceof MongoClient) {
  203. monitoringEvents.forEach(event => {
  204. topology.on(event, (object1, object2) => {
  205. if (event === 'open') {
  206. collectedEvents.push({ event: event, object1: mongoClient });
  207. } else {
  208. collectedEvents.push({ event: event, object1: object1, object2: object2 });
  209. }
  210. });
  211. });
  212. }
  213. return collectedEvents;
  214. }
  215. function resolveTLSOptions(options) {
  216. if (options.tls == null) {
  217. return;
  218. }
  219. ['sslCA', 'sslKey', 'sslCert'].forEach(optionName => {
  220. if (options[optionName]) {
  221. options[optionName] = fs.readFileSync(options[optionName]);
  222. }
  223. });
  224. }
  225. const emitDeprecationForNonUnifiedTopology = deprecate(() => {},
  226. 'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.');
  227. function connect(mongoClient, url, options, callback) {
  228. options = Object.assign({}, options);
  229. // If callback is null throw an exception
  230. if (callback == null) {
  231. throw new Error('no callback function provided');
  232. }
  233. let didRequestAuthentication = false;
  234. const logger = Logger('MongoClient', options);
  235. // Did we pass in a Server/ReplSet/Mongos
  236. if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) {
  237. return connectWithUrl(mongoClient, url, options, connectCallback);
  238. }
  239. const useNewUrlParser = options.useNewUrlParser !== false;
  240. const parseFn = useNewUrlParser ? parse : legacyParse;
  241. const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions;
  242. parseFn(url, options, (err, _object) => {
  243. // Do not attempt to connect if parsing error
  244. if (err) return callback(err);
  245. // Flatten
  246. const object = transform(_object);
  247. // Parse the string
  248. const _finalOptions = createUnifiedOptions(object, options);
  249. // Check if we have connection and socket timeout set
  250. if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000;
  251. if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000;
  252. if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true;
  253. if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true;
  254. if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary';
  255. if (_finalOptions.db_options && _finalOptions.db_options.auth) {
  256. delete _finalOptions.db_options.auth;
  257. }
  258. // resolve tls options if needed
  259. resolveTLSOptions(_finalOptions);
  260. // Store the merged options object
  261. mongoClient.s.options = _finalOptions;
  262. // Failure modes
  263. if (object.servers.length === 0) {
  264. return callback(new Error('connection string must contain at least one seed host'));
  265. }
  266. if (_finalOptions.auth && !_finalOptions.credentials) {
  267. try {
  268. didRequestAuthentication = true;
  269. _finalOptions.credentials = generateCredentials(
  270. mongoClient,
  271. _finalOptions.auth.user,
  272. _finalOptions.auth.password,
  273. _finalOptions
  274. );
  275. } catch (err) {
  276. return callback(err);
  277. }
  278. }
  279. if (_finalOptions.useUnifiedTopology) {
  280. return createTopology(mongoClient, 'unified', _finalOptions, connectCallback);
  281. }
  282. emitDeprecationForNonUnifiedTopology();
  283. // Do we have a replicaset then skip discovery and go straight to connectivity
  284. if (_finalOptions.replicaSet || _finalOptions.rs_name) {
  285. return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback);
  286. } else if (object.servers.length > 1) {
  287. return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback);
  288. } else {
  289. return createServer(mongoClient, _finalOptions, connectCallback);
  290. }
  291. });
  292. function connectCallback(err, topology) {
  293. const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`;
  294. if (err && err.message === 'no mongos proxies found in seed list') {
  295. if (logger.isWarn()) {
  296. logger.warn(warningMessage);
  297. }
  298. // Return a more specific error message for MongoClient.connect
  299. return callback(new MongoError(warningMessage));
  300. }
  301. if (didRequestAuthentication) {
  302. mongoClient.emit('authenticated', null, true);
  303. }
  304. // Return the error and db instance
  305. callback(err, topology);
  306. }
  307. }
  308. function connectWithUrl(mongoClient, url, options, connectCallback) {
  309. // Set the topology
  310. assignTopology(mongoClient, url);
  311. // Add listeners
  312. addListeners(mongoClient, url);
  313. // Propagate the events to the client
  314. relayEvents(mongoClient, url);
  315. let finalOptions = Object.assign({}, options);
  316. // If we have a readPreference passed in by the db options, convert it from a string
  317. if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
  318. finalOptions.readPreference = new ReadPreference(
  319. options.readPreference || options.read_preference
  320. );
  321. }
  322. const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism;
  323. if (isDoingAuth && !finalOptions.credentials) {
  324. try {
  325. finalOptions.credentials = generateCredentials(
  326. mongoClient,
  327. finalOptions.user,
  328. finalOptions.password,
  329. finalOptions
  330. );
  331. } catch (err) {
  332. return connectCallback(err, url);
  333. }
  334. }
  335. return url.connect(finalOptions, connectCallback);
  336. }
  337. function createListener(mongoClient, event) {
  338. const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']);
  339. return (v1, v2) => {
  340. if (eventSet.has(event)) {
  341. return mongoClient.emit(event, mongoClient);
  342. }
  343. mongoClient.emit(event, v1, v2);
  344. };
  345. }
  346. function createServer(mongoClient, options, callback) {
  347. // Pass in the promise library
  348. options.promiseLibrary = mongoClient.s.promiseLibrary;
  349. // Set default options
  350. const servers = translateOptions(options);
  351. const server = servers[0];
  352. // Propagate the events to the client
  353. const collectedEvents = collectEvents(mongoClient, server);
  354. // Connect to topology
  355. server.connect(options, (err, topology) => {
  356. if (err) {
  357. server.close(true);
  358. return callback(err);
  359. }
  360. // Clear out all the collected event listeners
  361. clearAllEvents(server);
  362. // Relay all the events
  363. relayEvents(mongoClient, server);
  364. // Add listeners
  365. addListeners(mongoClient, server);
  366. // Check if we are really speaking to a mongos
  367. const ismaster = topology.lastIsMaster();
  368. // Set the topology
  369. assignTopology(mongoClient, topology);
  370. // Do we actually have a mongos
  371. if (ismaster && ismaster.msg === 'isdbgrid') {
  372. // Destroy the current connection
  373. topology.close();
  374. // Create mongos connection instead
  375. return createTopology(mongoClient, 'mongos', options, callback);
  376. }
  377. // Fire all the events
  378. replayEvents(mongoClient, collectedEvents);
  379. // Otherwise callback
  380. callback(err, topology);
  381. });
  382. }
  383. const DEPRECATED_UNIFIED_EVENTS = new Set([
  384. 'reconnect',
  385. 'reconnectFailed',
  386. 'attemptReconnect',
  387. 'joined',
  388. 'left',
  389. 'ping',
  390. 'ha',
  391. 'all',
  392. 'fullsetup',
  393. 'open'
  394. ]);
  395. function registerDeprecatedEventNotifiers(client) {
  396. client.on('newListener', eventName => {
  397. if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) {
  398. emitDeprecationWarning(
  399. `The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`,
  400. 'DeprecationWarning'
  401. );
  402. }
  403. });
  404. }
  405. function createTopology(mongoClient, topologyType, options, callback) {
  406. // Pass in the promise library
  407. options.promiseLibrary = mongoClient.s.promiseLibrary;
  408. const translationOptions = {};
  409. if (topologyType === 'unified') translationOptions.createServers = false;
  410. // Set default options
  411. const servers = translateOptions(options, translationOptions);
  412. // determine CSFLE support
  413. if (options.autoEncryption != null) {
  414. let AutoEncrypter;
  415. try {
  416. require.resolve('mongodb-client-encryption');
  417. } catch (err) {
  418. callback(
  419. new MongoError(
  420. 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project'
  421. )
  422. );
  423. return;
  424. }
  425. try {
  426. let mongodbClientEncryption = require('mongodb-client-encryption');
  427. if (typeof mongodbClientEncryption.extension !== 'function') {
  428. callback(
  429. new MongoError(
  430. 'loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`'
  431. )
  432. );
  433. }
  434. AutoEncrypter = mongodbClientEncryption.extension(require('../../index')).AutoEncrypter;
  435. } catch (err) {
  436. callback(err);
  437. return;
  438. }
  439. const mongoCryptOptions = Object.assign(
  440. {
  441. bson:
  442. options.bson ||
  443. new BSON([
  444. BSON.Binary,
  445. BSON.Code,
  446. BSON.DBRef,
  447. BSON.Decimal128,
  448. BSON.Double,
  449. BSON.Int32,
  450. BSON.Long,
  451. BSON.Map,
  452. BSON.MaxKey,
  453. BSON.MinKey,
  454. BSON.ObjectId,
  455. BSON.BSONRegExp,
  456. BSON.Symbol,
  457. BSON.Timestamp
  458. ])
  459. },
  460. options.autoEncryption
  461. );
  462. options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions);
  463. }
  464. // Create the topology
  465. let topology;
  466. if (topologyType === 'mongos') {
  467. topology = new Mongos(servers, options);
  468. } else if (topologyType === 'replicaset') {
  469. topology = new ReplSet(servers, options);
  470. } else if (topologyType === 'unified') {
  471. topology = new NativeTopology(options.servers, options);
  472. registerDeprecatedEventNotifiers(mongoClient);
  473. }
  474. // Add listeners
  475. addListeners(mongoClient, topology);
  476. // Propagate the events to the client
  477. relayEvents(mongoClient, topology);
  478. // Open the connection
  479. assignTopology(mongoClient, topology);
  480. // initialize CSFLE if requested
  481. if (options.autoEncrypter) {
  482. options.autoEncrypter.init(err => {
  483. if (err) {
  484. callback(err);
  485. return;
  486. }
  487. topology.connect(options, err => {
  488. if (err) {
  489. topology.close(true);
  490. callback(err);
  491. return;
  492. }
  493. callback(undefined, topology);
  494. });
  495. });
  496. return;
  497. }
  498. // otherwise connect normally
  499. topology.connect(options, err => {
  500. if (err) {
  501. topology.close(true);
  502. return callback(err);
  503. }
  504. callback(undefined, topology);
  505. return;
  506. });
  507. }
  508. function createUnifiedOptions(finalOptions, options) {
  509. const childOptions = [
  510. 'mongos',
  511. 'server',
  512. 'db',
  513. 'replset',
  514. 'db_options',
  515. 'server_options',
  516. 'rs_options',
  517. 'mongos_options'
  518. ];
  519. const noMerge = ['readconcern', 'compression', 'autoencryption'];
  520. for (const name in options) {
  521. if (noMerge.indexOf(name.toLowerCase()) !== -1) {
  522. finalOptions[name] = options[name];
  523. } else if (childOptions.indexOf(name.toLowerCase()) !== -1) {
  524. finalOptions = mergeOptions(finalOptions, options[name], false);
  525. } else {
  526. if (
  527. options[name] &&
  528. typeof options[name] === 'object' &&
  529. !Buffer.isBuffer(options[name]) &&
  530. !Array.isArray(options[name])
  531. ) {
  532. finalOptions = mergeOptions(finalOptions, options[name], true);
  533. } else {
  534. finalOptions[name] = options[name];
  535. }
  536. }
  537. }
  538. return finalOptions;
  539. }
  540. function generateCredentials(client, username, password, options) {
  541. options = Object.assign({}, options);
  542. // the default db to authenticate against is 'self'
  543. // if authententicate is called from a retry context, it may be another one, like admin
  544. const source = options.authSource || options.authdb || options.dbName;
  545. // authMechanism
  546. const authMechanismRaw = options.authMechanism || 'DEFAULT';
  547. const authMechanism = authMechanismRaw.toUpperCase();
  548. if (!VALID_AUTH_MECHANISMS.has(authMechanism)) {
  549. throw MongoError.create({
  550. message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`,
  551. driver: true
  552. });
  553. }
  554. if (authMechanism === 'GSSAPI') {
  555. return new MongoCredentials({
  556. mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi',
  557. mechanismProperties: options,
  558. source,
  559. username,
  560. password
  561. });
  562. }
  563. return new MongoCredentials({
  564. mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism],
  565. source,
  566. username,
  567. password
  568. });
  569. }
  570. function legacyTransformUrlOptions(object) {
  571. return mergeOptions(createUnifiedOptions({}, object), object, false);
  572. }
  573. function mergeOptions(target, source, flatten) {
  574. for (const name in source) {
  575. if (source[name] && typeof source[name] === 'object' && flatten) {
  576. target = mergeOptions(target, source[name], flatten);
  577. } else {
  578. target[name] = source[name];
  579. }
  580. }
  581. return target;
  582. }
  583. function relayEvents(mongoClient, topology) {
  584. const serverOrCommandEvents = [
  585. // APM
  586. 'commandStarted',
  587. 'commandSucceeded',
  588. 'commandFailed',
  589. // SDAM
  590. 'serverOpening',
  591. 'serverClosed',
  592. 'serverDescriptionChanged',
  593. 'serverHeartbeatStarted',
  594. 'serverHeartbeatSucceeded',
  595. 'serverHeartbeatFailed',
  596. 'topologyOpening',
  597. 'topologyClosed',
  598. 'topologyDescriptionChanged',
  599. // Legacy
  600. 'joined',
  601. 'left',
  602. 'ping',
  603. 'ha'
  604. ].concat(CMAP_EVENT_NAMES);
  605. serverOrCommandEvents.forEach(event => {
  606. topology.on(event, (object1, object2) => {
  607. mongoClient.emit(event, object1, object2);
  608. });
  609. });
  610. }
  611. //
  612. // Replay any events due to single server connection switching to Mongos
  613. //
  614. function replayEvents(mongoClient, events) {
  615. for (let i = 0; i < events.length; i++) {
  616. mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
  617. }
  618. }
  619. function transformUrlOptions(_object) {
  620. let object = Object.assign({ servers: _object.hosts }, _object.options);
  621. for (let name in object) {
  622. const camelCaseName = LEGACY_OPTIONS_MAP[name];
  623. if (camelCaseName) {
  624. object[camelCaseName] = object[name];
  625. }
  626. }
  627. const hasUsername = _object.auth && _object.auth.username;
  628. const hasAuthMechanism = _object.options && _object.options.authMechanism;
  629. if (hasUsername || hasAuthMechanism) {
  630. object.auth = Object.assign({}, _object.auth);
  631. if (object.auth.db) {
  632. object.authSource = object.authSource || object.auth.db;
  633. }
  634. if (object.auth.username) {
  635. object.auth.user = object.auth.username;
  636. }
  637. }
  638. if (_object.defaultDatabase) {
  639. object.dbName = _object.defaultDatabase;
  640. }
  641. if (object.maxPoolSize) {
  642. object.poolSize = object.maxPoolSize;
  643. }
  644. if (object.readConcernLevel) {
  645. object.readConcern = new ReadConcern(object.readConcernLevel);
  646. }
  647. if (object.wTimeoutMS) {
  648. object.wtimeout = object.wTimeoutMS;
  649. }
  650. if (_object.srvHost) {
  651. object.srvHost = _object.srvHost;
  652. }
  653. return object;
  654. }
  655. function translateOptions(options, translationOptions) {
  656. translationOptions = Object.assign({}, { createServers: true }, translationOptions);
  657. // If we have a readPreference passed in by the db options
  658. if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') {
  659. options.readPreference = new ReadPreference(options.readPreference || options.read_preference);
  660. }
  661. // Do we have readPreference tags, add them
  662. if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) {
  663. options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags;
  664. }
  665. // Do we have maxStalenessSeconds
  666. if (options.maxStalenessSeconds) {
  667. options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds;
  668. }
  669. // Set the socket and connection timeouts
  670. if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000;
  671. if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000;
  672. if (!translationOptions.createServers) {
  673. return;
  674. }
  675. // Create server instances
  676. return options.servers.map(serverObj => {
  677. return serverObj.domain_socket
  678. ? new Server(serverObj.domain_socket, 27017, options)
  679. : new Server(serverObj.host, serverObj.port, options);
  680. });
  681. }
  682. module.exports = { validOptions, connect };