Monk constructor.

@param {Array|String} uri replica sets can be an array or
comma-separated
@param {Object|Function} opts or connect callback
@param {Function} fn connect callback
@return {Promise} resolve when the connection is opened
340362
function Manager (uri, opts, fn) {
  if (!uri) {
    throw Error('No connection URI provided.')
  }

  if (!(this instanceof Manager)) {
    return new Manager(uri, opts, fn)
  }

  if (typeof opts === 'function') {
    fn = opts
    opts = {}
  }

  opts = opts || {}

  this._collectionOptions = objectAssign({}, DEFAULT_OPTIONS, opts.collectionOptions || {})
  delete opts.collectionOptions

  if (Array.isArray(uri)) {
    if (!opts.database) {
      for (var i = 0, l = uri.length; i < l; i++) {
        if (!opts.database) {
          opts.database = uri[i].replace(/([^\/])+\/?/, '') // eslint-disable-line
        }
        uri[i] = uri[i].replace(/\/.*/, '')
      }
    }
    uri = uri.join(',') + '/' + opts.database
    monkDebug('repl set connection "%j" to database "%s"', uri, opts.database)
  }

  if (typeof uri === 'string') {
    if (!/^mongodb:\/\//.test(uri)) {
      uri = 'mongodb://' + uri
    }
  }

  this._state = STATE.OPENING

  this._queue = []
  this.on('open', function (db) {
    monkDebug('connection opened')
    monkDebug('emptying queries queue (%s to go)', this._queue.length)
    this._queue.forEach(function (cb) {
      cb(db)
    })
  }.bind(this))

  this._connectionURI = uri
  this._connectionOptions = opts

  this.open(uri, opts, fn && function (err) {
    fn(err, this)
  }.bind(this))

  this.helper = {
    id: ObjectId
  }

  this.collections = {}

  this.open = this.open.bind(this)
  this.close = this.close.bind(this)
  this.executeWhenOpened = this.executeWhenOpened.bind(this)
  this.collection = this.col = this.get = this.get.bind(this)
  this.oid = this.id
  this.setDefaultCollectionOptions = this.setDefaultCollectionOptions.bind(this)
  this.addMiddleware = this.addMiddleware.bind(this)
}
349451
function(callback) { // # 1

          var startReplicas = Math.pow(Number(self.conf.balancing['REPLICA_BASE_NUMBER']), Number(self.conf.balancing['MAX_LEVEL']));

          var address = '';
          if (self.conf.zookeeper) {
            if (typeof self.conf.zookeeper === 'string' || self.conf.zookeeper instanceof String) {
              address = self.conf.zookeeper;
            } else {
              if (self.conf.zookeeper.address) address = self.conf.zookeeper.address;
            }
          }

          self.nodeManager = new NodeManager(
            address,
            false,
            function(err, message) {
              if (!err) {
                console.info(' (init) ZOOKEEPER is connected');
                self.nodeManager.addServerNode(self.conf, startReplicas, function(err, path, replicas) {

                  //if (!err) console.info('        ZOOKEEPER /' + self.conf.host + ':' + self.conf.port);

                  var serverName = path.substring(path.lastIndexOf('/') + 1, path.length);
                  self.serverNodePath = path;

                  self.serverName = serverName.split('^')[0];

                  if (replicas) {
                    self.replicas = replicas;
                  } else {
                    self.replicas = startReplicas;
                  }

                  // init balacing config
                  self.nodeManager.getConfigInfo('balancing', function(data) {
                    if (data) {

                      self.conf.balancing = data;
                      var configReplica = Math.pow(Number(self.conf.balancing['REPLICA_BASE_NUMBER']), Number(self.conf.balancing['MAX_LEVEL']));

                      if (self.replicas != configReplica) {
                        self._changeReplicas(configReplica);
                      }
                    }
                  });

                  callback(err);
                });
              } else {
                callback(err, message);
              }
            }
          );
        }
