Replay any events due to single server connection switching to Mongos
764666
function replayEvents(mongoClient, events) {
  for (let i = 0; i < events.length; i++) {
    mongoClient.emit(events[i].event, events[i].object1, events[i].object2);
  }
}
1366966
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
         include_initial=True):
    """"""
    # First dump the full list of events in chronological order and keep
    # track of the events we've seen already
    seen = set()
    initial_events = get_events(conn, stack_name)
    for e in initial_events:
        if include_initial:
            log_func(e)
        seen.add(e.event_id)

    # Now keep looping through and dump the new events
    while 1:
        events = get_events(conn, stack_name)
        for e in events:
            if e.event_id not in seen:
                log_func(e)
                seen.add(e.event_id)
        time.sleep(sleep_time)
158417
function ReplayHandler (disp, store, def, options) {
  this.dispatcher = disp;

  this.store = store;

  def = def || {};

  this.definition = {
    correlationId: 'correlationId', // optional
    id: 'id',                       // optional
    name: 'name',                   // optional
//      aggregateId: 'aggregate.id',    // optional
//      context: 'context.name',        // optional
//      aggregate: 'aggregate.name',    // optional
    payload: 'payload'              // optional
//      revision: 'revision'            // optional
//      version: 'version',             // optional
//      meta: 'meta'                    // optional, if defined theses values will be copied to the notification (can be used to transport information like userId, etc..)
  };

  this.definition = _.defaults(def, this.definition);

  options = options || {};

  this.options = options;
}
356153
function () {
        var self = this;

        async.waterfall([

          function (next) {
            if (!self.events) {
              self.events = new Datastore();
              self.events.ensureIndex({
                fieldName: 'event_id',
                unique: true
              });
              self.events.ensureIndex({
                fieldName: 'recorded_at',
                sparse: true
              });
              self.events.ensureIndex({
                fieldName: 'created_at',
              }, next);
            } else {
              next();
            }
          },
          function (next) {
            if (!self.keepPolling) {
              self.keepPolling = true;

              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._emit, self), _.noop);
              next(null, true);
            } else {
              next(null, false);
            }
          },

          function (doLongPoll, next) {
            if (doLongPoll) {
              async.whilst(function () {
                return self.keepPolling;
              }, _.bind(self._longPoll, self), function (err) {
                if (err) {
                  /**
                   * Fires when an error occurs during long-polling.
                   * @event Connection#"polling.error"
                   * @type {Error}
                   * @see {@link Connection#startLongPolling}
                   */
                  self.emit('polling.error', err);
                } else if (!self.keepPolling) {
                  /**
                   * Fires when a running long-polling process ends.
                   * @event Connection#"polling.end"
                   * @see {@link Connection#stopLongPolling}
                   */
                  self.emit('polling.end');
                }
              });
            }
            next();
          }
        ], _.noop);
      }
913319
function(self, callback) {
  if (self.pool && self.pool.isDestroyed()) {
    self.cursorState.killed = true;
    const err = new MongoNetworkError(
      f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port)
    );
    _setCursorNotifiedImpl(self, () => callback(err));
    return true;
  }

  return false;
}
1028194
async function connect (mongoose, connectionName, connectionOpts) {
  const isDefault = connectionName === 'default'

  // Normalize and destructure connection options
  if (typeof connectionOpts === 'string') {
    connectionOpts = { uri: connectionOpts }
  }
  let { uri, options, forceReconnect } = connectionOpts

  // Apply default options
  // https://mongoosejs.com/docs/connections.html#options
  options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    ...options
  }

  // Manualy create connection
  let conn
  if (isDefault) {
    conn = mongoose.connection
  } else {
    conn = new mongoose.Connection(mongoose)
    mongoose.connections.push(conn)
  }

  // $logger helper
  conn.$logger = isDefault
    ? consola
    : consola.withTag(connectionName)

  // Log connection events
  logConnectionEvents(conn)

  // $connect helper
  conn.$connect = () => {
    return new Promise((resolve, reject) => {
      conn.openUri(uri, options, (error) => {
        if (error) {
          reject(error)
        } else {
          resolve(conn)
        }
      })
    })
  }

  // Make accessable via mongoose.$connectionName
  mongoose['$' + connectionName] = conn

  // Setup force reconnect
  if (forceReconnect) {
    const timeout = forceReconnect === true ? 1000 : forceReconnect
    conn.on('error', () => {
      conn.close()
    })
    conn.on('disconnected', () => {
      setTimeout(() => { conn.$connect() }, timeout)
    })
  }

  // Connect
  await conn.$connect()
  await conn.$initialConnection
}
523619
function _connectionFailureHandler(self) {
      return function() {
        if (this._connectionFailHandled) return;
        this._connectionFailHandled = true;
        // Destroy the connection
        this.destroy();
        // Count down the number of reconnects
        self.retriesLeft = self.retriesLeft - 1;
        // How many retries are left
        if (self.retriesLeft <= 0) {
          // Destroy the instance
          self.destroy();
          // Emit close event
          self.emit(
            'reconnectFailed',
            new MongoNetworkError(
              f(
                'failed to reconnect after %s attempts with interval %s ms',
                self.options.reconnectTries,
                self.options.reconnectInterval
              )
            )
          );
        } else {
          self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval);
        }
      };
    }
