Source: lib/topologies/server.js

  1. 'use strict';
  2. const CServer = require('mongodb-core').Server;
  3. const Cursor = require('../cursor');
  4. const TopologyBase = require('./topology_base').TopologyBase;
  5. const Store = require('./topology_base').Store;
  6. const MongoError = require('mongodb-core').MongoError;
  7. const MAX_JS_INT = require('../utils').MAX_JS_INT;
  8. const translateOptions = require('../utils').translateOptions;
  9. const filterOptions = require('../utils').filterOptions;
  10. const mergeOptions = require('../utils').mergeOptions;
  11. /**
  12. * @fileOverview The **Server** class is a class that represents a single server topology and is
  13. * used to construct connections.
  14. *
  15. * **Server Should not be used, use MongoClient.connect**
  16. */
  17. // Allowed parameters
  18. var legalOptionNames = [
  19. 'ha',
  20. 'haInterval',
  21. 'acceptableLatencyMS',
  22. 'poolSize',
  23. 'ssl',
  24. 'checkServerIdentity',
  25. 'sslValidate',
  26. 'sslCA',
  27. 'sslCRL',
  28. 'sslCert',
  29. 'ciphers',
  30. 'ecdhCurve',
  31. 'sslKey',
  32. 'sslPass',
  33. 'socketOptions',
  34. 'bufferMaxEntries',
  35. 'store',
  36. 'auto_reconnect',
  37. 'autoReconnect',
  38. 'emitError',
  39. 'keepAlive',
  40. 'keepAliveInitialDelay',
  41. 'noDelay',
  42. 'connectTimeoutMS',
  43. 'socketTimeoutMS',
  44. 'family',
  45. 'loggerLevel',
  46. 'logger',
  47. 'reconnectTries',
  48. 'reconnectInterval',
  49. 'monitoring',
  50. 'appname',
  51. 'domainsEnabled',
  52. 'servername',
  53. 'promoteLongs',
  54. 'promoteValues',
  55. 'promoteBuffers',
  56. 'compression',
  57. 'promiseLibrary',
  58. 'monitorCommands'
  59. ];
  60. /**
  61. * Creates a new Server instance
  62. * @class
  63. * @deprecated
  64. * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host.
  65. * @param {number} [port] The server port if IP4.
  66. * @param {object} [options=null] Optional settings.
  67. * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
  68. * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support)
  69. * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
  70. * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function.
  71. * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
  72. * @param {array} [options.sslCRL=null] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
  73. * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
  74. * @param {string} [options.ciphers=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
  75. * @param {string} [options.ecdhCurve=null] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info.
  76. * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
  77. * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
  78. * @param {string} [options.servername=null] String containing the server name requested via TLS SNI.
  79. * @param {object} [options.socketOptions=null] Socket options
  80. * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error.
  81. * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option.
  82. * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled
  83. * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket
  84. * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting
  85. * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting
  86. * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times
  87. * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries
  88. * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster
  89. * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled.
  90. * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit.
  91. * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology
  92. * @fires Server#connect
  93. * @fires Server#close
  94. * @fires Server#error
  95. * @fires Server#timeout
  96. * @fires Server#parseError
  97. * @fires Server#reconnect
  98. * @fires Server#commandStarted
  99. * @fires Server#commandSucceeded
  100. * @fires Server#commandFailed
  101. * @property {string} parserType the parser type used (c++ or js).
  102. * @return {Server} a Server instance.
  103. */
  104. class Server extends TopologyBase {
  105. constructor(host, port, options) {
  106. super();
  107. var self = this;
  108. // Filter the options
  109. options = filterOptions(options, legalOptionNames);
  110. // Promise library
  111. const promiseLibrary = options.promiseLibrary;
  112. // Stored options
  113. var storeOptions = {
  114. force: false,
  115. bufferMaxEntries:
  116. typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT
  117. };
  118. // Shared global store
  119. var store = options.store || new Store(self, storeOptions);
  120. // Detect if we have a socket connection
  121. if (host.indexOf('/') !== -1) {
  122. if (port != null && typeof port === 'object') {
  123. options = port;
  124. port = null;
  125. }
  126. } else if (port == null) {
  127. throw MongoError.create({ message: 'port must be specified', driver: true });
  128. }
  129. // Get the reconnect option
  130. var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true;
  131. reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect;
  132. // Clone options
  133. var clonedOptions = mergeOptions(
  134. {},
  135. {
  136. host: host,
  137. port: port,
  138. disconnectHandler: store,
  139. cursorFactory: Cursor,
  140. reconnect: reconnect,
  141. emitError: typeof options.emitError === 'boolean' ? options.emitError : true,
  142. size: typeof options.poolSize === 'number' ? options.poolSize : 5,
  143. monitorCommands:
  144. typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false
  145. }
  146. );
  147. // Translate any SSL options and other connectivity options
  148. clonedOptions = translateOptions(clonedOptions, options);
  149. // Socket options
  150. var socketOptions =
  151. options.socketOptions && Object.keys(options.socketOptions).length > 0
  152. ? options.socketOptions
  153. : options;
  154. // Translate all the options to the mongodb-core ones
  155. clonedOptions = translateOptions(clonedOptions, socketOptions);
  156. // Build default client information
  157. clonedOptions.clientInfo = this.clientInfo;
  158. // Do we have an application specific string
  159. if (options.appname) {
  160. clonedOptions.clientInfo.application = { name: options.appname };
  161. }
  162. // Define the internal properties
  163. this.s = {
  164. // Create an instance of a server instance from mongodb-core
  165. coreTopology: new CServer(clonedOptions),
  166. // Server capabilities
  167. sCapabilities: null,
  168. // Cloned options
  169. clonedOptions: clonedOptions,
  170. // Reconnect
  171. reconnect: clonedOptions.reconnect,
  172. // Emit error
  173. emitError: clonedOptions.emitError,
  174. // Pool size
  175. poolSize: clonedOptions.size,
  176. // Store Options
  177. storeOptions: storeOptions,
  178. // Store
  179. store: store,
  180. // Host
  181. host: host,
  182. // Port
  183. port: port,
  184. // Options
  185. options: options,
  186. // Server Session Pool
  187. sessionPool: null,
  188. // Active client sessions
  189. sessions: [],
  190. // Promise library
  191. promiseLibrary: promiseLibrary || Promise
  192. };
  193. }
  194. // Connect
  195. connect(_options, callback) {
  196. var self = this;
  197. if ('function' === typeof _options) (callback = _options), (_options = {});
  198. if (_options == null) _options = this.s.clonedOptions;
  199. if (!('function' === typeof callback)) callback = null;
  200. _options = Object.assign({}, this.s.clonedOptions, _options);
  201. self.s.options = _options;
  202. // Update bufferMaxEntries
  203. self.s.storeOptions.bufferMaxEntries =
  204. typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1;
  205. // Error handler
  206. var connectErrorHandler = function() {
  207. return function(err) {
  208. // Remove all event handlers
  209. var events = ['timeout', 'error', 'close'];
  210. events.forEach(function(e) {
  211. self.s.coreTopology.removeListener(e, connectHandlers[e]);
  212. });
  213. self.s.coreTopology.removeListener('connect', connectErrorHandler);
  214. // Try to callback
  215. try {
  216. callback(err);
  217. } catch (err) {
  218. process.nextTick(function() {
  219. throw err;
  220. });
  221. }
  222. };
  223. };
  224. // Actual handler
  225. var errorHandler = function(event) {
  226. return function(err) {
  227. if (event !== 'error') {
  228. self.emit(event, err);
  229. }
  230. };
  231. };
  232. // Error handler
  233. var reconnectHandler = function() {
  234. self.emit('reconnect', self);
  235. self.s.store.execute();
  236. };
  237. // Reconnect failed
  238. var reconnectFailedHandler = function(err) {
  239. self.emit('reconnectFailed', err);
  240. self.s.store.flush(err);
  241. };
  242. // Destroy called on topology, perform cleanup
  243. var destroyHandler = function() {
  244. self.s.store.flush();
  245. };
  246. // relay the event
  247. var relay = function(event) {
  248. return function(t, server) {
  249. self.emit(event, t, server);
  250. };
  251. };
  252. // Connect handler
  253. var connectHandler = function() {
  254. // Clear out all the current handlers left over
  255. ['timeout', 'error', 'close', 'destroy'].forEach(function(e) {
  256. self.s.coreTopology.removeAllListeners(e);
  257. });
  258. // Set up listeners
  259. self.s.coreTopology.on('timeout', errorHandler('timeout'));
  260. self.s.coreTopology.once('error', errorHandler('error'));
  261. self.s.coreTopology.on('close', errorHandler('close'));
  262. // Only called on destroy
  263. self.s.coreTopology.on('destroy', destroyHandler);
  264. // Emit open event
  265. self.emit('open', null, self);
  266. // Return correctly
  267. try {
  268. callback(null, self);
  269. } catch (err) {
  270. console.log(err.stack);
  271. process.nextTick(function() {
  272. throw err;
  273. });
  274. }
  275. };
  276. // Set up listeners
  277. var connectHandlers = {
  278. timeout: connectErrorHandler('timeout'),
  279. error: connectErrorHandler('error'),
  280. close: connectErrorHandler('close')
  281. };
  282. // Clear out all the current handlers left over
  283. [
  284. 'timeout',
  285. 'error',
  286. 'close',
  287. 'serverOpening',
  288. 'serverDescriptionChanged',
  289. 'serverHeartbeatStarted',
  290. 'serverHeartbeatSucceeded',
  291. 'serverHeartbeatFailed',
  292. 'serverClosed',
  293. 'topologyOpening',
  294. 'topologyClosed',
  295. 'topologyDescriptionChanged',
  296. 'commandStarted',
  297. 'commandSucceeded',
  298. 'commandFailed'
  299. ].forEach(function(e) {
  300. self.s.coreTopology.removeAllListeners(e);
  301. });
  302. // Add the event handlers
  303. self.s.coreTopology.once('timeout', connectHandlers.timeout);
  304. self.s.coreTopology.once('error', connectHandlers.error);
  305. self.s.coreTopology.once('close', connectHandlers.close);
  306. self.s.coreTopology.once('connect', connectHandler);
  307. // Reconnect server
  308. self.s.coreTopology.on('reconnect', reconnectHandler);
  309. self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler);
  310. // Set up SDAM listeners
  311. self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged'));
  312. self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted'));
  313. self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded'));
  314. self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed'));
  315. self.s.coreTopology.on('serverOpening', relay('serverOpening'));
  316. self.s.coreTopology.on('serverClosed', relay('serverClosed'));
  317. self.s.coreTopology.on('topologyOpening', relay('topologyOpening'));
  318. self.s.coreTopology.on('topologyClosed', relay('topologyClosed'));
  319. self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged'));
  320. self.s.coreTopology.on('commandStarted', relay('commandStarted'));
  321. self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded'));
  322. self.s.coreTopology.on('commandFailed', relay('commandFailed'));
  323. self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect'));
  324. self.s.coreTopology.on('monitoring', relay('monitoring'));
  325. // Start connection
  326. self.s.coreTopology.connect(_options);
  327. }
  328. }
  329. Object.defineProperty(Server.prototype, 'poolSize', {
  330. enumerable: true,
  331. get: function() {
  332. return this.s.coreTopology.connections().length;
  333. }
  334. });
  335. Object.defineProperty(Server.prototype, 'autoReconnect', {
  336. enumerable: true,
  337. get: function() {
  338. return this.s.reconnect;
  339. }
  340. });
  341. Object.defineProperty(Server.prototype, 'host', {
  342. enumerable: true,
  343. get: function() {
  344. return this.s.host;
  345. }
  346. });
  347. Object.defineProperty(Server.prototype, 'port', {
  348. enumerable: true,
  349. get: function() {
  350. return this.s.port;
  351. }
  352. });
  353. /**
  354. * Server connect event
  355. *
  356. * @event Server#connect
  357. * @type {object}
  358. */
  359. /**
  360. * Server close event
  361. *
  362. * @event Server#close
  363. * @type {object}
  364. */
  365. /**
  366. * Server reconnect event
  367. *
  368. * @event Server#reconnect
  369. * @type {object}
  370. */
  371. /**
  372. * Server error event
  373. *
  374. * @event Server#error
  375. * @type {MongoError}
  376. */
  377. /**
  378. * Server timeout event
  379. *
  380. * @event Server#timeout
  381. * @type {object}
  382. */
  383. /**
  384. * Server parseError event
  385. *
  386. * @event Server#parseError
  387. * @type {object}
  388. */
  389. /**
  390. * An event emitted indicating a command was started, if command monitoring is enabled
  391. *
  392. * @event Server#commandStarted
  393. * @type {object}
  394. */
  395. /**
  396. * An event emitted indicating a command succeeded, if command monitoring is enabled
  397. *
  398. * @event Server#commandSucceeded
  399. * @type {object}
  400. */
  401. /**
  402. * An event emitted indicating a command failed, if command monitoring is enabled
  403. *
  404. * @event Server#commandFailed
  405. * @type {object}
  406. */
  407. module.exports = Server;