connection.js 10.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
/*!
 * Module dependencies.
 */

var MongooseConnection = require('../../connection');
var mongo = require('mongodb');
var Db = mongo.Db;
var Server = mongo.Server;
var Mongos = mongo.Mongos;
var STATES = require('../../connectionstate');
var ReplSetServers = mongo.ReplSet;
var DisconnectedError = require('../../error/disconnected');

/**
 * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
 *
 * @inherits Connection
 * @api private
 */

function NativeConnection() {
  MongooseConnection.apply(this, arguments);
  this._listening = false;
}

/**
 * Expose the possible connection states.
 * @api public
 */

NativeConnection.STATES = STATES;

/*!
 * Inherits from Connection.
 */

NativeConnection.prototype.__proto__ = MongooseConnection.prototype;

/**
 * Opens the connection to MongoDB.
 *
 * @param {Function} fn
 * @return {Connection} this
 * @api private
 */

NativeConnection.prototype.doOpen = function(fn) {
  var _this = this;
  var server = new Server(this.host, this.port, this.options.server);

  if (this.options && this.options.mongos) {
    var mongos = new Mongos([server], this.options.mongos);
    this.db = new Db(this.name, mongos, this.options.db);
  } else {
    this.db = new Db(this.name, server, this.options.db);
  }

  this.db.open(function(err) {
    listen(_this);

    if (!mongos) {
      server.s.server.on('error', function(error) {
        if (/after \d+ attempts/.test(error.message)) {
          _this.emit('error', new DisconnectedError(server.s.server.name));
        }
      });
    }

    if (err) return fn(err);

    fn();
  });

  return this;
};

/**
 * Switches to a different database using the same connection pool.
 *
 * Returns a new connection object, with the new db.
 *
 * @param {String} name The database name
 * @return {Connection} New Connection Object
 * @api public
 */

NativeConnection.prototype.useDb = function(name) {
  // we have to manually copy all of the attributes...
  var newConn = new this.constructor();
  newConn.name = name;
  newConn.base = this.base;
  newConn.collections = {};
  newConn.models = {};
  newConn.replica = this.replica;
  newConn.hosts = this.hosts;
  newConn.host = this.host;
  newConn.port = this.port;
  newConn.user = this.user;
  newConn.pass = this.pass;
  newConn.options = this.options;
  newConn._readyState = this._readyState;
  newConn._closeCalled = this._closeCalled;
  newConn._hasOpened = this._hasOpened;
  newConn._listening = false;

  // First, when we create another db object, we are not guaranteed to have a
  // db object to work with. So, in the case where we have a db object and it
  // is connected, we can just proceed with setting everything up. However, if
  // we do not have a db or the state is not connected, then we need to wait on
  // the 'open' event of the connection before doing the rest of the setup
  // the 'connected' event is the first time we'll have access to the db object

  var _this = this;

  if (this.db && this._readyState === STATES.connected) {
    wireup();
  } else {
    this.once('connected', wireup);
  }

  function wireup() {
    newConn.db = _this.db.db(name);
    newConn.onOpen();
    // setup the events appropriately
    listen(newConn);
  }

  newConn.name = name;

  // push onto the otherDbs stack, this is used when state changes
  this.otherDbs.push(newConn);
  newConn.otherDbs.push(this);

  return newConn;
};

/*!
 * Register listeners for important events and bubble appropriately.
 */

function listen(conn) {
  if (conn.db._listening) {
    return;
  }
  conn.db._listening = true;

  conn.db.on('close', function(force) {
    if (conn._closeCalled) return;

    // the driver never emits an `open` event. auto_reconnect still
    // emits a `close` event but since we never get another
    // `open` we can't emit close
    if (conn.db.serverConfig.autoReconnect) {
      conn.readyState = STATES.disconnected;
      conn.emit('close');
      return;
    }
    conn.onClose(force);
  });
  conn.db.on('error', function(err) {
    conn.emit('error', err);
  });
  conn.db.on('reconnect', function() {
    conn.readyState = STATES.connected;
    conn.emit('reconnect');
    conn.emit('reconnected');
    conn.onOpen();
  });
  conn.db.on('timeout', function(err) {
    conn.emit('timeout', err);
  });
  conn.db.on('open', function(err, db) {
    if (STATES.disconnected === conn.readyState && db && db.databaseName) {
      conn.readyState = STATES.connected;
      conn.emit('reconnect');
      conn.emit('reconnected');
    }
  });
  conn.db.on('parseError', function(err) {
    conn.emit('parseError', err);
  });
}

/**
 * Opens a connection to a MongoDB ReplicaSet.
 *
 * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers.
 *
 * @param {Function} fn
 * @api private
 * @return {Connection} this
 */

NativeConnection.prototype.doOpenSet = function(fn) {
  var servers = [],
      _this = this;

  this.hosts.forEach(function(server) {
    var host = server.host || server.ipc;
    var port = server.port || 27017;
    servers.push(new Server(host, port, _this.options.server));
  });

  var server = this.options.mongos
    ? new Mongos(servers, this.options.mongos)
    : new ReplSetServers(servers, this.options.replset || this.options.replSet);
  this.db = new Db(this.name, server, this.options.db);

  this.db.s.topology.on('left', function(data) {
    _this.emit('left', data);
  });

  this.db.s.topology.on('joined', function(data) {
    _this.emit('joined', data);
  });

  this.db.on('fullsetup', function() {
    _this.emit('fullsetup');
  });

  this.db.on('all', function() {
    _this.emit('all');
  });

  this.db.open(function(err) {
    if (err) return fn(err);
    fn();
    listen(_this);
  });

  return this;
};

