Socket
Socket
Sign inDemoInstall

mongodb

Package Overview
Dependencies
Maintainers
1
Versions
551
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongodb - npm Package Compare versions

Comparing version 0.9.7-0 to 0.9.7-1

lib/mongodb/connection/strategies/ping_strategy.js

17

docs/database.md

@@ -23,9 +23,8 @@ Database

* `poolSize` - specify the number of connections in the pool `default:1`
* `retryMiliSeconds` - specify the number of milliseconds between connection attempts `default:5000`
* `numberOfRetries` - specify the number of retries for connection attempts `default:3`
* `reaperInterval` - specify the number of milliseconds between each reaper attempt `default:1000`
* `reaperTimeout` - specify the number of milliseconds for timing out callbacks that don't return `default:30000`
* `raw` - driver expects Buffer raw bson document, `default:false`
* `socketOptions` - a collection of pr socket settings
* `timeout` = set seconds before connection times out `default:0`
* `noDelay` = Disables the Nagle algorithm `default:true`
* `keepAlive` = Set if keepAlive is used `default:0`, which means no keepAlive, set higher than 0 for keepAlive
* `encoding` = ['ascii', 'utf8', or 'base64'] `default:null`
## DB options

@@ -39,3 +38,9 @@

* `forceServerObjectId` - generation of objectid is delegated to the mongodb server instead of the driver. default is false
* `retryMiliSeconds` - specify the number of milliseconds between connection attempts `default:5000`
* `numberOfRetries` - specify the number of retries for connection attempts `default:3`
* `reaperInterval` - specify the number of milliseconds between each reaper attempt `default:1000`
* `reaperTimeout` - specify the number of milliseconds for timing out callbacks that don't return `default:30000`
* `raw` - driver expects Buffer raw bson document, `default:false`
## Opening a database

@@ -42,0 +47,0 @@

@@ -41,1 +41,7 @@ Replicasets

* `read_secondary` set's the driver to read from secondary servers (slaves) instead of only from the primary(master) server.
* `socketOptions` - a collection of pr socket settings
* `timeout` = set seconds before connection times out `default:0`
* `noDelay` = Disables the Nagle algorithm `default:true`
* `keepAlive` = Set if keepAlive is used `default:0`, which means no keepAlive, set higher than 0 for keepAlive
* `encoding` = ['ascii', 'utf8', or 'base64'] `default:null`
GLOBAL.DEBUG = true;
sys = require("sys");
debug = require('util').debug,
inspect = require('util').inspect,
test = require("assert");

