topology_base.js 10.8 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 404 405 406 407 408 409 410 411 412 413 414 415 416 417
'use strict';

const EventEmitter = require('events'),
  MongoError = require('../core').MongoError,
  f = require('util').format,
  ReadPreference = require('../core').ReadPreference,
  ClientSession = require('../core').Sessions.ClientSession;

// The store of ops
var Store = function(topology, storeOptions) {
  var self = this;
  var storedOps = [];
  storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 };

  // Internal state
  this.s = {
    storedOps: storedOps,
    storeOptions: storeOptions,
    topology: topology
  };

  Object.defineProperty(this, 'length', {
    enumerable: true,
    get: function() {
      return self.s.storedOps.length;
    }
  });
};

Store.prototype.add = function(opType, ns, ops, options, callback) {
  if (this.s.storeOptions.force) {
    return callback(MongoError.create({ message: 'db closed by application', driver: true }));
  }

  if (this.s.storeOptions.bufferMaxEntries === 0) {
    return callback(
      MongoError.create({
        message: f(
          'no connection available for operation and number of stored operation > %s',
          this.s.storeOptions.bufferMaxEntries
        ),
        driver: true
      })
    );
  }

  if (
    this.s.storeOptions.bufferMaxEntries > 0 &&
    this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries
  ) {
    while (this.s.storedOps.length > 0) {
      var op = this.s.storedOps.shift();
      op.c(
        MongoError.create({
          message: f(
            'no connection available for operation and number of stored operation > %s',
            this.s.storeOptions.bufferMaxEntries
          ),
          driver: true
        })
      );
    }

    return;
  }

  this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback });
};

Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) {
  if (this.s.storeOptions.force) {
    return callback(MongoError.create({ message: 'db closed by application', driver: true }));
  }

  if (this.s.storeOptions.bufferMaxEntries === 0) {
    return callback(
      MongoError.create({
        message: f(
          'no connection available for operation and number of stored operation > %s',
          this.s.storeOptions.bufferMaxEntries
        ),
        driver: true
      })
    );
  }

  if (
    this.s.storeOptions.bufferMaxEntries > 0 &&
    this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries
  ) {
    while (this.s.storedOps.length > 0) {
      var op = this.s.storedOps.shift();
      op.c(
        MongoError.create({
          message: f(
            'no connection available for operation and number of stored operation > %s',
            this.s.storeOptions.bufferMaxEntries
          ),
          driver: true
        })
      );
    }

    return;
  }

  this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback });
};

Store.prototype.flush = function(err) {
  while (this.s.storedOps.length > 0) {
    this.s.storedOps
      .shift()
      .c(
        err ||
          MongoError.create({ message: f('no connection available for operation'), driver: true })
      );
  }
};

var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred'];
var secondaryOptions = ['secondary', 'secondaryPreferred'];

Store.prototype.execute = function(options) {
  options = options || {};
  // Get current ops
  var ops = this.s.storedOps;
  // Reset the ops
  this.s.storedOps = [];

  // Unpack options
  var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true;
  var executeSecondary =
    typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true;

  // Execute all the stored ops
  while (ops.length > 0) {
    var op = ops.shift();

    if (op.t === 'cursor') {
      if (executePrimary && executeSecondary) {
        op.o[op.m].apply(op.o, op.p);
      } else if (
        executePrimary &&
        op.o.options &&
        op.o.options.readPreference &&
        primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1
      ) {
        op.o[op.m].apply(op.o, op.p);
      } else if (
        !executePrimary &&
        executeSecondary &&
        op.o.options &&
        op.o.options.readPreference &&
        secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1
      ) {
        op.o[op.m].apply(op.o, op.p);
      }
    } else if (op.t === 'auth') {
      this.s.topology[op.t].apply(this.s.topology, op.o);
    } else {
      if (executePrimary && executeSecondary) {
        this.s.topology[op.t](op.n, op.o, op.op, op.c);
      } else if (
        executePrimary &&
        op.op &&
        op.op.readPreference &&
        primaryOptions.indexOf(op.op.readPreference.mode) !== -1
      ) {
        this.s.topology[op.t](op.n, op.o, op.op, op.c);
      } else if (
        !executePrimary &&
        executeSecondary &&
        op.op &&
        op.op.readPreference &&
        secondaryOptions.indexOf(op.op.readPreference.mode) !== -1
      ) {
        this.s.topology[op.t](op.n, op.o, op.op, op.c);
      }
    }
  }
};

Store.prototype.all = function() {
  return this.s.storedOps;
};