/**
 * Closes the connection
 *
 * @param {Boolean} [force]
 * @param {Function} [fn]
 * @return {Connection} this
 * @api private
 */

NativeConnection.prototype.doClose = function(force, fn) {
  this.db.close(force, fn);
  return this;
};

/**
 * Prepares default connection options for the node-mongodb-native driver.
 *
 * _NOTE: `passed` options take precedence over connection string options._
 *
 * @param {Object} passed options that were passed directly during connection
 * @param {Object} [connStrOptions] options that were passed in the connection string
 * @api private
 */

NativeConnection.prototype.parseOptions = function(passed, connStrOpts) {
  var o = passed ? require('../../utils').clone(passed) : {};

  o.db || (o.db = {});
  o.auth || (o.auth = {});
  o.server || (o.server = {});
  o.replset || (o.replset = o.replSet) || (o.replset = {});
  o.server.socketOptions || (o.server.socketOptions = {});
  o.replset.socketOptions || (o.replset.socketOptions = {});
  o.mongos || (o.mongos = (connStrOpts && connStrOpts.mongos));
  (o.mongos === true) && (o.mongos = {});

  var opts = connStrOpts || {};
  Object.keys(opts).forEach(function(name) {
    switch (name) {
      case 'ssl':
        o.server.ssl = opts.ssl;
        o.replset.ssl = opts.ssl;
        o.mongos && (o.mongos.ssl = opts.ssl);
        break;
      case 'poolSize':
        if (typeof o.server[name] === 'undefined') {
          o.server[name] = o.replset[name] = opts[name];
        }
        break;
      case 'slaveOk':
        if (typeof o.server.slave_ok === 'undefined') {
          o.server.slave_ok = opts[name];
        }
        break;
      case 'autoReconnect':
        if (typeof o.server.auto_reconnect === 'undefined') {
          o.server.auto_reconnect = opts[name];
        }
        break;
      case 'socketTimeoutMS':
      case 'connectTimeoutMS':
        if (typeof o.server.socketOptions[name] === 'undefined') {
          o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
        }
        break;
      case 'authdb':
        if (typeof o.auth.authdb === 'undefined') {
          o.auth.authdb = opts[name];
        }
        break;
      case 'authSource':
        if (typeof o.auth.authSource === 'undefined') {
          o.auth.authSource = opts[name];
        }
        break;
      case 'authMechanism':
        if (typeof o.auth.authMechanism === 'undefined') {
          o.auth.authMechanism = opts[name];
        }
        break;
      case 'retries':
      case 'reconnectWait':
      case 'rs_name':
        if (typeof o.replset[name] === 'undefined') {
          o.replset[name] = opts[name];
        }
        break;
      case 'replicaSet':
        if (typeof o.replset.rs_name === 'undefined') {
          o.replset.rs_name = opts[name];
        }
        break;
      case 'readSecondary':
        if (typeof o.replset.read_secondary === 'undefined') {
          o.replset.read_secondary = opts[name];
        }
        break;
      case 'nativeParser':
        if (typeof o.db.native_parser === 'undefined') {
          o.db.native_parser = opts[name];
        }
        break;
      case 'w':
      case 'safe':
      case 'fsync':
      case 'journal':
      case 'wtimeoutMS':
        if (typeof o.db[name] === 'undefined') {
          o.db[name] = opts[name];
        }
        break;
      case 'readPreference':
        if (typeof o.db.readPreference === 'undefined') {
          o.db.readPreference = opts[name];
        }
        break;
      case 'readPreferenceTags':
        if (typeof o.db.read_preference_tags === 'undefined') {
          o.db.read_preference_tags = opts[name];
        }
        break;
      case 'sslValidate':
        o.server.sslValidate = opts.sslValidate;
        o.replset.sslValidate = opts.sslValidate;
        o.mongos && (o.mongos.sslValidate = opts.sslValidate);
    }
  });

  if (!('auto_reconnect' in o.server)) {
    o.server.auto_reconnect = true;
  }

  // mongoose creates its own ObjectIds
  o.db.forceServerObjectId = false;

  // default safe using new nomenclature
  if (!('journal' in o.db || 'j' in o.db ||
        'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {
    o.db.w = 1;
  }

  if (o.promiseLibrary) {
    o.db.promiseLibrary = o.promiseLibrary;
  }

  validate(o);
  return o;
};

/*!
 * Validates the driver db options.
 *
 * @param {Object} o
 */

function validate(o) {
  if (o.db.w === -1 || o.db.w === 0) {
    if (o.db.journal || o.db.fsync || o.db.safe) {
      throw new Error(
          'Invalid writeConcern: '
        + 'w set to -1 or 0 cannot be combined with safe|fsync|journal');
    }
  }
}

/*!
 * Module exports.
 */

module.exports = NativeConnection;