125225
def mongo_retry(f):
    
    log_all_exceptions = 'arctic' in f.__module__ if f.__module__ else False

    @wraps(f)
    def f_retry(*args, **kwargs):
        global _retry_count, _in_retry
        top_level = not _in_retry
        _in_retry = True
        try:
            while True:
                try:
                    return f(*args, **kwargs)
                except (DuplicateKeyError, ServerSelectionTimeoutError) as e:
                    # Re-raise errors that won't go away.
                    _handle_error(f, e, _retry_count, **_get_host(args))
                    raise
                except (OperationFailure, AutoReconnect) as e:
                    _retry_count += 1
                    _handle_error(f, e, _retry_count, **_get_host(args))
                except Exception as e:
                    if log_all_exceptions:
                        _log_exception(f.__name__, e, _retry_count, **_get_host(args))
                    raise
        finally:
            if top_level:
                _in_retry = False
                _retry_count = 0
    return f_retry
1052404
function processNewChange(args) {
  const changeStream = args.changeStream;
  const error = args.error;
  const change = args.change;
  const callback = args.callback;
  const eventEmitter = args.eventEmitter || false;

  // If the changeStream is closed, then it should not process a change.
  if (changeStream.isClosed()) {
    // We do not error in the eventEmitter case.
    if (eventEmitter) {
      return;
    }

    const error = new MongoError('ChangeStream is closed');
    return typeof callback === 'function'
      ? callback(error, null)
      : changeStream.promiseLibrary.reject(error);
  }

  const topology = changeStream.topology;
  const options = changeStream.cursor.options;

  if (error) {
    if (isResumableError(error) && !changeStream.attemptingResume) {
      changeStream.attemptingResume = true;

      if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) {
        const startAtOperationTime = changeStream.cursor.cursorState.operationTime;
        changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options);
      }

      // stop listening to all events from old cursor
      ['data', 'close', 'end', 'error'].forEach(event =>
        changeStream.cursor.removeAllListeners(event)
      );

      // close internal cursor, ignore errors
      changeStream.cursor.close();

      // attempt recreating the cursor
      if (eventEmitter) {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return changeStream.emit('error', err);
          changeStream.cursor = createChangeStreamCursor(changeStream);
        });

        return;
      }

      if (callback) {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return callback(err, null);

          changeStream.cursor = createChangeStreamCursor(changeStream);
          changeStream.next(callback);
        });

        return;
      }

      return new Promise((resolve, reject) => {
        waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
          if (err) return reject(err);
          resolve();
        });
      })
        .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream)))
        .then(() => changeStream.next());
    }

    if (eventEmitter) return changeStream.emit('error', error);
    if (typeof callback === 'function') return callback(error, null);
    return changeStream.promiseLibrary.reject(error);
  }

  changeStream.attemptingResume = false;

  // Cache the resume token if it is present. If it is not present return an error.
  if (!change || !change._id) {
    var noResumeTokenError = new Error(
      'A change stream document has been received that lacks a resume token (_id).'
    );

    if (eventEmitter) return changeStream.emit('error', noResumeTokenError);
    if (typeof callback === 'function') return callback(noResumeTokenError, null);
    return changeStream.promiseLibrary.reject(noResumeTokenError);
  }

  changeStream.resumeToken = change._id;

  // Return the change
  if (eventEmitter) return changeStream.emit('change', change);
  if (typeof callback === 'function') return callback(error, change);
  return changeStream.promiseLibrary.resolve(change);
}
336980
function parseMongoConnectionOptions(req, res, next) {
  var options = {};
  options.uri = req.mongoUrl;

  req.connectionOptions = options;

  return next();
}
625674
def event_return(events):
    '''
    
    '''
    with _get_serv(events, commit=True) as cur:
        for event in events:
            tag = event.get('tag', '')
            data = event.get('data', '')
            sql = '''INSERT INTO `salt_events` (`tag`, `data`, `master_id`)
                     VALUES (%s, %s, %s)'''
            cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))