// Server capabilities
var ServerCapabilities = function(ismaster) {
  var setup_get_property = function(object, name, value) {
    Object.defineProperty(object, name, {
      enumerable: true,
      get: function() {
        return value;
      }
    });
  };

  // Capabilities
  var aggregationCursor = false;
  var writeCommands = false;
  var textSearch = false;
  var authCommands = false;
  var listCollections = false;
  var listIndexes = false;
  var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000;
  var commandsTakeWriteConcern = false;
  var commandsTakeCollation = false;

  if (ismaster.minWireVersion >= 0) {
    textSearch = true;
  }

  if (ismaster.maxWireVersion >= 1) {
    aggregationCursor = true;
    authCommands = true;
  }

  if (ismaster.maxWireVersion >= 2) {
    writeCommands = true;
  }

  if (ismaster.maxWireVersion >= 3) {
    listCollections = true;
    listIndexes = true;
  }

  if (ismaster.maxWireVersion >= 5) {
    commandsTakeWriteConcern = true;
    commandsTakeCollation = true;
  }

  // If no min or max wire version set to 0
  if (ismaster.minWireVersion == null) {
    ismaster.minWireVersion = 0;
  }

  if (ismaster.maxWireVersion == null) {
    ismaster.maxWireVersion = 0;
  }

  // Map up read only parameters
  setup_get_property(this, 'hasAggregationCursor', aggregationCursor);
  setup_get_property(this, 'hasWriteCommands', writeCommands);
  setup_get_property(this, 'hasTextSearch', textSearch);
  setup_get_property(this, 'hasAuthCommands', authCommands);
  setup_get_property(this, 'hasListCollectionsCommand', listCollections);
  setup_get_property(this, 'hasListIndexesCommand', listIndexes);
  setup_get_property(this, 'minWireVersion', ismaster.minWireVersion);
  setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion);
  setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch);
  setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern);
  setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation);
};

class TopologyBase extends EventEmitter {
  constructor() {
    super();
    this.setMaxListeners(Infinity);
  }

  // Sessions related methods
  hasSessionSupport() {
    return this.logicalSessionTimeoutMinutes != null;
  }

  startSession(options, clientOptions) {
    const session = new ClientSession(this, this.s.sessionPool, options, clientOptions);

    session.once('ended', () => {
      this.s.sessions.delete(session);
    });

    this.s.sessions.add(session);
    return session;
  }

  endSessions(sessions, callback) {
    return this.s.coreTopology.endSessions(sessions, callback);
  }

  get clientMetadata() {
    return this.s.coreTopology.s.options.metadata;
  }

  // Server capabilities
  capabilities() {
    if (this.s.sCapabilities) return this.s.sCapabilities;
    if (this.s.coreTopology.lastIsMaster() == null) return null;
    this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster());
    return this.s.sCapabilities;
  }

  // Command
  command(ns, cmd, options, callback) {
    this.s.coreTopology.command(ns.toString(), cmd, ReadPreference.translate(options), callback);
  }

  // Insert
  insert(ns, ops, options, callback) {
    this.s.coreTopology.insert(ns.toString(), ops, options, callback);
  }

  // Update
  update(ns, ops, options, callback) {
    this.s.coreTopology.update(ns.toString(), ops, options, callback);
  }

  // Remove
  remove(ns, ops, options, callback) {
    this.s.coreTopology.remove(ns.toString(), ops, options, callback);
  }

  // IsConnected
  isConnected(options) {
    options = options || {};
    options = ReadPreference.translate(options);

    return this.s.coreTopology.isConnected(options);
  }

  // IsDestroyed
  isDestroyed() {
    return this.s.coreTopology.isDestroyed();
  }

  // Cursor
  cursor(ns, cmd, options) {
    options = options || {};
    options = ReadPreference.translate(options);
    options.disconnectHandler = this.s.store;
    options.topology = this;

    return this.s.coreTopology.cursor(ns, cmd, options);
  }

  lastIsMaster() {
    return this.s.coreTopology.lastIsMaster();
  }

  selectServer(selector, options, callback) {
    return this.s.coreTopology.selectServer(selector, options, callback);
  }

  /**
   * Unref all sockets
   * @method
   */
  unref() {
    return this.s.coreTopology.unref();
  }

  /**
   * All raw connections
   * @method
   * @return {array}
   */
  connections() {
    return this.s.coreTopology.connections();
  }

  close(forceClosed, callback) {
    // If we have sessions, we want to individually move them to the session pool,
    // and then send a single endSessions call.
    this.s.sessions.forEach(session => session.endSession());

    if (this.s.sessionPool) {
      this.s.sessionPool.endAllPooledSessions();
    }

    // We need to wash out all stored processes
    if (forceClosed === true) {
      this.s.storeOptions.force = forceClosed;
      this.s.store.flush();
    }

    this.s.coreTopology.destroy(
      {
        force: typeof forceClosed === 'boolean' ? forceClosed : false
      },
      callback
    );
  }
}

// Properties
Object.defineProperty(TopologyBase.prototype, 'bson', {
  enumerable: true,
  get: function() {
    return this.s.coreTopology.s.bson;
  }
});

Object.defineProperty(TopologyBase.prototype, 'parserType', {
  enumerable: true,
  get: function() {
    return this.s.coreTopology.parserType;
  }
});

Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', {
  enumerable: true,
  get: function() {
    return this.s.coreTopology.logicalSessionTimeoutMinutes;
  }
});

Object.defineProperty(TopologyBase.prototype, 'type', {
  enumerable: true,
  get: function() {
    return this.s.coreTopology.type;
  }
});

exports.Store = Store;
exports.ServerCapabilities = ServerCapabilities;
exports.TopologyBase = TopologyBase;