1361752
function read(uri) {
    "use strict";
    var parsedUrl = url.parse(uri, false, true);
    var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
    var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
    var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;

    var options = {
        host: parsedUrl.host,
        path: parsedUrl.path,
        agent: agent,
        port: serverPort,
        method: 'GET',
        headers: {'Content-Type': 'application/json'}
    };

    return new Promise(function (resolve, reject) {

        var req = makeRequest(options, function (response) {
            var data = '';

            response.on('data', function (chunk) {
                data += chunk;
            });

            response.on('end', function () {
                resolve({
                    status: response.statusCode,
                    data: data
                });
            });
        });

        req.on('error', reject);
        req.end();
    });
}
879063
function knStartServer(args, callback)
{
	var host, port, server;

	if (!mod_restify)
		mod_restify = require('restify');

	mod_assert.ok('uri_base' in args);
	mod_assert.equal('string', typeof (args['uri_base']));

	port = 'port' in args ? args['port'] : 80;
	host = 'host' in args ? args['host'] : '::';
	server = mod_restify.createServer({ serverName: 'Kang' });
	server.get(new RegExp(args['uri_base'] + '/.*'),
	    knRestifyHandler(args));
	server.listen(port, host, function () { callback(null, server); });
}
1135307
function start(callback) {
    var dbDeferred = Q.defer();
    config = defaultConfig;

    if (typeof gmeConfig.rest.components[CONFIG_ID] === 'object' &&
        gmeConfig.rest.components[CONFIG_ID].options) {

        config = gmeConfig.rest.components[CONFIG_ID].options;
    }

    mongodb.MongoClient.connect(config.mongo.uri, config.mongo.options, function (err, db) {
        if (err) {
            dbDeferred.reject(err);
        } else {
            dbConn = db;
            dbDeferred.resolve();
        }
    });

    return dbDeferred.promise.nodeify(callback);
}
762111
function RPCify (obj, opts) {
  if (!obj) return null
  if (!(this instanceof RPCify)) return new RPCify(obj, opts)
  opts = opts || {}

  var defaults = {
    skipPrivate: true,
    include: null,
    exclude: [],
    override: {},
    factory: null,
    name: null,
    access: function () { return true }
  }

  if (obj.__hyperpc) {
    this.opts = Object.assign(defaults, obj.__hyperpc, opts)
  } else if (obj.prototype && obj.prototype.__hyperpc) {
    this.opts = Object.assign(defaults, obj.prototype.__hyperpc, opts)
  } else if (!obj.prototype && Object.getPrototypeOf(obj) && Object.getPrototypeOf(obj).__hyperpc) {
    this.opts = Object.assign(defaults, Object.getPrototypeOf(obj).__hyperpc, opts)
  } else {
    this.opts = Object.assign(defaults, opts)
  }

  this.access = this.opts.access
  this.override = this.opts.override
  this.cache = {}

  if (obj.prototype) {
    // 1. Class (prototype)

    if (opts.factory) this.factory = opts.factory
    else this.factory = makeDefaultFactory(obj)

    this.instance = null
    this.name = obj.name
    this.funcs = getAllFuncs(obj.prototype)
  } else {
    // 2. Object instance

    this.factory = null
    this.instance = obj
    this.name = Object.getPrototypeOf(obj).name
    this.funcs = getAllFuncs(obj)
  }

  var out = ['constructor']
  if (this.opts.exclude) out = out.concat(this.opts.exclude)

  this.filteredFuncs = this.funcs.filter(f => {
    if (this.opts.include && this.opts.include.indexOf(f) === -1) return false
    if (out.indexOf(f) !== -1) return false
    if (this.opts.skipPrivate && f.substr(0, 1) === '_') return false
    return true
  })
}
1141023
async function connectToServer(client, config) {
  return new Promise((resolve, reject) => {
    client
      .on('ready', error => (error ? reject(error) : resolve(client)))
      .on('error', error => reject(error))
      .connect(config);
  });
}
292094
function(callback) {

  log('Connecting...');
  MongoClient.connect(dbUrl, dbOptions, function(err, dbConn) {
    
    if(err) {
      log('Cannot connect: ' + err);
      callback(err);
      return;
    } 
    
    log('Connected!');
    isConnected = true;
    db = dbConn;

    // http://stackoverflow.com/a/18715857/446681
    db.on('close', function() {
      log('Connection was closed!!!');
      isConnected = false;
    });

    log('Executing...');
    callback(null, db);
  
  });

}
1340460
function setupConnection( options ) {
  var db

  // force this connect option to exist as true
  // http://mongoosejs.com/docs/connections.html#use-mongo-client
  if ( !options.connect.useMongoClient ) {
    options.connect.useMongoClient = true
  }

  // http://mongoosejs.com/docs/promises.html#plugging-in-your-own-promises-library
  mongoose.Promise = global.Promise
  mongoose.set( 'debug', options.debug === true )

  db = mongoose.connection

  if ( options.debug === true ) {
    db.on( 'connected', eventLogger( 'connected', db ) )
    db.on( 'connecting', eventLogger( 'connecting', db ) )
    db.on( 'disconnected', eventLogger( 'disconnected', db ) )
    db.on( 'open', eventLogger( 'open', db ) )
    db.on( 'reconnected', eventLogger( 'reconnected', db ) )
  }

  db.on( 'error', eventLogger( 'error', db ) )
  db.on( 'error', attachErrorToDb( db ) )

  db.uri = getUri( options.uri )

  process.on( 'SIGINT',
    function () {
      mongoose.connection.close(
        function () {
          console.log( 'mongoose default connection disconnected through app termination' )
          process.exit( 0 )
        }
      );
    }
  )

  return db
}
287985
function connect(dbUri, debugFlag, mongos) {
    var deferred = Q.defer();
    var opts = {
        server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
        replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } }
    };

    if (mongos) {
        opts.mongos = true;
    }

    mongoose.set('debug', debugFlag);

    // make sure we disconnect any other existing connections
    mongoose.disconnect(function () {
        mongoose.connect(dbUri, opts, function (err)  {
            err ? deferred.reject(err) : deferred.resolve();
        });
    });

    return deferred.promise;
}
511516
function(opts, callback) {
  if (callback === undefined) {
    throw new Error('callback undefined in $fh.cache. See documentation of $fh.cache for proper usage');
  }

  if (opts.act === undefined) {
    return callback('No cache actions defined!');
  }

  var fullKey = appname + opts.key;

  var client = redisClient();
  if (opts.act === 'save') {
    client.on("connect", function() {
      if (redisPassword) {
        client.auth(redisPassword, function(err) {
          if (err) {
            callback(err);
          }
        });
      }
    });
    client.on("error", function(err) {
      console.error("fh.cache error: %s ", err);
      return callback(err);
    });
    client.on("ready", function(err) {
      if (err) {
        return callback(err);
      }
      if (opts.expire !== undefined) {
        client.setex(fullKey, opts.expire, opts.value, function(err, reply) {
          client.quit();
          return callback(err, reply);
        });
      } else {
        client.set(fullKey, opts.value, function(err, reply) {
          client.quit();
          return callback(err, reply);
        });
      }
    });
  } else if (opts.act === 'load') {
    client.on("connect", function() {
      if (redisPassword) {
        client.auth(redisPassword, function(err) {
          if (err) {
            callback(err);
          }
        });
      }
    });
    client.on("error", function(err) {
      console.error("fh.cache error: %s", err);
      callback(err);
      client.end();
    });
    client.on("ready", function(err) {
      if (err) {
        return callback(err);
      }
      client.get(fullKey, function(err, reply) {
        client.quit();
        return callback(err, reply);
      });
    });
  } else if (opts.act === 'remove') {
    client.on("connect", function() {
      if (redisPassword) {
        client.auth(redisPassword, function(err) {
          if (err) {
            callback(err);
          }
        });
      }
    });
    client.on("error", function(err) {
      console.error("fh.cache error: %s", err);
      return callback(err);
    });
    client.on("ready", function(err) {
      if (err) {
        return callback(err);
      }
      client.del(fullKey, function(err, reply) {
        client.quit();
        return callback(err, reply);
      });
    });
  } else {
    return callback("Unknown cache action: " + opts.act);
  }
}
867769
def initialize_socket(uri, opts = {})
      return if opts[:socket]

      @socket = TCPSocket.new(uri.host, uri.port)
      opts.merge!({:socket => @socket})
      @intentional_termination = false
    end
283405
function constructMongoLink(dbName, prefix, servers, params, credentials) {
        if (dbName && Array.isArray(servers)) {
            var url = "mongodb://";
            if (credentials && Object.hasOwnProperty.call(credentials, 'username') && credentials.hasOwnProperty.call(credentials, 'password')) {
                url = url.concat(credentials.username, ':', credentials.password, '@');
            }

            servers.forEach(function (element, index, array) {
                url = url.concat(element.host, ':', element.port, (index === array.length - 1 ? '' : ','));
            });

            url = url.concat('/');
            if (prefix) url = url.concat(prefix);
            url = url.concat(dbName);

            if (params && 'object' === typeof params && Object.keys(params).length) {
                url = url.concat('?');
                for (var i = 0; i < Object.keys(params).length; i++) {
                    url = url.concat(Object.keys(params)[i], '=', params[Object.keys(params)[i]], i === Object.keys(params).length - 1 ? '' : "&");
                }
            }
            return url;
        }
        return null;
    }
719379
function(callback) {
        var scarlet = new Scarlet(Math.min(opts.n, 100));

        function connect(taskObject) {
            var client = taskObject.task.client;
            var i = taskObject.task.idx;

            client.connect(function() {
                scarlet.taskDone(taskObject);
            });

            client.on("error", function(err) {
                console.log(err + ": Client " + i);
            });
        }

        console.time("Connect");

        // if mode is `clients`, we create (opts.complicating) clients,
        // otherwise we create only one.
        var max = opts["complicating-mode"] === "clients" ? opts.complicating : 1;
        for(var i = 0; i < max; i++) {
            var client = illyria2.createClient("127.0.0.1", SERVER_PORT, {
                runTimeout: 10000,
                retryInterval: 1000,
                reconnect: true
            });

            scarlet.push({ idx: i, client: client }, connect);

            clients.push(client);
        }

        scarlet.afterFinish(max, function() {
            console.timeEnd("Connect");
            callback();
        }, false);
    }
708067
function(opts) {
      opts = opts || {};
      var path = opts.path || this.path,
          callback = opts.callback,
          method = opts.method || this.method,
          ws = getWebsocketPlugin(),
          transports = app.config.transports,
          self = this,
          i = 0,
          error,
          response;

      if (ws) {
        if (transports && transports.length > 0) {
          async.whilst(
            function () {
              return (i < transports.length);
            },
            function (done) {
              self.doConnect(transports[i], method, path, function (err, res) {
                error = err;
                response = res;
                if (!err && res) {
                  i = transports.length;
                } else {
                  i++;
                  if (i < transports.length) {
                    delete self.request;
                  }
                }
                done();
              });
            },
            function (err) {
              callback(err || error, response);
            }
          );
        } else {
          error = 'no transport available';
          log.error('%s %s', app.name, error);
          callback(error);
        }
      } else {
        this.doConnect('http', method, path, callback);
      }
      return this;
    }
2863
function Connection(uri) {
    this.channels = {};
    let version = require('../package.json').version;
    let opts = {
        query: 'instanceId=' + 'js_cli_' + version,
        'sync disconnect on unload': true,
        path: '/syncsocket'
    };
    this.socket = io.connect(uri, opts);
    this.bindEvents();
}
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
}