939321
def _get_events(self):
        """"""
        events, changed_container_ids = self.docker_util.get_events()
        if not self._disable_net_metrics:
            self._invalidate_network_mapping_cache(events)
        if changed_container_ids and self._service_discovery:
            get_sd_backend(self.agentConfig).update_checks(changed_container_ids)
        if changed_container_ids:
            self.metadata_collector.invalidate_cache(events)
        return events
1330286
def events(self, from_dt=None, to_dt=None):
        
        self.refresh_client(from_dt, to_dt)
        return self.response['Event']
293656
function executeReconnect(self) {
    return function() {
      if (self.state === DESTROYED || self.state === UNREFERENCED) {
        return;
      }

      connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
        var monitoringFrequencey = self.s.replicaSetState.hasPrimary()
          ? _haInterval
          : self.s.minHeartbeatFrequencyMS;

        // Create a timeout
        self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start());
      });
    };
  }
1220761
function logConnectionEvents (conn) {
  // Emitted after getting disconnected from the db.
  // _readyState: 0
  conn.on('disconnected', () => {
    conn.$logger.debug('Disconnected!')
  })

  // Emitted when this connection successfully connects to the db.
  // May be emitted multiple times in reconnected scenarios.
  // _readyState: 1
  conn.on('connected', () => {
    conn.$logger.success('Connected!')
  })

  // Emitted when connection.{open,openSet}() is executed on this connection.
  // _readyState: 2
  conn.on('connecting', () => {
    conn.$logger.info('Connecting...')
  })

  // Emitted when connection.close() was executed.
  // _readyState: 3
  conn.on('disconnecting', () => {
    conn.$logger.debug('Disconnecting...')
  })

  // Emitted when an error occurs on this connection.
  conn.on('error', (error) => {
    conn.$logger.error(error)
  })

  // Emitted after we connected and onOpen is executed
  // on all of this connections models.
  conn.on('open', () => {
    conn.$logger.debug('Connection opened!')
  })

  // Emitted after we connected and subsequently disconnected,
  // followed by successfully another successfull connection.
  conn.on('reconnected', () => {
    conn.$logger.debug('Reconnected!')
  })

  // Emitted in a replica-set scenario, when all nodes specified
  // in the connection string are connected.
  conn.on('fullsetup', () => {
    conn.$logger.debug('ReplicaSet ready!')
  })
}
35857
function(connectionName, collectionName, options, stream) {

      options = options || {};

      var connectionObject = connections[connectionName];
      if (!connectionObject) return stream.end(Errors.InvalidConnection);

      var collection = connectionObject.collections[collectionName];
      if (!collection) return stream.end(Errors.CollectionNotRegistered);

      collection.stream(options, stream);
    }
302234
function (id, callback) {
    if (this.isReplaying) {
      if (this.replayingVms[id]) {
        return callback(null, this.replayingVms[id]);
      }
      if (this.replayingVmsToDelete[id]) {
        var vm = new viewmodel.ViewModel({ id: id }, this.repository);
        var clonedInitValues = _.cloneDeep(this.modelInitValues);
        for (var prop in clonedInitValues) {
          if (!vm.has(prop)) {
            vm.set(prop, clonedInitValues[prop]);
          }
        }
        this.replayingVms[vm.id] = vm;
        return callback(null, this.replayingVms[id]);
      }
    }
    var self = this;
    this.repository.get(id, function(err, vm) {
      if (err) {
        debug(err);
        return callback(err);
      }
      if (!vm) {
        err = new Error('No vm object returned!');
        debug(err);
        return callback(err);
      }
      var clonedInitValues = _.cloneDeep(self.modelInitValues);
      for (var prop in clonedInitValues) {
        if (!vm.has(prop)) {
          vm.set(prop, clonedInitValues[prop]);
        }
      }
      if (self.isReplaying) {
        if (!self.replayingVms[vm.id]) {
          self.replayingVms[vm.id] = vm;
        }
        return callback(null, self.replayingVms[vm.id]);
      }
      callback(null, vm);
    });
  }