@@ -15,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -29,3 +26,3 @@ db.open(function(err, db) {

admin.profilingLevel(function(err, profilingLevel) {
sys.puts("Profiling level: " + profilingLevel);
console.log("Profiling level: " + profilingLevel);
});

@@ -35,3 +32,3 @@

admin.setProfilingLevel('all', function(err, level) {
sys.puts("Profiling level: " + level);
console.log("Profiling level: " + level);

@@ -45,3 +42,3 @@ // Read records, creating a profiling event

admin.profilingInfo(function(err, info) {
sys.puts(sys.inspect(info));
console.dir(info);

@@ -51,3 +48,3 @@ // Validate returns a hash if all is well or return an error hash if there is a

admin.validateCollection(collection.collectionName, function(err, result) {
sys.puts(result.result);
console.dir(result);
db.close();

@@ -54,0 +51,0 @@ });

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -15,11 +14,11 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-blog', new Server(host, port, {}), {native_parser:true});
db.open(function(err, db) {
db.dropDatabase(function(err, result) {
sys.puts("===================================================================================");
sys.puts(">> Adding Authors");
console.log("===================================================================================");
console.log(">> Adding Authors");
db.collection('authors', function(err, collection) {
collection.createIndex(["meta", ['_id', 1], ['name', 1], ['age', 1]], function(err, indexName) {
sys.puts("===================================================================================");
console.log("===================================================================================");
var authors = {};

@@ -31,3 +30,3 @@

docs.forEach(function(doc) {
sys.puts(sys.inspect(doc));
console.dir(doc);
authors[doc.name] = doc;

@@ -37,13 +36,13 @@ });

sys.puts("===================================================================================");
sys.puts(">> Authors ordered by age ascending");
sys.puts("===================================================================================");
console.log("===================================================================================");
console.log(">> Authors ordered by age ascending");
console.log("===================================================================================");
collection.find({}, {'sort':[['age', 1]]}, function(err, cursor) {
cursor.each(function(err, author) {
if(author != null) {
sys.puts("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]");
console.log("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]");
} else {
sys.puts("===================================================================================");
sys.puts(">> Adding users");
sys.puts("===================================================================================");
console.log("===================================================================================");
console.log(">> Adding users");
console.log("===================================================================================");
db.collection('users', function(err, userCollection) {

@@ -55,3 +54,3 @@ var users = {};

docs.forEach(function(doc) {
sys.puts(sys.inspect(doc));
console.dir(doc);
users[doc.login] = doc;

@@ -61,13 +60,13 @@ });

sys.puts("===================================================================================");
sys.puts(">> Users ordered by login ascending");
sys.puts("===================================================================================");
console.log("===================================================================================");
console.log(">> Users ordered by login ascending");
console.log("===================================================================================");
userCollection.find({}, {'sort':[['login', 1]]}, function(err, cursor) {
cursor.each(function(err, user) {
if(user != null) {
sys.puts("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]");
console.log("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]");
} else {
sys.puts("===================================================================================");
sys.puts(">> Adding articles");
sys.puts("===================================================================================");
console.log("===================================================================================");
console.log(">> Adding articles");
console.log("===================================================================================");
db.collection('articles', function(err, articlesCollection) {

@@ -85,14 +84,14 @@ articlesCollection.insert([

docs.forEach(function(doc) {
sys.puts(sys.inspect(doc));
console.dir(doc);
});
})
sys.puts("===================================================================================");
sys.puts(">> Articles ordered by title ascending");
sys.puts("===================================================================================");
console.log("===================================================================================");
console.log(">> Articles ordered by title ascending");
console.log("===================================================================================");
articlesCollection.find({}, {'sort':[['title', 1]]}, function(err, cursor) {
cursor.each(function(err, article) {
if(article != null) {
sys.puts("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]");
sys.puts(">> Closing connection");
console.log("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]");
console.log(">> Closing connection");
db.close();

@@ -99,0 +98,0 @@ }

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -13,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -27,3 +26,3 @@ db.open(function(err, db) {

cursor.toArray(function(err, items) {
sys.puts("The number of records: " + items.length);
console.log("The number of records: " + items.length);
db.close();

@@ -30,0 +29,0 @@ })

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -13,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -32,3 +31,3 @@ db.open(function(err, db) {

cursor.each(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
if(item != null) console.dir(item);
});

@@ -40,3 +39,3 @@ });

cursor.toArray(function(err, items) {
sys.puts("count: " + items.length);
console.log("count: " + items.length);
});

@@ -50,3 +49,3 @@ });

cursor.each(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
if(item != null) console.dir(item);
});

@@ -59,3 +58,3 @@ });

cursor.nextObject(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
if(item != null) console.dir(item);
});

@@ -70,3 +69,4 @@ });

cursor.nextObject(function(err, item) {
sys.puts("nextObject returned: " + sys.inspect(item));
console.log("nextObject returned: ");
console.dir(item);
db.close();

@@ -73,0 +73,0 @@ });

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -14,3 +13,3 @@

sys.puts(">> Connecting to " + host + ":" + port);
console.log(">> Connecting to " + host + ":" + port);
var db1 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -62,7 +61,7 @@ db1.open(function(err, db) {

GridStore.exist(db, 'foobar2', function(err, result) {
sys.puts("File 'foobar2' exists: " + result);
console.log("File 'foobar2' exists: " + result);
});
GridStore.exist(db, 'does-not-exist', function(err, result) {
sys.puts("File 'does-not-exist' exists: " + result);
console.log("File 'does-not-exist' exists: " + result);
});

@@ -72,3 +71,3 @@

GridStore.read(db, 'foobar2', 6, 7, function(err, data) {
sys.puts(data);
console.log(data);
});

@@ -83,3 +82,3 @@

gridStore.tell(function(tell) {
sys.puts("tell: " + tell); // Should be 5
console.log("tell: " + tell); // Should be 5
});

@@ -94,3 +93,3 @@ gridStore.seek(4, function(err, gridStore){});

GridStore.exist(db, 'foobar2', function(err, result) {
sys.puts("File 'foobar2' exists: " + result);
console.log("File 'foobar2' exists: " + result);
db.close();

@@ -115,6 +114,6 @@ });

gridStore.open(function(err, gridStore) {
sys.puts("contentType: " + gridStore.contentType);
sys.puts("uploadDate: " + gridStore.uploadDate);
sys.puts("chunkSize: " + gridStore.chunkSize);
sys.puts("metadata: " + gridStore.metadata);
console.log("contentType: " + gridStore.contentType);
console.log("uploadDate: " + gridStore.uploadDate);
console.log("chunkSize: " + gridStore.chunkSize);
console.log("metadata: " + gridStore.metadata);
});

@@ -131,6 +130,6 @@

gridStore.open(function(err, gridStore) {
sys.puts("contentType: " + gridStore.contentType);
sys.puts("uploadDate: " + gridStore.uploadDate);
sys.puts("chunkSize: " + gridStore.chunkSize);
sys.puts("metadata: " + gridStore.metadata);
console.log("contentType: " + gridStore.contentType);
console.log("uploadDate: " + gridStore.uploadDate);
console.log("chunkSize: " + gridStore.chunkSize);
console.log("metadata: " + gridStore.metadata);
db.close();

@@ -158,5 +157,5 @@ });

GridStore.read(db, filename, function(err, data) {
sys.puts(data);
console.log(data);
if(callback != null) callback();
});
}
GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -14,13 +13,15 @@

sys.puts(">> Connecting to " + host + ":" + port);
console.log(">> Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
db.open(function(err, db) {
sys.puts(">> Dropping collection test");
console.log(">> Dropping collection test");
db.dropCollection('test', function(err, result) {
sys.puts("dropped: " + sys.inspect(result));
console.log("dropped: ");
console.dir(result);
});
sys.puts(">> Creating collection test");
console.log(">> Creating collection test");
db.collection('test', function(err, collection) {
sys.puts("created: " + sys.inspect(collection));
console.log("created: ");
console.dir(collection);

@@ -30,29 +31,32 @@ var objectCount = 100;

var messages = ["hola", "hello", "aloha", "ciao"];
sys.puts(">> Generate test data");
console.log(">> Generate test data");
for(var i = 0; i < objectCount; i++) {
objects.push({'number':i, 'rndm':((5*Math.random()) + 1), 'msg':messages[parseInt(4*Math.random())]})
}
sys.puts("generated");
console.log("generated");
sys.puts(">> Inserting data (" + objects.length + ")");
console.log(">> Inserting data (" + objects.length + ")");
collection.insert(objects);
sys.puts("inserted");
console.log("inserted");
sys.puts(">> Creating index")
console.log(">> Creating index")
collection.createIndex([['all'], ['_id', 1], ['number', 1], ['rndm', 1], ['msg', 1]], function(err, indexName) {
sys.puts("created index: " + indexName);
console.log("created index: " + indexName);
sys.puts(">> Gathering index information");
console.log(">> Gathering index information");
collection.indexInformation(function(err, doc) {
sys.puts("indexInformation: " + sys.inspect(doc));
console.log("indexInformation: ");
console.dir(doc);
sys.puts(">> Dropping index");
console.log(">> Dropping index");
collection.dropIndex('all_1__id_1_number_1_rndm_1_msg_1', function(err, result) {
sys.puts("dropped: " + sys.inspect(result));
console.log("dropped: ");
console.dir(result);
sys.puts(">> Gathering index information");
console.log(">> Gathering index information");
collection.indexInformation(function(err, doc) {
sys.puts("indexInformation: " + sys.inspect(doc));
sys.puts(">> Closing connection");
console.log("indexInformation: ");
console.dir(doc);
console.log(">> Closing connection");
db.close();

@@ -59,0 +63,0 @@ });

@@ -13,3 +13,3 @@ GLOBAL.DEBUG = true;

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -30,3 +30,3 @@ db.open(function(err, db) {

names.forEach(function(name) {
sys.puts(sys.inspect(name));
console.dir(name);
});

@@ -39,3 +39,3 @@ });

items.forEach(function(item) {
sys.puts(sys.inspect(item));
console.dir(item);
});

@@ -48,3 +48,3 @@ });

db.indexInformation('test', function(err, doc) {
sys.puts(sys.inspect(doc));
console.dir(doc);
collection.drop(function(err, result) {

@@ -51,0 +51,0 @@ db.close();

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -20,4 +19,4 @@

//connect without dbName for querying not only "local" db
sys.puts("Connecting to " + host + ":" + port);
this.db = new Db('', new Server(host, port, {}), {});
console.log("Connecting to " + host + ":" + port);
this.db = new Db('testing', new Server(host, port, {}), {});
}

@@ -32,3 +31,3 @@

if (err) {
sys.puts('> MongoSlave error' + err);
console.log('> MongoSlave error' + err);
process.exit(1);

@@ -39,3 +38,3 @@ }

if (! collection) {
sys.puts('> MongoSlave - local.oplog.$main not found');
console.log('> MongoSlave - local.oplog.$main not found');
self.stop();

@@ -53,7 +52,7 @@ return false;

if (items.length) {
sys.puts('> MongoSlave started');
console.log('> MongoSlave started');
self.running = true;
self._runSlave(collection, items[0]['ts']);
} else if (err) {
sys.puts(err);
console.log(err);
self.stop();

@@ -70,3 +69,3 @@ }

if (!this.running) return;
sys.puts('> MongoSlave stopped');
console.log('> MongoSlave stopped');
this.running = false;

@@ -121,5 +120,5 @@ this.db.close();

watcher.onObject(function(obj) {
sys.puts(sys.inspect(obj));
console.dir(obj);
});
watcher.start();
GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -13,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);

@@ -27,3 +26,3 @@ var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

collection.count(function(err, count) {
sys.puts("There are " + count + " records.");
console.log("There are " + count + " records.");
});

@@ -36,5 +35,6 @@

// that provides a 12 byte value
sys.puts("Printing docs from Cursor Each")
console.log("Printing docs from Cursor Each")
cursor.each(function(err, doc) {
if(doc != null) sys.puts("Doc from Each " + sys.inspect(doc));
if(doc != null) console.log("Doc from Each ");
console.dir(doc);
})

@@ -45,5 +45,6 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Printing docs from Array")
console.log("Printing docs from Array")
docs.forEach(function(doc) {
sys.puts("Doc from Array " + sys.inspect(doc));
console.log("Doc from Array ");
console.dir(doc);
});

@@ -58,3 +59,3 @@ });

cursor.nextObject(function(err, doc) {
sys.puts("Returned #1 documents");
console.log("Returned #1 documents");
});

@@ -67,3 +68,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
})

@@ -75,3 +76,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -82,3 +83,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -90,3 +91,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -98,3 +99,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -106,4 +107,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
})

@@ -122,4 +123,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
})

@@ -130,4 +131,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
db.close();

@@ -134,0 +135,0 @@ })

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -25,5 +24,5 @@

var replStat = new ReplSetServers(servers);
sys.puts("Connecting to " + host + ":" + port);
sys.puts("Connecting to " + host1 + ":" + port1);
sys.puts("Connecting to " + host2 + ":" + port2);
console.log("Connecting to " + host + ":" + port);
console.log("Connecting to " + host1 + ":" + port1);
console.log("Connecting to " + host2 + ":" + port2);
var db = new Db('node-mongo-examples', replStat, {native_parser:true});

@@ -40,3 +39,3 @@ db.open(function(err, db) {

collection.count(function(err, count) {
sys.puts("There are " + count + " records.");
console.log("There are " + count + " records.");
});

@@ -49,5 +48,6 @@

// that provides a 12 byte value
sys.puts("Printing docs from Cursor Each")
console.log("Printing docs from Cursor Each")
cursor.each(function(err, doc) {
if(doc != null) sys.puts("Doc from Each " + sys.inspect(doc));
if(doc != null) console.log("Doc from Each ");
console.dir(doc);
})

@@ -58,5 +58,6 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Printing docs from Array")
console.log("Printing docs from Array")
docs.forEach(function(doc) {
sys.puts("Doc from Array " + sys.inspect(doc));
console.log("Doc from Array ");
console.dir(doc);
});

@@ -71,3 +72,3 @@ });

cursor.nextObject(function(err, doc) {
sys.puts("Returned #1 documents");
console.log("Returned #1 documents");
});

@@ -80,3 +81,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
})

@@ -88,3 +89,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -95,3 +96,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -103,3 +104,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -111,3 +112,3 @@ });

cursor.toArray(function(err, docs) {
sys.puts("Returned #" + docs.length + " documents");
console.log("Returned #" + docs.length + " documents");
});

@@ -119,4 +120,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
})

@@ -135,4 +136,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
})

@@ -143,4 +144,4 @@ });

cursor.explain(function(err, doc) {
sys.puts("-------------------------- Explanation");
sys.puts(sys.inspect(doc));
console.log("-------------------------- Explanation");
console.dir(doc);
db.close();

@@ -147,0 +148,0 @@ })

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -21,5 +20,5 @@

sys.puts("Connecting to " + host + ":" + port);
sys.puts("Connecting to " + host + ":" + port1);
sys.puts("Connecting to " + host + ":" + port2);
console.log("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port1);
console.log("Connecting to " + host + ":" + port2);

@@ -36,5 +35,3 @@ var server = new Server(host, port, {});

var db = new Db('mongo-example', replStat, {native_parser:true});
var db = new Db('mongo-example', replStat, {native_parser:true});
db.open(function(err, db) {

@@ -51,3 +48,3 @@

collection.count(function(err, count) {
sys.puts("There are " + count + " records in the test collection. Here they are:");
console.log("There are " + count + " records in the test collection. Here they are:");

@@ -57,4 +54,4 @@ collection.find(function(err, cursor) {

if(item != null) {
sys.puts(sys.inspect(item));
sys.puts("created at " + new Date(item._id.generationTime) + "\n")
console.dir(item);
console.log("created at " + new Date(item._id.generationTime) + "\n")
}

@@ -61,0 +58,0 @@ // Null signifies end of iterator

GLOBAL.DEBUG = true;
sys = require("sys"),
debug = require('util').debug,
inspect = require('util').inspect,
test = require("assert");

@@ -15,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -29,3 +26,3 @@ db.open(function(err, db) {

collection.count(function(err, count) {
sys.puts("There are " + count + " records in the test collection. Here they are:");
console.log("There are " + count + " records in the test collection. Here they are:");

@@ -35,4 +32,4 @@ collection.find(function(err, cursor) {

if(item != null) {
sys.puts(sys.inspect(item));
sys.puts("created at " + new Date(item._id.generationTime) + "\n")
console.dir(item);
console.log("created at " + new Date(item._id.generationTime) + "\n")
}

@@ -39,0 +36,0 @@ // Null signifies end of iterator

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -13,3 +12,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});

@@ -24,3 +23,3 @@ db.open(function(err, db) {

if(err instanceof Error) {
sys.puts("expected error: " + err.message);
console.log("expected error: " + err.message);
}

@@ -31,3 +30,3 @@

if(err instanceof Error) {
sys.puts("expected error: " + err.message);
console.log("expected error: " + err.message);
}

@@ -34,0 +33,0 @@

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -14,3 +13,3 @@

sys.puts("Connecting to " + host + ":" + port);
console.log("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {});

@@ -40,3 +39,3 @@ db.open(function(err, db) {

collection.findOne(function(err, document) {
sys.puts(sys.inspect(document));
console.dir(document);
collection.remove(function(err, collection) {

@@ -43,0 +42,0 @@ db.close();

GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert");

@@ -9,3 +8,3 @@

sys.puts('Connecting to ' + Db.DEFAULT_URL);
console.log('Connecting to ' + Db.DEFAULT_URL);
connect(Db.DEFAULT_URL, function(err, db) {

@@ -12,0 +11,0 @@ db.dropDatabase(function(err, result) {

@@ -292,3 +292,3 @@ var sys = require('util'),

var object2 = BSON.deserialize(simple_string_serialized);
assert.deepEqual(object, object2);
assert.equal(object.doc.id, object2.doc.id)

@@ -327,3 +327,5 @@ // JS Object

var doc2 = BSON.deserialize(new Buffer(simple_string_serialized_2));
assert.deepEqual(doc2, doc1)
assert.equal(doc._id.id, doc1._id.id)
assert.equal(doc._id.id, doc2._id.id)
assert.equal(doc1._id.id, doc2._id.id)

@@ -330,0 +332,0 @@ var doc = {

@@ -44,2 +44,17 @@ var Collection = require('./collection').Collection,

Admin.prototype.ping = function(options, callback) {
// Unpack calls
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
options = args.length ? args.shift() : {};
// Set self
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.executeDbCommand({ping:1}, options, function(err, result) {
self.db.databaseName = databaseName;
return callback(err, result);
})
}
Admin.prototype.authenticate = function(username, password, callback) {

@@ -49,3 +64,3 @@ var self = this;

this.db.databaseName = 'admin';
this.db.authenticate(username, password, function(err, result) {
this.db.authenticate(username, password, function(err, result) {
self.db.databaseName = databaseName;

@@ -52,0 +67,0 @@ return callback(err, result);

@@ -177,3 +177,3 @@

// Factor out the encode so it can be shared by add_header and push_int32
BinaryParser.encode_int32 = function encode_int32 (number) {
BinaryParser.encode_int32 = function encode_int32 (number, asArray) {
var a, b, c, d, unsigned;

@@ -188,3 +188,3 @@ unsigned = (number < 0) ? (number + 0x100000000) : number;

d = Math.floor(unsigned);
return chr(a) + chr(b) + chr(c) + chr(d);
return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d);
};

@@ -191,0 +191,0 @@

@@ -27,6 +27,6 @@ /**

// Throw an error if it's not a valid setup
if(id != null && (id.length != 12 && id.length != 24)) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format");
if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format");
// Generate id based on the input
if (null == id) {
this.id = this.generate();
if (null == id || 'number' == typeof id) {
this.id = this.generate(id);
} else if (/^[0-9a-fA-F]{24}$/.test(id)) {

@@ -55,8 +55,17 @@ return ObjectID.createFromHexString(id);

ObjectID.prototype.generate = function() {
var unixTime = parseInt(Date.now()/1000, 10);
var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true);
var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
var pid2Bytes = BinaryParser.fromShort(process.pid);
var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
ObjectID.prototype.generate = function(time) {
if ('number' == typeof time) {
var time4Bytes = BinaryParser.encodeInt(time, 32, true, true);
/* for time-based ObjectID the bytes following the time will be zeroed */
var machine3Bytes = BinaryParser.encodeInt(0, 24, false);
var pid2Bytes = BinaryParser.fromShort(0);
var index3Bytes = BinaryParser.encodeInt(0, 24, false, true);
} else {
var unixTime = parseInt(Date.now()/1000,10);
var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true);
var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
var pid2Bytes = BinaryParser.fromShort(process.pid);
var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
}
return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes;

@@ -131,3 +140,3 @@ };

ObjectID.prototype.__defineGetter__("generationTime", function() {
return BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true) * 1000;
return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true));
});

@@ -134,0 +143,0 @@

@@ -305,3 +305,3 @@ /**

}
// Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection)

@@ -677,2 +677,4 @@ this.db._executeInsertCommand(insertCommand, commandOptions, function (err, error) {

// Ensure selector is not null
selector = selector == null ? {} : selector;
// Validate correctness off the selector

@@ -839,2 +841,4 @@ var object = selector;

// Ensure selector is not null
selector = selector == null ? {} : selector;
// Validate correctness off the selector

@@ -900,28 +904,2 @@ var object = selector;

});
// // callback for backward compatibility
// if (callback) {
// // TODO refactor Cursor args
// callback(null, new Cursor(this.db, this, selector, fields, o.skip, o.limit, o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize, o.slaveOk, o.raw));
// } else {
// return new Cursor(this.db, this, selector, fields, o.skip, o.limit, o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize, o.slaveOk, o.raw);
// }
// var self = this;
// // Get all the arguments
// var args = Array.prototype.slice.call(arguments, 0);
// // Retrieve the callback
// var callback = args.pop();
// try {
// // Call find function with one item
// this.find.apply(this, args).limit(1).toArray(function(err, items) {
// if(err != null) return callback(err instanceof Error ? err : self.db.wrap(new Error(err)), null);
// if(items.length == 1) return callback(null, items[0]);
// callback(null, null);
// });
//
// }catch(err) {
// console.log("----------------------------------- 444444444444444444444444444444444")
// console.dir(err)
// }
};

@@ -928,0 +906,0 @@

@@ -18,12 +18,6 @@ var utils = require('./connection_utils'),

this.socketOptions.port = port;
this.bson = bson;
// PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc)
this.socketOptions.poolSize = poolSize;
this.bson = bson;
// Set host variable or default
utils.setStringParameter(this.socketOptions, 'host', '127.0.0.1');
// Set port variable or default
utils.setIntegerParameter(this.socketOptions, 'port', 27017);
// Set poolSize or default
utils.setIntegerParameter(this.socketOptions, 'poolSize', 1);
// Set default settings for the socket options

@@ -53,3 +47,3 @@ utils.setIntegerParameter(this.socketOptions, 'timeout', 0);

// The pool state
this._poolState = 'not connected';
this._poolState = 'disconnected';
}

@@ -108,5 +102,5 @@

// errors
if(Object.keys(self.connectionsWithErrors).length > 0 && fireError) {
// Set pool type to not connected
self._poolState = 'not connected';
if(Object.keys(self.connectionsWithErrors).length > 0 && Object.keys(self.openConnections).length == 0 && fireError) {
// Set pool type to disconnected
self._poolState = 'disconnected';
// Emit error

@@ -149,4 +143,4 @@ self.emit("error", err, connection);

connection.on("parseError", function(err) {
// Set pool type to not connected
self._poolState = 'not connected';
// Set pool type to disconnected
self._poolState = 'disconnected';
// Only close the connection if it's still connected

@@ -177,4 +171,4 @@ if(self.isConnected()) self.stop();

ConnectionPool.prototype.stop = function() {
// Set not connected
this._poolState = 'not connected';
// Set disconnected
this._poolState = 'disconnected';

@@ -225,7 +219,15 @@ // Get all open connections

var keys = Object.keys(this.openConnections);
return this.openConnections[(keys[(this.currentConnectionIndex++ % keys.length)])]
return this.openConnections[(keys[(this.currentConnectionIndex++ % (keys.length))])]
}
ConnectionPool.prototype.getAllConnections = function() {
return this.openConnections;
// Get all keys
var allKeys = Object.keys(this.openConnections);
var allConnections = new Array(allKeys.length);
// Collect all connections
for(var i = 0; i < allKeys.length; i++) {
allConnections[i] = this.openConnections[allKeys[i]];
}
// Return list of connections
return allConnections;
}

@@ -232,0 +234,0 @@

@@ -46,3 +46,16 @@ var utils = require('./connection_utils'),

// Create new connection instance
this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
// this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
this.connection = new net.Socket();
// Set options on the socket
this.connection.setTimeout(this.socketOptions.timeout);
this.connection.setNoDelay(this.socketOptions.noDelay);
// Set keep alive if defined
if(this.socketOptions.keepAlive > 0) {
this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
} else {
this.connection.setKeepAlive(false);
}
// Add handlers
this.connection.on("error", errorHandler(this));
// Add all handlers to the socket to manage it

@@ -54,4 +67,5 @@ this.connection.on("connect", connectHandler(this));

this.connection.on("drain", drainHandler(this));
this.connection.on("error", errorHandler(this));
this.connection.on("close", closeHandler(this));
// Start socket
this.connection.connect(this.socketOptions.port, this.socketOptions.host);
}

@@ -61,3 +75,3 @@

Connection.prototype.isConnected = function() {
return this.connected;
return this.connected && !this.connection.destroyed && this.connection.writable && this.connection.readable;
}

@@ -85,4 +99,6 @@

resetHandlers(this, true);
// Add a dummy error listener to catch any weird last moment errors (and ignore them)
this.connection.on("error", function() {})
// destroy connection
this.connection.destroy();
this.connection.end();
}

@@ -110,12 +126,3 @@

var connectHandler = function(self) {
return function() {
// Set options on the socket
// this.setEncoding(self.socketOptions.encoding);
this.setTimeout(self.socketOptions.timeout);
this.setNoDelay(self.socketOptions.noDelay);
// Set keep alive if defined
if(self.socketOptions.keepAlive > 0) {
this.setKeepAlive(true, self.socketOptions.keepAlive);
}
return function() {
// Set connected

@@ -206,2 +213,11 @@ self.connected = true;

var sizeOfMessage = binaryutils.decodeUInt32(data, 0);
// If we have a negative sizeOfMessage emit error and return
if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonSize) {
// We got a parse Error fire it off then keep going
self.emit("parseError", {err:"socketHandler", trace:'', bin:self.buffer, parseState:{
sizeOfMessage:sizeOfMessage,
bytesRead:self.bytesRead,
stubBuffer:self.stubBuffer}});
return;
}

@@ -257,13 +273,20 @@ // Ensure that the size of message is larger than 0 and less than the max allowed

} else {
self.emit("message", data.slice(0, sizeOfMessage));
// Reset state of buffer
self.buffer = null;
self.sizeOfMessage = 0;
self.bytesRead = 0;
self.stubBuffer = null;
// Copy rest of message
data = data.slice(sizeOfMessage);
try {
self.emit("message", data.slice(0, sizeOfMessage));
// Reset state of buffer
self.buffer = null;
self.sizeOfMessage = 0;
self.bytesRead = 0;
self.stubBuffer = null;
// Copy rest of message
data = data.slice(sizeOfMessage);
} catch (err) {
// We got a parse Error fire it off then keep going
self.emit("parseError", {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
sizeOfMessage:sizeOfMessage,
bytesRead:self.bytesRead,
stubBuffer:self.stubBuffer}});
}
}
}
} else {

@@ -292,5 +315,5 @@ // Create a buffer that contains the space for the non-complete message

var timeoutHandler = function(self) {
var timeoutHandler = function(self) {
return function() {
self.emit("end", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self);
self.emit("error", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self);
}

@@ -304,3 +327,3 @@ }

var errorHandler = function(self) {
var errorHandler = function(self) {
return function(err) {

@@ -307,0 +330,0 @@ // Set connected to false

@@ -8,3 +8,5 @@ var Connection = require('./connection').Connection,

inspect = require('util').inspect,
Server = require('./server').Server;
Server = require('./server').Server,
PingStrategy = require('./strategies/ping_strategy').PingStrategy,
StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy;

@@ -27,3 +29,3 @@ /**

this.readSecondary = this.options["read_secondary"];
this.slaveOk = this.readSecondary;
this.slaveOk = true;
this.closedConnectionCount = 0;

@@ -35,3 +37,25 @@

this._serverState = 'disconnected';
// Read preference
this._readPreference = null;
// Do we record server stats or not
this.recordQueryStats = false;
// Strategy for picking a secondary
this.strategy = this.options['strategy'] == null ? 'ping' : this.options['strategy'];
// Make sure strategy is one of the two allowed
if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical')) throw new Error("Only ping or statistical strategies allowed");
// Let's set up our strategy object for picking secodaries
if(this.strategy == 'ping') {
// Create a new instance
this.strategyInstance = new PingStrategy(this);
} else if(this.strategy == 'statistical') {
// Set strategy as statistical
this.strategyInstance = new StatisticsStrategy(this);
// Add enable query information
this.enableRecordQueryStats(true);
}
// Set default connection pool options
this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
// Ensure all the instances are of type server and auto_reconnect is false

@@ -54,3 +78,3 @@ if(!Array.isArray(servers) || servers.length == 0) {

}
// Auto Reconnect property

@@ -60,7 +84,18 @@ Object.defineProperty(this, "autoReconnect", { enumerable: true

return true;
// if(this.target != null) return this.target.autoReconnect;
// if(this.primary != null) return this.primary.autoReconnect;
}
});
// Get Read Preference method
Object.defineProperty(this, "readPreference", { enumerable: true
, get: function () {
if(this._readPreference == null && this.readSecondary) {
return Server.READ_SECONDARY;
} else if(this._readPreference == null && !this.readSecondary) {
return Server.READ_PRIMARY;
} else {
return this._readPreference;
}
}
});
// Auto Reconnect property

@@ -142,2 +177,13 @@ Object.defineProperty(this, "host", { enumerable: true

// Always ourselves
ReplSetServers.prototype.setReadPreference = function(preference) {
// Set read preference
this._readPreference = preference;
// Ensure slaveOk is correct for secodnaries read preference and tags
if(this._readPreference == Server.READ_SECONDARY
|| (this._readPreference != null && typeof this._readPreference == 'object')) {
this.slaveOk = true;
}
}
ReplSetServers.prototype.setTarget = function(target) {

@@ -148,2 +194,3 @@ this.target = target;

ReplSetServers.prototype.isConnected = function() {
// Return the state of the replicaset server
return this.primary != null && this._state.master != null && this._state.master.isConnected();

@@ -159,3 +206,3 @@ }

// Clean up dead connections
var cleanupConnections = function(connections, addresses) {
var cleanupConnections = ReplSetServers.cleanupConnections = function(connections, addresses, byTags) {
// Ensure we don't have entries in our set with dead connections

@@ -167,4 +214,9 @@ var keys = Object.keys(connections);

if(!server.isConnected()) {
// Remove from connections and addresses
delete connections[keys[i]];
delete addresses[keys[i]];
// Clean up tags if needed
if(server.tags != null && typeof server.tags === 'object') {
cleanupTags(server, byTags);
}
}

@@ -174,2 +226,32 @@ }

var cleanupTags = ReplSetServers._cleanupTags = function(server, byTags) {
var serverTagKeys = Object.keys(server.tags);
// Iterate over all server tags and remove any instances for that tag that matches the current
// server
for(var i = 0; i < serverTagKeys.length; i++) {
// Fetch the value for the tag key
var value = server.tags[serverTagKeys[i]];
// If we got an instance of the server
if(byTags[serverTagKeys[i]] != null
&& byTags[serverTagKeys[i]][value] != null
&& Array.isArray(byTags[serverTagKeys[i]][value])) {
// List of clean servers
var cleanInstances = [];
// We got instances for the particular tag set
var instances = byTags[serverTagKeys[i]][value];
for(var j = 0; j < instances.length; j++) {
var serverInstance = instances[j];
// If we did not find an instance add it to the clean instances
if((serverInstance.host + ":" + serverInstance.port) !== (server.host + ":" + server.port)) {
cleanInstances.push(serverInstance);
}
}
// Update the byTags list
byTags[serverTagKeys[i]][value] = cleanInstances;
}
}
}
ReplSetServers.prototype.allServerInstances = function() {

@@ -209,4 +291,7 @@ // Close all the servers (concatenate entire list of servers first for ease)

// Keep reference to parent
this.db = parent;
// Set server state to connecting
this._serverState = 'connecting';
// Reference to the instance

@@ -221,23 +306,18 @@ var replSetSelf = this;

// If it's the first call let's reset our state
if(firstCall || replSetSelf._state == null) {
replSetSelf._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'setName':null, 'errorMessages':[]};
} else {
// Clean out dead connections
cleanupConnections(replSetSelf._state.arbiters, replSetSelf._state.addresses);
cleanupConnections(replSetSelf._state.passives, replSetSelf._state.addresses);
cleanupConnections(replSetSelf._state.secondaries, replSetSelf._state.addresses);
// Get master
var master = replSetSelf._state.master;
if(master != null) {
// Remove master from list
replSetSelf._state.addresses[master.host + ":" + master.port];
// Clean up master
replSetSelf._state.master = null;
}
}
// Clean up state
replSetSelf._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'byTags':{}, 'setName':null, 'errorMessages':[]};
// Add a close event handler to ourselves to notify the parent
this.on("close", function() {
parent.emit("close");
// Stop instance
if(replSetSelf.strategyInstance != null) {
// Stop the strategy
replSetSelf.strategyInstance.stop(function() {
// Emit close
parent.emit("close");
})
} else {
// Emit close
parent.emit("close");
}
})

@@ -252,2 +332,4 @@

numberOfServersLeftToInitialize = numberOfServersLeftToInitialize - 1;
// Add enable query information
instanceServer.enableRecordQueryStats(replSetSelf.recordQueryStats);

@@ -266,5 +348,6 @@ if(err == null && result.documents[0].hosts != null) {

var passives = Array.isArray(document.passives) ? document.passives : [];
var tags = document.tags ? document.tags : {};
var primary = document.primary;
var me = document.me;
// Error handler for the servers, this handles unexpected errors coming from

@@ -284,8 +367,37 @@ // a wrong callback or something else

instanceServer.on("error", errorHandler);
// Add tag info
instanceServer.tags = tags;
// For each tag in tags let's add the instance Server to the list for that tag
if(tags != null && typeof tags === 'object') {
var tagKeys = Object.keys(tags);
// For each tag file in the server add it to byTags
for(var i = 0; i < tagKeys.length; i++) {
var value = tags[tagKeys[i]];
// Check if we have a top level tag object
if(replSetSelf._state.byTags[tagKeys[i]] == null) replSetSelf._state.byTags[tagKeys[i]] = {};
// For the value check if we have an array of server instances
if(!Array.isArray(replSetSelf._state.byTags[tagKeys[i]][value])) replSetSelf._state.byTags[tagKeys[i]][value] = [];
// Check that the instance is not already registered there
var valueArray = replSetSelf._state.byTags[tagKeys[i]][value];
var found = false;
// Iterate over all values
for(var j = 0; j < valueArray.length; j++) {
if(valueArray[j].host == instanceServer.host && valueArray[j].port == instanceServer.port) {
found = true;
break;
}
}
// If it was not found push the instance server to the list
if(!found) valueArray.push(instanceServer);
}
}
// Remove from error list
delete replSetSelf._state.errors[instanceServer.host + ":" + instanceServer.port];
delete replSetSelf._state.errors[me];
// Add our server to the list of finished servers
replSetSelf._state.addresses[instanceServer.host + ":" + instanceServer.port] = instanceServer;
replSetSelf._state.addresses[me] = instanceServer;

@@ -331,4 +443,17 @@ // Assign the set name

// Default empty socket options object
var socketOptions = {};
// If a socket option object exists clone it
if(replSetSelf.socketOptions != null) {
var keys = Object.keys(replSetSelf.socketOptions);
for(var i = 0; i < keys.length;i++) socketOptions[keys[i]] = replSetSelf.socketOptions[keys[i]];
}
// Add host information to socket options
socketOptions['host'] = parts[0];
socketOptions['port'] = parseInt(parts[1]);
// Create a new server instance
var newServer = new Server(parts[0], parseInt(parts[1]), {auto_reconnect:false});
var newServer = new Server(parts[0], parseInt(parts[1]), {auto_reconnect:false, 'socketOptions':socketOptions});
// var newServer = new Server(parts[0], parseInt(parts[1]), {auto_reconnect:false});
// Add server to list, ensuring we don't get a cascade of request to the same server

@@ -350,9 +475,28 @@ replSetSelf._state.addresses[candidateServerString] = newServer;

replSetSelf._serverState = 'connected';
// If we don't expect a master let's call back, otherwise we need a master before
// the connection is successful
if(replSetSelf.masterNotNeeded || replSetSelf._state.master != null) {
callback(null, parent);
// If we have a read strategy boot it
if(replSetSelf.strategyInstance != null) {
// Ensure we have a proper replicaset defined
replSetSelf.strategyInstance.replicaset = replSetSelf;
// Start strategy
replSetSelf.strategyInstance.start(function(err) {
callback(null, parent);
})
} else {
callback(null, parent);
}
} else if(replSetSelf.readSecondary == true && Object.keys(replSetSelf._state.secondaries).length > 0) {
callback(null, parent);
// If we have a read strategy boot it
if(replSetSelf.strategyInstance != null) {
// Ensure we have a proper replicaset defined
replSetSelf.strategyInstance.replicaset = replSetSelf;
// Start strategy
replSetSelf.strategyInstance.start(function(err) {
callback(null, parent);
})
} else {
callback(null, parent);
}
} else if(replSetSelf.readSecondary == true && Object.keys(replSetSelf._state.secondaries).length == 0) {

@@ -364,3 +508,4 @@ callback(new Error("no secondary server found"), null);

} else if((numberOfServersLeftToInitialize == 0) && replSetSelf._state.errorMessages.length > 0) {
callback(replSetSelf._state.errorMessages[0], null);
// Callback to signal we are done
callback(replSetSelf._state.errorMessages[0], null);
}

@@ -371,3 +516,3 @@ }

// Ensure we have all registered servers in our set
for(var i = 0; i < serverConnections.length; i++) {
for(var i = 0; i < serverConnections.length; i++) {
replSetSelf._state.addresses[serverConnections[i].host + ':' + serverConnections[i].port] = serverConnections[i];

@@ -377,4 +522,19 @@ }

// Initialize all the connections
for(var i = 0; i < serverConnections.length; i++) {
for(var i = 0; i < serverConnections.length; i++) {
try {
// Default empty socket options object
var socketOptions = {};
// If a socket option object exists clone it
if(this.socketOptions != null && typeof this.socketOptions === 'object') {
var keys = Object.keys(this.socketOptions);
for(var j = 0; j < keys.length;j++) socketOptions[keys[j]] = this.socketOptions[keys[j]];
}
// Add host information to socket options
socketOptions['host'] = serverConnections[i].host;
socketOptions['port'] = serverConnections[i].port;
// Set the socket options
serverConnections[i].socketOptions = socketOptions;
// Connect with the server
serverConnections[i].connect(parent, {'firstCall':true, returnIsMasterResults: true, eventReceiver:serverConnections[i]}, connectionHandler(serverConnections[i]));

@@ -391,2 +551,7 @@ } catch (err) {

}
// Check if we have an error in the inital set of servers and callback with error
if(replSetSelf._state.errorMessages.length > 0 && firstCall) {
callback(replSetSelf._state.errorMessages[0], null);
}
}

@@ -401,7 +566,37 @@

// from it, otherwise just pass the primary connection
if(this.readSecondary == true && Object.keys(this._state.secondaries).length > 0) {
// Pick a random key
var keys = Object.keys(this._state.secondaries);
var key = keys[Math.floor(Math.random() * keys.length)];
return this._state.secondaries[key].checkoutReader();
if((this.readSecondary == true || this._readPreference == Server.READ_SECONDARY) && Object.keys(this._state.secondaries).length > 0) {
// Checkout a secondary server from the passed in set of servers
if(this.strategyInstance != null) {
return this.strategyInstance.checkoutSecondary();
} else {
// Pick a random key
var keys = Object.keys(this._state.secondaries);
var key = keys[Math.floor(Math.random() * keys.length)];
return this._state.secondaries[key].checkoutReader();
}
} else if(this._readPreference != null && typeof this._readPreference === 'object' && Object.keys(this._state.secondaries).length > 0) {
// Get all tag keys (used to try to find a server that is valid)
var keys = Object.keys(this._readPreference);
// final instance server
var instanceServer = null;
// for each key look for an avilable instance
for(var i = 0; i < keys.length; i++) {
// Grab subkey value
var value = this._readPreference[keys[i]];
// Check if we have any servers for the tag, if we do pick a random one
if(this._state.byTags[keys[i]] != null
&& this._state.byTags[keys[i]][value] != null
&& Array.isArray(this._state.byTags[keys[i]][value])
&& this._state.byTags[keys[i]][value].length > 0) {
// Let's grab an available server from the list using a random pick
var serverInstances = this._state.byTags[keys[i]][value];
// Set instance to return
instanceServer = serverInstances[Math.floor(Math.random() * serverInstances.length)];
break;
}
}
// Return the instance of the server
return instanceServer != null ? instanceServer.checkoutReader() : this.checkoutWriter();
} else {

@@ -416,9 +611,5 @@ return this.checkoutWriter();

// Get connection object
var allConnectionsObject = this._state.master.connectionPool.getAllConnections();
// Get the keys for the object
var keys = Object.keys(allConnectionsObject);
// For each connection entry add it to the list of connections
for(var i = 0; i < keys.length; i++) {
allConnections.push(allConnectionsObject[keys[i]]);
}
var allMasterConnections = this._state.master.connectionPool.getAllConnections();
// Add all connections to list
allConnections = allConnections.concat(allMasterConnections);

@@ -428,13 +619,9 @@ // If we have read secondary let's add all secondary servers

// Get all the keys
keys = Object.keys(this._state.secondaries);
var keys = Object.keys(this._state.secondaries);
// For each of the secondaries grab the connections
for(var i = 0; i < keys.length; i++) {
// Get connection object
var secondaryConnectionObject = this._state.secondaries[keys[i]].connectionPool.getAllConnections();
// Get the keys for the object
var secondaryKeys = Object.keys(secondaryConnectionObject);
// For each connection entry add it to the list of connections
for(var i = 0; i < keys.length; i++) {
allConnections.push(secondaryConnectionObject[secondaryKeys[i]]);
}
var secondaryPoolConnections = this._state.secondaries[keys[i]].connectionPool.getAllConnections();
// Add all connections to list
allConnections = allConnections.concat(secondaryPoolConnections);
}

@@ -447,2 +634,20 @@ }

ReplSetServers.prototype.enableRecordQueryStats = function(enable) {
// Set the global enable record query stats
this.recordQueryStats = enable;
// Ensure all existing servers already have the flag set, even if the
// connections are up already or we have not connected yet
if(this._state != null && this._state.addresses != null) {
var keys = Object.keys(this._state.addresses);
// Iterate over all server instances and set the enableRecordQueryStats flag
for(var i = 0; i < keys.length; i++) {
this._state.addresses[keys[i]].enableRecordQueryStats(enable);
}
} else if(Array.isArray(this.servers)) {
for(var i = 0; i < this.servers.length; i++) {
this.servers[i].enableRecordQueryStats(enable);
}
}
}
ReplSetServers.prototype.disconnect = function(callback) {

@@ -452,33 +657,19 @@ this.close(callback);

ReplSetServers.prototype.close = function(callback) { //
ReplSetServers.prototype.close = function(callback) {
var self = this;
// Set server status as disconnected
this._serverState = 'disconnected';
// Close all the servers (concatenate entire list of servers first for ease)
var allServers = self._state.master != null ? [self._state.master] : [];
// Secondary keys
var keys = Object.keys(self._state.secondaries);
// Add all secondaries
for(var i = 0; i < keys.length; i++) {
allServers.push(self._state.secondaries[keys[i]]);
// Get all the server instances and close them
var allServers = [];
// Make sure we have servers
if(this._state['addresses'] != null) {
var keys = Object.keys(this._state.addresses);
for(var i = 0; i < keys.length; i++) {
allServers.push(this._state.addresses[keys[i]]);
}
}
// Arbiter keys
var keys = Object.keys(self._state.arbiters);
// Add all arbiters
for(var i = 0; i < keys.length; i++) {
allServers.push(self._state.arbiters[keys[i]]);
}
// Passive keys
var keys = Object.keys(self._state.passives);
// Add all arbiters
for(var i = 0; i < keys.length; i++) {
allServers.push(self._state.passives[keys[i]]);
}
// Let's process all the closing
var numberOfServersToClose = allServers.length;
// Close the servers

@@ -492,3 +683,4 @@ for(var i = 0; i < allServers.length; i++) {

if(numberOfServersToClose == 0) {
self._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'setName':null, 'errorMessages':[]};
// Clear out state
self._state = {'master':null, 'secondaries':{}, 'arbiters':{}, 'passives':{}, 'errors':{}, 'addresses':{}, 'byTags':{}, 'setName':null, 'errorMessages':[]};
}

@@ -500,4 +692,3 @@

self.removeAllListeners();
// Perform the callback
callback(null);
callback(null);
} else if(numberOfServersToClose == 0) {

@@ -504,0 +695,0 @@ // Remove all the listeners

@@ -26,3 +26,7 @@ var Connection = require('./connection').Connection,

this.__defineGetter__("primary", function() { return self; });
this.__defineGetter__("readPreference", function() { return Server.READ_PRIMARY; });
// Set default connection pool options
this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
// Just keeps list of events we allow

@@ -32,13 +36,32 @@ this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]};

this._serverState = 'disconnected';
// Contains state information about server connection
this._state = {'runtimeStats': {'queryStats':new RunningStats()}};
// Do we record server stats or not
this.recordQueryStats = false;
// Getter for query Stats
this.__defineGetter__("queryStats", function() { return this._state.runtimeStats.queryStats; });
this.__defineGetter__("runtimeStats", function() { return this._state.runtimeStats; });
};
// Inherit simple event emitter
inherits(Server, SimpleEmitter);
// Read Preferences
Server.READ_PRIMARY = 'primary';
Server.READ_SECONDARY = 'secondary';
// Always ourselves
Server.prototype.setReadPreference = function() {}
// Server close function
Server.prototype.close = function(callback) {
// Remove all local listeners
this.removeAllListeners();
// Remove all the listeners on the pool so it does not fire messages all over the place
this.connectionPool.removeAllEventListeners();
// Close the connection if it's open
if(this.connectionPool.isConnected()) this.connectionPool.stop();
if(this.connectionPool) {
// Remove all the listeners on the pool so it does not fire messages all over the place
this.connectionPool.removeAllEventListeners();
// Close the connection if it's open
this.connectionPool.stop();
}
// Set server status as disconnected

@@ -55,3 +78,3 @@ this._serverState = 'disconnected';

Server.prototype.isConnected = function() {
return this.connectionPool.isConnected();
return this.connectionPool && this.connectionPool.isConnected();
}

@@ -81,3 +104,3 @@

// Create connection Pool instance with the current BSON serializer
var connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson_deserializer);
var connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson_deserializer, this.socketOptions);

@@ -119,2 +142,5 @@ // Set up a new pool using default settings

// Set server state to connected
server._serverState = 'connected';
// Register handler for messages

@@ -156,2 +182,9 @@ dbInstance._registerHandler(db_command, false, connection, connectHandler);

var callbackInstance = dbInstanceObject._removeHandler(mongoReply.responseTo);
// Let's record the stats info if it's enabled
if(server.recordQueryStats == true && server._state['runtimeStats'] != null
&& server._state.runtimeStats['queryStats'] instanceof RunningStats) {
// Add data point to the running statistics object
server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start);
}
// Only call if we have an actual callback instance, might have been removed by the reaper

@@ -174,6 +207,6 @@ if(callbackInstance != null) {

for(var i = 0; i < server.dbInstances.length; i++) {
server.dbInstances[i].emit("error", new Error(err));
server.dbInstances[i].emit("error", typeof err === 'string' ? new Error(err) : err);
}
} else {
eventReceiver.emit("error", new Error(err));
eventReceiver.emit("error", typeof err === 'string' ? new Error(err) : err);
}

@@ -185,3 +218,3 @@ }

// Handle errors
connectionPool.on("error", function(message) {
connectionPool.on("error", function(message) {
// Force close the pool

@@ -191,12 +224,24 @@ if(connectionPool.isConnected()) connectionPool.stop();

if(server._serverState === 'connecting' && firstCall) {
// Set server state to connected
server._serverState = 'disconnected';
// Shut down the pool
connectionPool.stop();
// Only do a callback if we have a valid callback function, on retries this might not be true
if(typeof callback === 'function') callback(new Error(message && message.err ? message.err : message));
} else {
// Set server instance to disconnected state
server._serverState = !connectionPool.isConnected() ? 'disconnected' : server._serverState;
// Emit event
if(eventEmitterIsDb) {
// Issue error across all the db instances registered in server instance
for(var i = 0; i < server.dbInstances.length; i++) {
server.dbInstances[i].emit("error", new Error(message.err));
}
if(server._serverState != 'disconnected') {
for(var i = 0; i < server.dbInstances.length; i++) {
server.dbInstances[i].emit("error", new Error(message.err));
}
}
} else {
eventReceiver.emit("error", new Error(message.err));
if(server._serverState != 'disconnected') {
eventReceiver.emit("error", new Error(message.err));
}
}

@@ -213,3 +258,3 @@ }

if(eventEmitterIsDb) {
// Issue error across all the db instances registered in server instance
// Issue close across all the db instances registered in server instance
for(var i = 0; i < server.dbInstances.length; i++) {

@@ -223,6 +268,9 @@ server.dbInstances[i].emit("close");

// Handle errors
// If we have a parser error we are in an unknown state, close everything and emit
// error
connectionPool.on("parseError", function(message) {
// Force close the pool
if(connectionPool.isConnected()) self.stop();
if(connectionPool.isConnected()) self.stop();
// Emit error
server.emit("error", message);
});

@@ -246,4 +294,57 @@

Server.prototype.enableRecordQueryStats = function(enable) {
this.recordQueryStats = enable;
}
//
// Internal statistics object used for calculating average and standard devitation on
// running queries
var RunningStats = function() {
this.m_n = 0;
this.m_oldM = 0.0;
this.m_oldS = 0.0;
this.m_newM = 0.0;
this.m_newS = 0.0;
// Define getters
Object.defineProperty(this, "numDataValues", { enumerable: true
, get: function () { return this.m_n; }
});
Object.defineProperty(this, "mean", { enumerable: true
, get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; }
});
Object.defineProperty(this, "variance", { enumerable: true
, get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); }
});
Object.defineProperty(this, "standardDeviation", { enumerable: true
, get: function () { return Math.sqrt(this.variance); }
});
Object.defineProperty(this, "sScore", { enumerable: true
, get: function () {
var bottom = this.mean + this.standardDeviation;
if(bottom == 0) return 0;
return ((2 * this.mean * this.standardDeviation)/(bottom));
}
});
}
RunningStats.prototype.push = function(x) {
// Update the number of samples
this.m_n = this.m_n + 1;
// See Knuth TAOCP vol 2, 3rd edition, page 232
if(this.m_n == 1) {
this.m_oldM = this.m_newM = x;
this.m_oldS = 0.0;
} else {
this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n;
this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM);
// set up for next iteration
this.m_oldM = this.m_newM;
this.m_oldS = this.m_newS;
}
}

@@ -27,2 +27,10 @@ var SimpleEmitter = exports.SimpleEmitter = function() {}

SimpleEmitter.prototype.listeners = function(event) {
return this.eventHandlers[event];
}
SimpleEmitter.prototype.overrideListeners = function(event, listeners) {
this.eventHandlers[event] = listeners;
}
SimpleEmitter.prototype.removeListeners = function(event) {

@@ -29,0 +37,0 @@ if(this.eventHandlers[event] == null) throw "Event handler only accepts values of " + Object.keys(this.eventHandlers);

@@ -47,2 +47,6 @@ var QueryCommand = require('./commands/query_command').QueryCommand,

// Command queue, keeps a list of incoming commands that need to be executed once the connection is up
this.commands = [];
// Set up logger
this.logger = this.options.logger != null

@@ -72,3 +76,11 @@ && (typeof this.options.logger.debug == 'function')

this.raw = this.options.raw != null ? this.options.raw : false;
// Record query stats
this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false;
// If we have server stats let's make sure the driver objects have it enabled
if(this.recordQueryStats == true) {
this.serverConfig.enableRecordQueryStats(true);
}
// Retry information

@@ -81,4 +93,2 @@ this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 5000;

this.reaperTimeout = this.options.reaperTimeout != null ? this.options.reaperTimeout : 30000;
// Start reaper, cleans up timed out calls
this.reaperIntervalId = setInterval(reaper(this, this.reaperTimeout), this.reaperInterval);
};

@@ -154,7 +164,11 @@

self.serverConfig.connect(self, {firstCall: true}, function(err, result) {
// Clear reaper interval
if(self.reaperIntervalId != null) clearInterval(self.reaperIntervalId);
if(err != null) {
// Clear reaper interval
if(self.reaperIntervalId != null) clearInterval(self.reaperIntervalId);
// Return error from connection
return callback(err, null);
} else {
// Start new reaper, cleans up timed out calls
self.reaperIntervalId = setInterval(reaper(self, self.reaperTimeout), self.reaperInterval);
}

@@ -371,5 +385,4 @@ // Callback

// Get the amount of connections in the pool to ensure we have authenticated all comments
var numberOfConnections = Object.keys(this.serverConfig.allRawConnections()).length;
var errorObject = null;
var numberOfConnections = this.serverConfig.allRawConnections().length;
var errorObject = null;
// Execute all four

@@ -718,2 +731,6 @@ this._executeQueryCommand(DbCommand.createGetNonceCommand(self), {onAll:true}, function(err, result, connection) {

Db.prototype.numberOfHandlers = function() {
return Object.keys(this._mongodbHandlers).length;
}
var __executeQueryCommand = function(self, db_command, options, callback) {

@@ -753,9 +770,7 @@ // Options unpacking

var connections = self.serverConfig.allRawConnections();
var keys = Object.keys(connections);
var numberOfEntries = keys.length;
var numberOfEntries = connections.length;
// Go through all the connections
for(var i = 0; i < keys.length; i++) {
for(var i = 0; i < connections.length; i++) {
// Fetch a connection
var connection = connections[keys[i]];
var connection = connections[i];
// Override connection if needed

@@ -809,43 +824,99 @@ connection = specifiedConnection != null ? specifiedConnection : connection;

var numberOfRetriesDone = numberOfTimes;
// The interval function triggers retries
var intervalId = setInterval(function() {
// Attemp a reconnect
self.serverConfig.connect(self, {firstCall: false}, function(err, result) {
// Adjust the number of retries done
numberOfRetriesDone = numberOfRetriesDone - 1;
// If we have no error, we are done
if(err != null && numberOfRetriesDone <= 0) {
// No more retries, clear interval retries and fire an error
clearInterval(intervalId);
callback(err, null);
} else if(err == null) {
// Clear retries and fire message
clearInterval(intervalId);
// If we have auths we need to replay them
if(Array.isArray(self.auths) && self.auths.length > 0) {
// Get number of auths we need to execute
var numberOfAuths = self.auths.length;
// Apply all auths
for(var i = 0; i < self.auths.length; i++) {
// // Ensure we listen to errors on the serverConfig (don't want unexpected exceptions escaping during listening)
// self.serverConfig.on("error", function(err) {
// console.log("============================== received error")
// console.dir(err)
// })
// Retry function, execute once
var retryFunction = function(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback) {
_self.serverConfig.connect(_self, {firstCall: false}, function(err, result) {
// Definitively restart
if(err != null && _numberOfRetriesDone > 0) {
// Adjust the number of retries left
_numberOfRetriesDone = _numberOfRetriesDone - 1;
// Force close the current connections
_self.serverConfig.close(function(err) {
// Retry the connect
setTimeout(function() {
retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);
}, _retryInMilliseconds);
});
} else if(err != null && numberOfRetriesDone <= 0) {
// Force close the current connections
_self.serverConfig.close(function(err) {
// Force close the current connections
_callback(err, null);
});
} else if(err == null && _self.serverConfig.isConnected() == true && Array.isArray(_self.auths) && _self.auths.length > 0) {
// Get number of auths we need to execute
var numberOfAuths = _self.auths.length;
// Apply all auths
for(var i = 0; i < _self.auths.length; i++) {
_self.authenticate(_self.auths[i].username, _self.auths[i].password, function(err, authenticated) {
numberOfAuths = numberOfAuths - 1;
self.authenticate(self.auths[i].username, self.auths[i].password, function(err, authenticated) {
numberOfAuths = numberOfAuths - 1;
// If we have no more authentications to replay
if(numberOfAuths == 0) {
if(err != null || !authenticated) {
return callback(err, null);
} else {
command(self, db_command, options, callback);
}
// If we have no more authentications to replay
if(numberOfAuths == 0) {
if(err != null || !authenticated) {
return _callback(err, null);
} else {
// Set connected
_self.state = 'connected';
// Execute command
command(_self, _db_command, _options, function(err, result) {
// Peform the command callback
_callback(err, result);
// Execute any backed up commands
while(_self.commands.length > 0) {
// Fetch the command
var command = _self.commands.shift();
// Execute based on type
if(command['type'] == 'query') {
__executeQueryCommand(_self, command['db_command'], command['options'], command['callback']);
} else if(command['type'] == 'insert') {
__executeInsertCommand(_self, command['db_command'], command['options'], command['callback']);
}
}
});
}
})
}
});
}
} else if(err == null && _self.serverConfig.isConnected() == true) {
// Set connected
_self.state = 'connected';
// Execute command
command(_self, _db_command, _options, function(err, result) {
// Peform the command callback
_callback(err, result);
// Execute any backed up commands
while(_self.commands.length > 0) {
// Fetch the command
var command = _self.commands.shift();
// Execute based on type
if(command['type'] == 'query') {
__executeQueryCommand(_self, command['db_command'], command['options'], command['callback']);
} else if(command['type'] == 'insert') {
__executeInsertCommand(_self, command['db_command'], command['options'], command['callback']);
}
}
} else {
command(self, db_command, options, callback);
}
});
} else {
// Adjust the number of retries left
_numberOfRetriesDone = _numberOfRetriesDone - 1;
// Force close the current connections
_self.serverConfig.close(function(err) {
// Retry the connect
setTimeout(function() {
retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);
}, _retryInMilliseconds);
});
}
});
}, retryInMilliseconds);
};
// Execute function first time
retryFunction(self, numberOfRetriesDone, retryInMilliseconds, numberOfTimes, command, db_command, options, callback);
}

@@ -865,3 +936,8 @@

if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect) {
// Set state as reconnecting
this.state = 'connecting';
// Retry command
__retryCommandOnFailure(this, this.retryMiliSeconds, this.numberOfRetries, __executeQueryCommand, db_command, options, callback);
} else if(this.state == 'connecting') {
this.commands.push({type:'insert', 'db_command':db_command, 'options':options, 'callback':callback});
} else {

@@ -894,5 +970,6 @@ __executeQueryCommand(self, db_command, options, callback)

}
// If we have no callback and there is no connection
if(connection == null) return null;
if(connection == null && typeof callback == 'function') return callback(new Error("no primary server found"), null);

@@ -906,7 +983,9 @@ // Write the message out

// Clean up listener and return error
var callbackInstance = self._removeHandler(db_command[1]);
var callbackInstance = self._removeHandler(db_command[1].getRequestId());
// Only call if the reaper has not removed it
if(callbackInstance != null) {
callbackInstance.callback(err, null);
}
} else {
callback(new Error("no callback instance found"), null);
}
} else {

@@ -929,4 +1008,9 @@ self.emit("error", err);

// If the pool is not connected, attemp to reconnect to send the message
if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect) {
if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect && this.state != 'connecting') {
// Set state as reconnecting
this.state = 'connecting';
// Retry command
__retryCommandOnFailure(this, this.retryMiliSeconds, this.numberOfRetries, __executeInsertCommand, db_command, options, callback);
} else if(this.state == 'connecting') {
this.commands.push({type:'insert', 'db_command':db_command, 'options':options, 'callback':callback});
} else {

@@ -933,0 +1017,0 @@ __executeInsertCommand(self, db_command, options, callback)

@@ -21,2 +21,3 @@

, 'collection'
, 'connection/connection'
, 'connection/server'

@@ -53,2 +54,3 @@ , 'connection/repl_set_servers'

, 'collection'
, 'connection/connection'
, 'connection/server'

@@ -87,2 +89,3 @@ , 'connection/repl_set_servers'

, 'collection'
, 'connection/connection'
, 'connection/server'

@@ -89,0 +92,0 @@ , 'connection/repl_set_servers'

{ "name" : "mongodb"
, "description" : "A node.js driver for MongoDB"
, "keywords" : ["mongodb", "mongo", "driver", "db"]
, "version" : "0.9.7-0"
, "version" : "0.9.7-1"
, "author" : "Christian Amor Kvalheim <christkv@gmail.com>"

@@ -66,5 +66,5 @@ , "contributors" : [ "Aaron Heckmann",

, "engines" : { "node" : ">=0.4.0" }
, "scripts": { "install" : "bash ./install.sh" }
, "scripts": { "install" : "bash ./install.sh || exit 0" }
, "licenses" : [ { "type" : "Apache License, Version 2.0"
, "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ]
}

@@ -27,3 +27,3 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure();

tearDown: function(callback) {
serverManager.stop(9, function(err, result) {
serverManager.killAll(function(err, result) {
callback();

@@ -147,3 +147,3 @@ });

collection.find().toArray(function(err, items) {
collection.find({}).toArray(function(err, items) {
test.ok(err == null);

@@ -150,0 +150,0 @@ test.equal(1, items.length);

@@ -15,3 +15,4 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

ServerManager = require('../test/tools/server_manager').ServerManager,
Step = require("../deps/step/lib/step");
Step = require("../deps/step/lib/step"),
mongodb = require('../lib/mongodb');

@@ -79,7 +80,6 @@ // Test db

var connections = connectionPool.getAllConnections();
var keys = Object.keys(connections);
// Ensure no close events are fired as we are closing the connection specifically
for(var i = 0; i < keys.length; i++) {
connections[keys[i]].on("close", function() { test.ok(false); });
for(var i = 0; i < connections.length; i++) {
connections[i].on("close", function() { test.ok(false); });
}

@@ -104,7 +104,6 @@

var connections = connectionPool.getAllConnections();
var keys = Object.keys(connections);
// Ensure no close events are fired as we are closing the connection specifically
for(var i = 0; i < keys.length; i++) {
connections[keys[i]].on("close", function() { test.ok(false); });
for(var i = 0; i < connections.length; i++) {
connections[i].on("close", function() { test.ok(false); });
}

@@ -120,2 +119,27 @@

testShouldCorrectlyCloseOnUnopedConnection : function(test) {
var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}),{native_parser: (process.env['TEST_NATIVE'] != null)});
db.close();
test.done();
},
testConnectUsingDefaultHostAndPort : function(test) {
var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4}),{native_parser: (process.env['TEST_NATIVE'] != null)});
db.open(function(err, db) {
test.equal(null, err);
test.done();
db.close();
})
},
testConnectUsingSocketOptions : function(test) {
var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4, socketOptions:{keepAlive:100}}),{native_parser: (process.env['TEST_NATIVE'] != null)});
db.open(function(err, db) {
test.equal(null, err);
test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive)
test.done();
db.close();
})
},
noGlobalsLeaked : function(test) {

@@ -122,0 +146,0 @@ var leaks = gleak.detectNew();

@@ -628,3 +628,3 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

},
shouldCorrectlyExecuteFindOneWithAnInSearchTag : function(test) {

@@ -946,2 +946,30 @@ client.createCollection('shouldCorrectlyExecuteFindOneWithAnInSearchTag', function(err, collection) {

'Should correctly execute find and findOne queries with selector set to null' : function(test) {
client.createCollection('Should_correctly_execute_find_and_findOne_queries_in_the_same_way', function(err, collection) {
var doc = {_id : new client.bson_serializer.ObjectID(), a:1, c:2, comments:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]};
// insert doc
collection.insert(doc, {safe:true}, function(err, result) {
collection.find(null, {comments: {$slice: -5}}).toArray(function(err, docs) {
test.equal(5, docs[0].comments.length)
collection.findOne(null, {comments: {$slice: -5}}, function(err, item) {
test.equal(5, item.comments.length)
test.done();
});
});
});
});
},
shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists : function(test) {
client.createCollection('shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists', function(err, collection) {
collection.findAndModify({'a':1}, [], {'$set':{'b':3}}, {'new': true}, function(err, updated_doc) {
test.equal(null, err)
test.equal(null, updated_doc);
test.done();
});
});
},
noGlobalsLeaked : function(test) {

@@ -948,0 +976,0 @@ var leaks = gleak.detectNew();

@@ -61,2 +61,4 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

client.open(function(err, db_p) {
if(err != null) throw err;
if(numberOfTestsRun == Object.keys(tests).length) {

@@ -819,2 +821,34 @@ // If first test drop the db

'Should Correctly update two fields including a sub field' : function(test) {
var doc = {
_id: new client.bson_serializer.ObjectID(),
Prop1: 'p1',
Prop2: 'p2',
More: {
Sub1: 's1',
Sub2: 's2',
Sub3: 's3'
}
}
client.createCollection("Should_Correctly_update_two_fields_including_a_sub_field", {}, function(err, collection) {
collection.insert(doc, {safe:true}, function(err, result) {
test.equal(null, err);
// Update two fields
collection.update({_id:doc._id}, {$set:{Prop1:'p1_2', 'More.Sub2':'s2_2'}}, {safe:true}, function(err, numberOfUpdatedDocs) {
test.equal(null, err);
test.equal(1, numberOfUpdatedDocs);
collection.findOne({_id:doc._id}, function(err, item) {
test.equal(null, err);
test.equal('p1_2', item.Prop1);
test.equal('s2_2', item.More.Sub2);
test.done();
})
});
})
});
},
noGlobalsLeaked : function(test) {

@@ -821,0 +855,0 @@ var leaks = gleak.detectNew();

@@ -100,3 +100,3 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

var originalHex= objectId.toHexString();
var newObjectId= new client.bson_serializer.ObjectID.createFromHexString(originalHex)

@@ -131,2 +131,10 @@ var newHex= newObjectId.toHexString();

},
shouldCorrectlyGenerateObjectIDFromTimestamp : function(test) {
var timestamp = Math.floor(new Date().getTime()/1000);
var objectID = new client.bson_serializer.ObjectID(timestamp);
var time2 = objectID.generationTime;
test.equal(timestamp, time2);
test.done();
},

@@ -133,0 +141,0 @@ noGlobalsLeaked : function(test) {

@@ -16,2 +16,8 @@ var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

// process.on('uncaughtException', function(err) {
// console.log("-------------------------------------------------------------------------")
// console.dir(err)
// console.log(err.stack)
// })
// Define the tests, we want them to run as a nested test so we only clean up the

@@ -174,3 +180,3 @@ // db connection once

client.createCollection('shouldCorrectlyPeformQueryUsingRaw', function(err, collection) {
collection.insert([{a:1}, {b:2}, {b:3}], function(err, result) {
collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) {
test.equal(null, err);

@@ -189,6 +195,7 @@

client.bson_deserializer.BSON.serializeWithBufferAndIndex(fieldsObject, false, rawFieldsObject, 0);
collection.find(rawQueryObject, rawFieldsObject, {raw:true}).toArray(function(err, items) {
test.equal(1, items.length);
test.ok(items[0] instanceof Buffer);
if(items[0] == null) console.dir(items)
var object = client.bson_deserializer.BSON.deserialize(items[0]);

@@ -198,2 +205,4 @@ test.equal(3, object.b)

collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) {
test.equal(null, err);
test.ok(item != null);
var object = client.bson_deserializer.BSON.deserialize(item);

@@ -264,3 +273,3 @@ test.equal(3, object.b)

client.createCollection('shouldCorrectlyPeformQueryUsingRawSettingRawAtCollectionLevel', function(err, collection) {
collection.insert([{a:1}, {b:2}, {b:3}], function(err, result) {
collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) {
test.equal(null, err);

@@ -288,2 +297,4 @@

collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) {
test.equal(null, err);
test.ok(item != null);
var object = client.bson_deserializer.BSON.deserialize(item);

@@ -290,0 +301,0 @@ test.equal(3, object.b)

@@ -71,5 +71,5 @@ var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false;

tearDown: function(callback) {
RS.restartKilledNodes(function(err, result) {
// RS.restartKilledNodes(function(err, result) {
callback();
});
// });
},

@@ -94,3 +94,22 @@

},
shouldCorrectlyConnectWithDefaultReplicasetAndSocketOptionsSet : function(test) {
// Replica configuration
var replSet = new ReplSetServers([
new Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[0], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[2], { auto_reconnect: true } )
],
{socketOptions:{keepAlive:100}}
);
var db = new Db('integration_test_', replSet);
db.open(function(err, p_db) {
test.equal(null, err);
test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive)
test.done();
p_db.close();
})
},
shouldEmitCloseNoCallback : function(test) {

@@ -129,3 +148,3 @@ // Replica configuration

test.equal(null, err);
var dbCloseCount = 0;//, serverCloseCount = 0;
var dbCloseCount = 0;
db.on('close', function() { ++dbCloseCount; });

@@ -137,3 +156,2 @@

test.equal(dbCloseCount, 0);
// test.equal(serverCloseCount, db.serverConfig.servers.length);
test.done();

@@ -140,0 +158,0 @@ });

@@ -40,4 +40,4 @@ var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false;

db.open(function(err, p_db) {
db.close();
if(err != null) {
db.close();
// Wait for a sec and retry

@@ -74,5 +74,5 @@ setTimeout(function() {

tearDown: function(callback) {
RS.restartKilledNodes(function(err, result) {
// RS.restartKilledNodes(function(err, result) {
callback();
});
// });
},

@@ -124,5 +124,3 @@

if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err));
test.ok(err == null);
test.equal(true, p_db.serverConfig.isConnected());

@@ -129,0 +127,0 @@ p_db.collection('testsets', function(err, collection) {

@@ -18,2 +18,7 @@ var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false;

// process.on("uncaughtException", function(err) {
// console.log("================================================================ uncaughtException")
// console.dir(err)
// })
var ensureConnection = function(test, numberOfTries, callback) {

@@ -42,4 +47,7 @@ // Replica configuration

db.open(function(err, p_db) {
// Close connections
db.close();
// Process result
if(err != null) {
db.close();
// db.close();
// Wait for a sec and retry

@@ -61,3 +69,3 @@ setTimeout(function() {

serversUp = true;
RS = new ReplicaSetManager({retries:120, passive_count:1, arbiter_count:1});
RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1});
RS.startSet(true, function(err, result) {

@@ -74,5 +82,5 @@ callback();

tearDown: function(callback) {
RS.restartKilledNodes(function(err, result) {
// RS.restartKilledNodes(function(err, result) {
callback();
});
// });
},

@@ -98,6 +106,6 @@

// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, r) {
if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, collection) {
if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err));

@@ -133,6 +141,6 @@ // Insert a dummy document

// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, r) {
if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, collection) {
if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err));

@@ -168,6 +176,6 @@ // Insert a dummy document

// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, r) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, collection) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

@@ -202,3 +210,3 @@ // Insert a dummy document

// Insert some data
var db = new Db('integration_test_', replSet);
var db = new Db('integration_test_', replSet, {retryMiliSeconds:1000});

@@ -223,6 +231,6 @@ // Print any errors

// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, r) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, collection) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

@@ -234,7 +242,9 @@ // Insert a dummy document

setTimeout(function() {
// console.log("--------------------------------------------------------------------- -1")
// Kill the primary
RS.killPrimary(2, {killNodeWaitTime:10}, function(node) {
RS.killPrimary(2, {killNodeWaitTime:1}, function(node) {
// console.log("--------------------------------------------------------------------- 0")
// Attempt insert (should fail)
collection.insert({a:30}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
// console.log("--------------------------------------------------------------------- 1")
test.ok(err != null)

@@ -244,18 +254,28 @@

if(err != null) {
collection.insert({a:40}, {safe: true}, function(err, r) {
// console.log("--------------------------------------------------------------------- 2")
collection.insert({a:40}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
// Peform a count
collection.count(function(err, count) {
test.equal(2, count);
p_db.close();
test.done();
// console.log("===================================================================== START")
// console.log("===================================================================== START")
// console.log("===================================================================== START")
setTimeout(function() {
// console.log("===================================================================== DONE")
p_db.close();
test.done();
}, 5000)
});
});
} else {
console.log("+++++++++++++++++++++++++++++++++++++++++++ FAILURE")
// console.log("--------------------------------------------------------------------- 3")
p_db.close();
test.ok(false)
test.done();
}
});
});
}, 2000);
}, 5000);
});

@@ -293,6 +313,6 @@ });

// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, r) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, collection) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

@@ -304,9 +324,13 @@ // Insert a dummy document

setTimeout(function() {
// console.log("--------------------------------------------------------------------- -1")
// Kill the primary
RS.killPrimary(2, {killNodeWaitTime:1}, function(node) {
// console.log("--------------------------------------------------------------------- 0")
// Ok let's execute same query a couple of times
collection.find({}).toArray(function(err, items) {
// console.log("--------------------------------------------------------------------- 1")
test.ok(err != null);
collection.find({}).toArray(function(err, items) {
// console.log("--------------------------------------------------------------------- 2")
test.ok(err == null);

@@ -316,2 +340,3 @@ test.equal(1, items.length);

collection.find({}).toArray(function(err, items) {
// console.log("--------------------------------------------------------------------- 3")
test.ok(err == null);

@@ -346,8 +371,11 @@ test.equal(1, items.length);

db.open(function(err, p_db) {
// console.log("=============================================================== 0")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Drop collection on replicaset
p_db.dropCollection('testsets', function(err, r) {
p_db.dropCollection('shouldWorkCorrectlyWithInserts', function(err, r) {
// console.log("=============================================================== 1")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Recreate collection on replicaset
p_db.createCollection('testsets', function(err, collection) {
p_db.createCollection('shouldWorkCorrectlyWithInserts', function(err, collection) {
// console.log("=============================================================== 2")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

@@ -357,2 +385,3 @@

collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) {
// console.log("=============================================================== 3")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));

@@ -362,97 +391,106 @@

collection.count(function(err, c) {
// console.log("=============================================================== 4")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
test.equal(1, c);
// Close starting connection
p_db.close();
// Ensure replication happened in time
setTimeout(function() {
// Kill the primary
RS.killPrimary(function(node) {
// Ensure valid connection
// Do inserts
ensureConnection(test, retries, function(err, p_db) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
test.ok(err == null);
test.equal(true, p_db.serverConfig.isConnected());
p_db.collection('testsets', function(err, collection) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Execute a set of inserts
Step(
function inserts() {
var group = this.group();
collection.save({a:30}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:40}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:50}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:60}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:70}, {safe:{w:2, wtimeout: 10000}}, group());
},
function finishUp(err, values) {
// Restart the old master and wait for the sync to happen
RS.restartKilledNodes(function(err, result) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Contains the results
var results = [];
// Just wait for the results
setTimeout(function() {
// Ensure the connection
ensureConnection(test, retries, function(err, p_db) {
// Kill the primary
RS.killPrimary(function(node) {
// console.log("=============================================================== 5")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
test.ok(err == null);
p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) {
// console.log("=============================================================== 6")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Execute a set of inserts
Step(
function inserts() {
var group = this.group();
collection.save({a:30}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:40}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:50}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:60}, {safe:{w:2, wtimeout: 10000}}, group());
collection.save({a:70}, {safe:{w:2, wtimeout: 10000}}, group());
},
function finishUp(err, values) {
// console.log("=============================================================== 7")
// Restart the old master and wait for the sync to happen
RS.restartKilledNodes(function(err, result) {
// console.log("=============================================================== 8")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Contains the results
var results = [];
// Just wait for the results
setTimeout(function() {
// console.log("=============================================================== 9")
// Ensure the connection
ensureConnection(test, retries, function(err, p_db) {
// console.log("=============================================================== 10")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Get the collection
p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) {
// console.log("=============================================================== 11")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
collection.find().each(function(err, item) {
// console.log("=============================================================== 12")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Get the collection
p_db.collection('testsets', function(err, collection) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
collection.find().each(function(err, item) {
if(item == null) {
// console.log("=============================================================== 13")
// Ensure we have the correct values
test.equal(6, results.length);
[20, 30, 40, 50, 60, 70].forEach(function(a) {
test.equal(1, results.filter(function(element) {
return element.a == a;
}).length);
});
// Run second check
collection.save({a:80}, {safe:true}, function(err, r) {
// console.log("=============================================================== 14")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
if(item == null) {
collection.find().toArray(function(err, items) {
// console.log("=============================================================== 15")
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Ensure we have the correct values
test.equal(6, results.length);
[20, 30, 40, 50, 60, 70].forEach(function(a) {
test.equal(1, results.filter(function(element) {
return element.a == a;
}).length);
});
// Run second check
collection.save({a:80}, {safe:true}, function(err, r) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
collection.find().toArray(function(err, items) {
if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err));
// Ensure we have the correct values
test.equal(7, items.length);
[20, 30, 40, 50, 60, 70, 80].forEach(function(a) {
test.equal(1, items.filter(function(element) {
return element.a == a;
}).length);
});
p_db.close();
test.done();
});
});
} else {
results.push(item);
}
});
});
});
}, 5000);
})
}
);
});
});
test.equal(7, items.length);
// console.log("=============================================================== 16")
// console.dir(err)
// console.dir(items)
// Sort items by a
items = items.sort(function(a,b) { return a.a > b.a});
// Test all items
test.equal(20, items[0].a);
test.equal(30, items[1].a);
test.equal(40, items[2].a);
test.equal(50, items[3].a);
test.equal(60, items[4].a);
test.equal(70, items[5].a);
test.equal(80, items[6].a);
p_db.close();
test.done();
});
});
} else {
results.push(item);
}
});
});
});
}, 5000);
})
}
);
});
}, 2000);
});
})

@@ -459,0 +497,0 @@ })

@@ -21,5 +21,5 @@ var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false;

var replSet = new ReplSetServers( [
// new Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[0], { auto_reconnect: true } ),
// new Server( RS.host, RS.ports[2], { auto_reconnect: true } )
new Server( RS.host, RS.ports[2], { auto_reconnect: true } )
],

@@ -42,4 +42,4 @@ {rs_name:RS.name}

db.open(function(err, p_db) {
db.close();
if(err != null) {
db.close();
// Wait for a sec and retry

@@ -61,3 +61,3 @@ setTimeout(function() {

serversUp = true;
RS = new ReplicaSetManager({retries:120, passive_count:1, arbiter_count:1});
RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1});
RS.startSet(true, function(err, result) {

@@ -77,6 +77,6 @@ if(err != null) throw err;

tearDown: function(callback) {
RS.restartKilledNodes(function(err, result) {
if(err != null) throw err;
// RS.restartKilledNodes(function(err, result) {
// if(err != null) throw err;
callback();
})
// })
},

@@ -100,5 +100,5 @@

if(err != null) debug("shouldReadPrimary :: " + inspect(err));
test.equal(false, p_db.serverConfig.isReadPrimary());
test.equal(false, p_db.serverConfig.isPrimary());
p_db.close();
test.done();

@@ -130,2 +130,3 @@ });

test.ok(p_db.serverConfig.primary.port != p_db.serverConfig.read.port);
p_db.close();
test.done();

@@ -142,2 +143,4 @@ });

new Server( RS.host, RS.ports[0], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new Server( RS.host, RS.ports[2], { auto_reconnect: true } ),
],

@@ -164,2 +167,3 @@ {rs_name:RS.name, read_secondary:true}

test.equal(3, items.length);
p_db.close();
test.done();

@@ -181,19 +185,3 @@ });

var retryEnsure = function(numberOfRetries, execute, callback) {
execute(function(done) {
if(done) {
return callback(null, null);
} else {
numberOfRetries = numberOfRetries - 1;
if(numberOfRetries <= 0) {
return callback(new Error("Failed to execute command"), null);
} else {
setTimeout(function() {
retryEnsure(numberOfRetries, execute, callback);
}, 1000);
}
}
});
}

@@ -213,4 +201,1 @@

@@ -32,4 +32,4 @@ var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false;

db.open(function(err, p_db) {
db.close();
if(err != null) {
db.close();
// Wait for a sec and retry

@@ -70,6 +70,6 @@ setTimeout(function() {

tearDown: function(callback) {
RS.restartKilledNodes(function(err, result) {
if(err != null) throw err;
// RS.restartKilledNodes(function(err, result) {
// if(err != null) throw err;
callback();
})
// })
},

@@ -105,2 +105,3 @@

test.equal(true, err.wtimeout)
p_db.close();
test.done();

@@ -107,0 +108,0 @@ });

@@ -25,2 +25,3 @@ var debug = require('util').debug,

this.killNodeWaitTime = options['kill_node_wait_time'] != null ? options['kill_node_wait_time'] : 20000;
this.tags = options['tags'] != null ? options['tags'] : [];

@@ -88,3 +89,2 @@ this.arbiterCount = options["arbiter_count"] != null ? options["arbiter_count"] : 2;

killall = args.length ? args.shift() : true;
debug("** Starting a replica set with " + this.count + " nodes");

@@ -95,9 +95,10 @@

var n = 0;
var tagsIndex = 0;
Step(
function startPrimaries() {
function startAllServers() {
var group = this.group();
// Start primary instances
for(n = 0; n < (self.primaryCount + self.secondaryCount); n++) {
self.initNode(n, {}, group());
self.initNode(n, {tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group());
}

@@ -107,3 +108,3 @@

for(var i = 0; i < self.passiveCount; i++) {
self.initNode(n, {priority:0}, group())
self.initNode(n, {priority:0, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group())
n = n + 1;

@@ -114,3 +115,3 @@ }

for(var i = 0; i < self.arbiterCount; i++) {
self.initNode(n, {arbiterOnly:true}, group());
self.initNode(n, {arbiterOnly:true, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group());
n = n + 1;

@@ -215,2 +216,8 @@ }

}
// Check if we have tags
if(self.mongods[n]['tags'] != null) {
member["tags"] = self.mongods[n]['tags'];
}
// Push member to config

@@ -375,3 +382,5 @@ self.config["members"].push(member);

connection.admin().command({"replSetGetStatus": 1}, function(err, object) {
/// Get documents
// Close connection
if(connection != null) connection.close();
// Get documents
var documents = object.documents;

@@ -389,4 +398,2 @@ // Get status object

done = true;
// if we have a connection force close it
if(connection != null) connection.close();
// Return error

@@ -424,4 +431,2 @@ return callback(new Error("Operation Failure"), null);

done = true;
// if we have a connection force close it
if(connection != null) connection.close();
// Return error

@@ -436,2 +441,4 @@ return callback(new Error("Operation Failure"), null);

});
} else if(err != null && connection != null) {
if(connection != null) connection.close();
}

@@ -444,78 +451,2 @@ });

ensureUpFunction();
// // Write out the ensureUp
// // process.stdout.write(".");
// if(!self.up) process.stdout.write(".");
// // Retry check for server up sleeping inbetween
// self.retriedConnects = 0;
// // Attemp to retrieve a connection
// self.getConnection(function(err, connection) {
// // If we have an error or no connection object retry
// if(err != null || connection == null) {
// // if we have a connection force close it
// if(connection != null) connection.close();
// // Retry the connection
// setTimeout(function() {
// self.ensureUpRetries++;
// self.ensureUp(callback);
// }, 1000)
// // Return
// return;
// }
//
// // Check repl set get status
// connection.admin().command({"replSetGetStatus": 1}, function(err, object) {
// /// Get documents
// var documents = object.documents;
// // Get status object
// var status = documents[0];
//
// // If no members set
// if(status["members"] == null || err != null) {
// // if we have a connection force close it
// if(connection != null) connection.close();
// // Ensure we perform enough retries
// if(self.ensureUpRetries < self.retries) {
// setTimeout(function() {
// self.ensureUpRetries++;
// self.ensureUp(callback);
// }, 1000)
// } else {
// // if we have a connection force close it
// if(connection != null) connection.close();
// // Return error
// return callback(new Error("Operation Failure"), null);
// }
// } else {
// // Establish all health member
// var healthyMembers = status.members.filter(function(element) {
// return element["health"] == 1 && [1, 2, 7].indexOf(element["state"]) != -1
// });
//
// var stateCheck = status["members"].filter(function(element, indexOf, array) {
// return element["state"] == 1;
// });
//
// if(healthyMembers.length == status.members.length && stateCheck.length > 0) {
// // if we have a connection force close it
// if(connection != null) connection.close();
// // process.stdout.write("all members up! \n\n");
// if(!self.up) process.stdout.write("all members up!\n\n")
// self.up = true;
// return callback(null, status);
// } else {
// // if we have a connection force close it
// if(connection != null) connection.close();
// // Ensure we perform enough retries
// if(self.ensureUpRetries < self.retries) {
// setTimeout(function() {
// self.ensureUpRetries++;
// self.ensureUp(callback);
// }, 1000)
// } else {
// return callback(new Error("Operation Failure"), null);
// }
// }
// }
// });
// });
}

@@ -633,3 +564,3 @@

// Create boot command
this.mongods[n]["start"] = "mongod --noprealloc --smallfiles --replSet " + this.name + " --logpath '" + this.mongods[n]['log_path'] + "' " +
this.mongods[n]["start"] = "mongod --rest --noprealloc --smallfiles --replSet " + this.name + " --logpath '" + this.mongods[n]['log_path'] + "' " +
" --dbpath " + this.mongods[n]['db_path'] + " --port " + this.mongods[n]['port'] + " --fork";

@@ -636,0 +567,0 @@ this.mongods[n]["start"] = this.durable ? this.mongods[n]["start"] + " --dur" : this.mongods[n]["start"];

@@ -18,3 +18,3 @@ var debug = require('util').debug,

this.log_path = getPath(this, "log-" + this.port);
this.durable = options["durable"] != null ? options["durable"] : false;
this.journal = options["journal"] != null ? options["journal"] : false;
this.auth = options['auth'] != null ? options['auth'] : false;

@@ -37,3 +37,3 @@ this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true;

var startCmd = generateStartCmd({log_path: self.log_path,
db_path: self.db_path, port: self.port, durable: self.durable, auth:self.auth});
db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth});

@@ -90,3 +90,3 @@ // console.log("----------------------------------------------------------------------- start")

callback();
}, 500);
}, 5000);
}

@@ -119,2 +119,8 @@ });

ServerManager.prototype.killAll = function(callback) {
exec('killall mongod', function(err, stdout, stderr) {
callback(null, null);
});
}
// Get absolute path

@@ -130,5 +136,5 @@ var getPath = function(self, name) {

" --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork";
startCmd = options['durable'] ? startCmd + " --dur" : startCmd;
startCmd = options['journal'] ? startCmd + " --journal" : startCmd;
startCmd = options['auth'] ? startCmd + " --auth" : startCmd;
return startCmd;
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc