connect.js 22 KB

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