connect.js 22 KB

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