Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

hapi

Package Overview
Dependencies
Maintainers
2
Versions
295
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

hapi - npm Package Compare versions

Comparing version 0.5.0 to 0.5.1

test/integration/hapi.server.js

269

lib/monitor/index.js

@@ -12,3 +12,3 @@ /*

var Os = require('./os');
var ProcessMonitor = require('./process');
var Process = require('./process');

@@ -20,95 +20,224 @@ // Declare internals

// Monitor constructor
/**
* Monitor Constructor
*
* @param {Object} server (HTTP Server), must be an EventEmitter
* @param {Object} settings object with configuration
* @param {Function} logger instance
* @api public
*/
module.exports = Monitor = function (server, settings, logger) {
module.exports = Monitor = function (server) {
// Public properties
this.server = server.listener;
this.options = Utils.merge({}, server.settings || {});
this.clients = {};
this.timer = null;
this.server = server;
this.options = Utils.merge({}, settings || {});
this.package = this._loadPackage();
this.logger = logger;
// Load process level functions
if (this.options && this.options.monitor) {
this.process = new ProcessMonitor();
// Load process level functions
// Load OS level functions
this.process = new Process.Monitor();
// this.os = new OsMonitor();
this.os = new Os.Monitor();
// Load OS level functions
// Public properties
this.os = new Os.Monitor();
this.clients = {};
this.timer = null;
try {
// Initialize Events
this.package = require(process.env.PWD + "/package.json");
} catch (e) {
this._initOps();
this._initRequests();
this._initLogs();
}
else {
this.package = {};
this.logger.info("Hapi monitoring is disabled");
}
return this;
};
Monitor.prototype.getClient = function (host) {
/**
* Load and parse package.json from instance of web server
*
* @param {String} rootdir path to root directory
* @api private
*/
Monitor.prototype._loadPackage = function(rootdir) {
if (this.clients.hasOwnProperty(host)) {
rootdir = rootdir || process.env.PWD;
var path = require('path'),
fs = require('fs'),
filepath = rootdir + "/package.json";
return this.clients[host];
if (path.existsSync(rootdir)) {
try {
var package = require(filepath);
}
catch (e) {
try {
var package = JSON.parse(fs.readFileSync(filepath));
}
catch (e) {
this.logger("Error parsing package.json at: " + filepath);
throw e;
}
}
return package;
}
else {
this.clients[host] = new Client({ host: host });
return this.clients[host];
return {}
}
};
}
Monitor.prototype.logger = function () {
/**
* Initialize Operations Monitoring if configured
*
* @api private
*/
Monitor.prototype._initOps = function() {
var self = this;
var that = this;
if (typeof this.options.monitor.ops !== "undefined" &&
this.options.monitor.ops !== null) {
if (this.server) {
if (this.options.monitor.interval &&
Object.keys(this.options.monitor.ops).length > 0) {
this.server.removeListener('response', this.handle('request'));
this.server.on('response', this.handle('request'));
}
this.ops_interval = setInterval((function(){
if (this.options.monitor.interval && Object.keys(this.options.monitor.ops).length > 0) {
that.processOps(function(err, results) {
clearInterval(this.timer);
this.timer = setInterval((function (s) {
// if (err === null) {
if( !err ) {
return function () {
that.server.emit('ops', results);
}
else {
return s.meter();
};
})(self), this.options.monitor.interval);
that.logger.err(err);
}
})
}), this.options.monitor.interval);
// Support user-defined binds via config
// Also, support multiple outbound locations
var useDefault = true;
for(var posturl in Object.keys(this.options.monitor.ops)) {
if (typeof this.options.monitor.ops[posturl] == "function") {
this.server.on('ops', this.options.monitor.ops[posturl]);
useDefault = false;
}
}
if (useDefault == true) {
this.server.on('ops', this.handle('ops'));
}
}
else {
this.logger.err("'interval' setting must be also be supplied with 'ops'");
}
}
else {
return this.process.instrument;
};
this.logger.info("Hapi will not be monitoring ops data");
}
}
Monitor.prototype.meter = function () {
/**
* Initial Request Monitoring if configured
*
* @api private
*/
Monitor.prototype._initRequests = function() {
var event = 'ops';
var hosts = Object.keys(this.options.monitor[event]);
if (this.options.monitor.request &&
Object.keys(this.options.monitor.request).length >0) {
for (var i in hosts) {
var useDefault = true;
for(var posturl in Object.keys(this.options.monitor.request)) {
if (hosts.hasOwnProperty(i)) {
if (typeof this.options.monitor.request[posturl] == "function") {
var host = hosts[i];
var client = this.getClient(host);
// console.log(this.os.poll_cpu.toString());
this.options.monitor[event][host](client, this)();
this.server.on('response', this.options.monitor.request[posturl]);
useDefault = false;
}
}
if (useDefault == true) {
this.server.on('response', this.handle('request'));
}
}
else {
this.logger.info("Hapi will not be monitoring request responses");
}
}
/**
* Initial Log Monitoring if configured
*
* @api private
*/
Monitor.prototype._initLogs = function() {
if (this.options.monitor.log &&
Object.keys(this.options.monitor.log).length >0) {
this.logger.externalStores = this.options.monitor.log;
}
else {
this.logger.info("Hapi will be logging to stdout");
}
}
/**
* Get a Hapi HTTP Client
*
* @param {String} host Base URL for the HTTP Client
* @api public
*/
Monitor.prototype.getClient = function (host) {
if (this.clients.hasOwnProperty(host)) {
return this.clients[host];
}
else {
this.clients[host] = new Client({ host: host });
return this.clients[host];
}
};
Monitor.prototype._request = function (client, url, monitor) {
/**
* Generate and send Request Monitoring data
*
* @param {Object} client HTTP client to use for sending
* @param {String} url path to POST data
* @api private
*/
Monitor.prototype._request = function (client, url) {

@@ -136,2 +265,4 @@ var that = this;

// Note: Anivia-specific schema
var data = {

@@ -159,2 +290,9 @@

/**
* Gather Operational Statistics in Parallel
*
* @param {Function} callback to receive resulting data
* @api public
*/
Monitor.prototype.processOps = function(callback) {

@@ -172,13 +310,20 @@

pscpu: this.process.cpu
}, function (err, results) {
callback(err || null, results);
});
}, callback);
};
Monitor.prototype._ops = function(client, url, monitor) {
/**
* Generate and send Operational Monitoring data
*
* @param {Object} client HTTP client to use for sending
* @param {String} url path to POST data
* @api private
*/
Monitor.prototype._ops = function(client, url) {
var that = this;
return function(results) {
// Note: Anivia-specific schema
var module = that.options.module || 'Blammo';

@@ -219,2 +364,9 @@ var data = {

/**
* Respond to Monitoring Signals and dispatch handlers
*
* @param {String} event signal name
* @api public
*/
Monitor.prototype.handle = function (event) {

@@ -255,3 +407,2 @@

};
};
};

@@ -19,2 +19,7 @@ /*

/**
* Operating System Monitor Constructor
*
* @api public
*/
OSMonitor = function () {

@@ -33,5 +38,6 @@

/**
* Return memory statistics to a callback
*
*
*
* @param {Function} callback
* @api public
*/

@@ -51,2 +57,3 @@ OSMonitor.prototype.mem = function (callback) {

*
* @param {String} target (optional) allow user to specify individual CPU by number
* @param {Function} callback function to process the asynchronous result

@@ -188,2 +195,2 @@ * @api private

module.exports = new OSMonitor();
module.exports.Monitor = OSMonitor;
module.exports.Monitor = OSMonitor;

@@ -18,5 +18,13 @@ /*

module.exports = ProcessMonitor = function () {
/**
* Process Monitor Constructor, most functions inherited from process module
*
* @api public
*/
ProcessMonitor = function () {
this.builtins = ['uptime', 'memoryUsage'];
// Expose Node os functions as async fns
Utils.inheritAsync(ProcessMonitor, process, this.builtins);

@@ -65,38 +73,3 @@

/**
* Return request response time TODO: move into sep request.js file?
*
* @api public
* @param {Object} req Express request object
*/
ProcessMonitor.prototype.responseTime = function (req) {
if (!req._startTime) {
return null;
}
return (new Date()) - req._startTime;
};
/**
* Instrumentation for Hapi goes here
*/
ProcessMonitor.prototype.instrument = function (req, res, next) {
if (req._instrumented) {
return next();
}
req._startTime = new Date();
req._instrumented = true;
next();
};
module.exports = new ProcessMonitor();
module.exports.Monitor = ProcessMonitor;

@@ -92,45 +92,2 @@ /*

// Initialize Log downstream if set
this.monitor = null;
if (this.settings.monitor) {
this.monitor = new Monitor(this);
if (this.settings.monitor.ops &&
this.settings.monitor.interval &&
Object.keys(this.settings.monitor.ops).length > 0) {
this.on('ops', this.monitor.handle('ops'));
this.monitor_interval = setInterval((function () {
that.monitor.processOps(function (err, results) {
if (err === null) {
that.emit('ops', results);
}
else {
Log.err(err);
}
});
}), this.settings.monitor.interval);
}
if (this.settings.monitor.request &&
Object.keys(this.settings.monitor.request).length > 0) {
this.on('response', this.monitor.handle('request'));
}
if (this.settings.monitor.log &&
Object.keys(this.settings.monitor.log).length > 0) {
Log.externalStores = this.settings.monitor.log;
}
}
// Initialize cache engine

@@ -229,10 +186,6 @@

// Setup OPTIONS handler
// Initialize Monitoring if set
this.router.options(/.+/, function () {
this.monitor = new Monitor(this, this.settings, Log);
that.setCorsHeaders(this.res);
internals.respond(this.res, 200);
});
// Setup OAuth token endpoint

@@ -565,3 +518,3 @@

res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, If-None-Match');
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, If-None-Match, X-Requested-With');
res.setHeader('Access-Control-Max-Age', this.settings.cors.maxAge);

@@ -601,2 +554,3 @@ };

var that = this;
var routeConfig = (this.routeDefaults ? Utils.merge(Utils.clone(this.routeDefaults), config) : config);

@@ -662,4 +616,7 @@

var next = arguments[arguments.length - 1]; // Does not modify 'arguments'
var params = arguments.slice(0, arguments.length - 1);
// var next = arguments[arguments.length - 1]; // Does not modify 'arguments'
// var params = arguments.slice(0, arguments.length - 1);
var args = Array.prototype.slice.call(arguments); // Convert arguments to instanceof Array
var next = args[args.length - 1];
var params = args.slice(0, args.length - 1);
func(this.req, this.res, next, params);

@@ -697,2 +654,13 @@ };

this.router[routeConfig.method.toLowerCase()](routeConfig.path, { stream: true }, chain);
// Setup CORS 'OPTIONS' handler
if (routeConfig.cors !== false) {
this.router.options(routeConfig.path, function () {
that.setCorsHeaders(this.res);
internals.respond(this.res, 200);
});
}
};

@@ -769,4 +737,7 @@

var defaultInstances = (arguments.length === 2 ? (arguments[0] instanceof Array ? arguments[0] : [arguments[0]]) : null);
var routes = (arguments.length === 2 ? arguments[1] : arguments[0]);
// var defaultInstances = (arguments.length === 2 ? (arguments[0] instanceof Array ? arguments[0] : [arguments[0]]) : null);
// var routes = (arguments.length === 2 ? arguments[1] : arguments[0]);
var args = Array.prototype.slice.call(arguments); // Convert arguments to instanceof Array
var defaultInstances = (args.length === 2 ? (args[0] instanceof Array ? args[0] : [args[0]]) : null);
var routes = (args.length === 2 ? args[1] : args[0]);

@@ -773,0 +744,0 @@ // Process each route

{
"name": "hapi",
"description": "HTTP API Server framework",
"version": "0.5.0",
"version": "0.5.1",
"author": "Eran Hammer-Lahav <eran@hueniverse.com>",

@@ -27,3 +27,3 @@ "repository": "git://github.com/walmartlabs/hapi",

"sinon": "1.3.4",
"joi":"0.3.x"
"joi":"0.x.x"
},

@@ -30,0 +30,0 @@ "devDependencies": {

@@ -1,22 +0,24 @@

var assert = require('assert');
var b64 = require("../lib/base64");
var should = require("should");
// var assert = require('assert');
// var b64 = require("../lib/base64");
// var should = require("should");
describe("base64", function(){
var source = "World of WalmartLabs",
encoded = "V29ybGQgb2YgV2FsbWFydExhYnM=";
// describe("base64", function(){
// var source = "World of WalmartLabs",
// encoded = "V29ybGQgb2YgV2FsbWFydExhYnM=";
describe("#encode", function(){
it("should encode known sample to known encoding", function(done){
b64.encode(source).should.equal(encoded);
done();
})
})
// describe("#encode", function(){
// it("should encode known sample to known encoding", function(done){
// var test = b64.encode(source);
// console.log(test, encoded, test === encoded);
// test.should.equal(encoded);
// done();
// })
// })
describe("#decode", function(){
it("should decode known encoding to known sample", function(done){
b64.decode(encoded).should.equal(source);
done();
})
})
})
// describe("#decode", function(){
// it("should decode known encoding to known sample", function(done){
// b64.decode(encoded).should.equal(source);
// done();
// })
// })
// })

@@ -1,183 +0,185 @@

var assert = require('assert');
var hapi = require('../lib/hapi');
var should = require("should");
var sinon = require("sinon");
var utils = require("../lib/utils");
// var assert = require('assert');
// var hapi = require('../lib/hapi');
// var should = require("should");
// var sinon = require("sinon");
// var utils = require("../lib/utils");
describe("utils", function(){
var emptyObj = {};
var nestedObj = {
x: 'x',
y: 'y'
}
var dupsArray = [nestedObj, {z:'z'}, nestedObj];
var reducedDupsArray = [nestedObj, {z:'z'}];
// describe("utils", function(){
// var emptyObj = {};
// var nestedObj = {
// x: 'x',
// y: 'y'
// }
// var dupsArray = [nestedObj, {z:'z'}, nestedObj];
// var reducedDupsArray = [nestedObj, {z:'z'}];
describe("#getTimestamp", function(){
it("should return a valid unix timestamp", function(done){
(function(){
var ts = utils.getTimestamp();
ts.should.be.a('number');
var datetime = new Date(ts);
datetime.should.be.a('object');
}).should.not.throw();
done();
})
})
// describe("#getTimestamp", function(){
// it("should return a valid unix timestamp", function(done){
// (function(){
// var ts = utils.getTimestamp();
// ts.should.be.a('number');
// var datetime = new Date(ts);
// datetime.should.be.a('object');
// }).should.not.throw();
// done();
// })
// })
describe("#clone", function(){
it("should clone a nested object", function(done){
var a = nestedObj;
var b = utils.clone(a);
// describe("#clone", function(){
// it("should clone a nested object", function(done){
// var a = nestedObj;
// var b = utils.clone(a);
assert.deepEqual(a, b);
done();
})
})
// assert.deepEqual(a, b);
// done();
// })
// })
describe("#merge", function(){
it("should", function(done){
var a = emptyObj;
var b = nestedObj;
// describe("#merge", function(){
// it("should", function(done){
// var a = emptyObj;
// var b = nestedObj;
var c = utils.merge(a, b);
assert.deepEqual(a, b);
assert.deepEqual(c, b);
done();
})
})
// var c = utils.merge(a, b);
// assert.deepEqual(a, b);
// assert.deepEqual(c, b);
// done();
// })
// })
describe("#unique", function(){
it("should ensure uniqueness within array of objects based on subkey", function(done){
var a = utils.unique(dupsArray, 'x');
assert.deepEqual(a, reducedDupsArray);
done();
})
})
// describe("#unique", function(){
// it("should ensure uniqueness within array of objects based on subkey", function(done){
// var a = utils.unique(dupsArray, 'x');
// assert.deepEqual(a, reducedDupsArray);
// done();
// })
// })
describe("#map", function(){
it("should convert basic array to existential object", function(done){
var keys = [1,2,3,4];
var a = utils.map(keys);
for(var i in keys){
a[keys[i]].should.equal(true);
}
done();
})
// describe("#map", function(){
// it("should convert basic array to existential object", function(done){
// var keys = [1,2,3,4];
// var a = utils.map(keys);
// for(var i in keys){
// a[keys[i]].should.equal(true);
// }
// done();
// })
it("should convert array of objects to existential object", function(done){
var keys = [{x:1}, {x:2}, {x:3}];
var subkey = 'x';
var a= utils.map(keys, subkey);
for(var i in keys){
a[keys[i][subkey]].should.equal(true);
}
done();
})
})
describe("#checkEmail", function(){
var validEmail = "ehammer@walmart.com",
invalidEmail = "ohai";
// it("should convert array of objects to existential object", function(done){
// var keys = [{x:1}, {x:2}, {x:3}];
// var subkey = 'x';
// var a= utils.map(keys, subkey);
// for(var i in keys){
// a[keys[i][subkey]].should.equal(true);
// }
// done();
// })
// })
// // #checkEmail was removed in 78435467c133416ea03465845b32026365d79bf8
// // describe("#checkEmail", function(){
// // var validEmail = "ehammer@walmart.com",
// // invalidEmail = "ohai";
it("should return false on invalid email", function(done){
utils.checkEmail(invalidEmail).should.equal(false);
done();
})
// // it("should return false on invalid email", function(done){
// // utils.checkEmail(invalidEmail).should.equal(false);
// // done();
// // })
it("should return true on valid email", function(done){
utils.checkEmail(validEmail).should.equal(true);
done();
})
})
// // it("should return true on valid email", function(done){
// // utils.checkEmail(validEmail).should.equal(true);
// // done();
// // })
// // })
describe("#hide", function(){
var objWithHiddenKeys = {
location: {
name: 'San Bruno'
},
company: {
name: "@WalmartLabs"
}
}
// describe("#hide", function(){
// var objWithHiddenKeys = {
// location: {
// name: 'San Bruno'
// },
// company: {
// name: "@WalmartLabs"
// }
// }
it("should delete params with definition's hide set to true", function(done){
var a = utils.hide(objWithHiddenKeys, {location: {hide: true}});
should.not.exist(objWithHiddenKeys.location);
should.exist(objWithHiddenKeys.company);
done();
})
})
// it("should delete params with definition's hide set to true", function(done){
// var a = utils.hide(objWithHiddenKeys, {location: {hide: true}});
// should.not.exist(objWithHiddenKeys.location);
// should.exist(objWithHiddenKeys.company);
// done();
// })
// })
describe("#getRandomString", function(){
it('should return a random string of length 10 by default', function(done){
var a = utils.getRandomString()
a.length.should.equal(10);
done();
})
// describe("#getRandomString", function(){
// it('should return a random string of length 10 by default', function(done){
// var a = utils.getRandomString()
// a.length.should.equal(10);
// done();
// })
it('should return random string of length n for any given n', function(done){
var nArray = [1,2,3,4,6,8,12,20,30];
for(var index in nArray){
var n = nArray[index];
var o = utils.getRandomString(n);
o.length.should.equal(n);
}
done();
})
// it('should return random string of length n for any given n', function(done){
// var nArray = [1,2,3,4,6,8,12,20,30];
// for(var index in nArray){
// var n = nArray[index];
// var o = utils.getRandomString(n);
// o.length.should.equal(n);
// }
// done();
// })
it('should return null if negative size given', function(done){
var a = utils.getRandomString(-10);
should.not.exist(a);
done();
})
// it('should return null if negative size given', function(done){
// var a = utils.getRandomString(-10);
// should.not.exist(a);
// done();
// })
it('should return null if non-numeric size given', function(done){
var sizes = ['a', [1,2,3], {x:1}, 1.45];
for(var i in sizes){
var size = sizes[i];
should.not.exist(utils.getRandomString(size));
}
done();
})
})
// it('should return null if non-numeric size given', function(done){
// var sizes = ['a', [1,2,3], {x:1}, 1.45];
// for(var i in sizes){
// var size = sizes[i];
// should.not.exist(utils.getRandomString(size));
// }
// done();
// })
// })
describe("#encrypt", function(){
// Non-deterministic function, test TBD
})
// describe("#encrypt", function(){
// // Non-deterministic function, test TBD
// })
describe("#decrypt", function(){
// Non-deterministic function, test TBD
})
// describe("#decrypt", function(){
// // Non-deterministic function, test TBD
// })
describe("#exists", function(){
it("should return true for non null, non undefined values", function(done){
var values = [true, 1, "one", [1], {x:1}, function(){ return 1; }];
for(var i in values){
utils.exists(values[i]).should.equal(true);
}
done();
})
})
// // #exists was removed in 78435467c133416ea03465845b32026365d79bf8
// // describe("#exists", function(){
// // it("should return true for non null, non undefined values", function(done){
// // var values = [true, 1, "one", [1], {x:1}, function(){ return 1; }];
// // for(var i in values){
// // utils.exists(values[i]).should.equal(true);
// // }
// // done();
// // })
// // })
describe("#email", function(){
// Function generates side effect, not sure if good to email on EVERY test run
// it("should", function(done){
// hapi.Process.initialize({
// name: "ohai",
// email: {
// admin: "thegoleffect@gmail.com",
// fromName: "Van",
// replyTo: "thegoleffect@gmail.com",
// server: "localhost"
// }
// })
// describe("#email", function(){
// // Function generates side effect, not sure if good to email on EVERY test run
// // it("should", function(done){
// // hapi.Process.initialize({
// // name: "ohai",
// // email: {
// // admin: "thegoleffect@gmail.com",
// // fromName: "Van",
// // replyTo: "thegoleffect@gmail.com",
// // server: "localhost"
// // }
// // })
// utils.email('thegoleffect@gmail.com', 'test', 'ohai', null, function(){
// console.log('sent')
// done();
// })
// })
// // utils.email('thegoleffect@gmail.com', 'test', 'ohai', null, function(){
// // console.log('sent')
// // done();
// // })
// // })
})
})
// })
// })

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