Skip to content
This repository has been archived by the owner on Oct 25, 2023. It is now read-only.

Commit

Permalink
Missing statistics.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Anders Hessellund Jensen committed Apr 8, 2014
1 parent e64dd00 commit 9f89b41
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions statistics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"use strict";

var MA = require('moving-average');
var _ = require('underscore');

var logger = require('./logger');
exports.stats = {};

exports.emit = function(type, value, err, meta) {
if(!meta) {
meta = {};
}
meta.type = type;
meta.value = value;
if(err) {
meta.error = err;
}
if(err) {
logger.info('stat_error', 'measured', meta);
}
else {
logger.info('stat', 'measured', meta);
}
var now = Date.now();
if(!exports.stats[type]) {
exports.stats[type] = {
ma1s: MA(1000),
ma1m: MA(60 * 1000),
ma1h: MA(60 * 60 * 1000),
ma1d: MA(24 * 60 * 60 * 1000),
ma1s_error: MA(1000),
ma1m_error: MA(60 * 1000),
ma1h_error: MA(60 * 60 * 1000),
ma1d_error: MA(24 * 60 * 60 * 1000)
};
}
var stat = exports.stats[type];
if(value) {
stat.lastTime = now;
stat.lastValue = value;
stat.ma1s.push(now, value);
stat.ma1m.push(now, value);
stat.ma1h.push(now, value);
stat.ma1d.push(now, value);
}
if(err) {
stat.lastErrorTime = now;
}
var errval = err ? 0 : 1;
stat.ma1s_error.push(now, errval);
stat.ma1m_error.push(now, errval);
stat.ma1h_error.push(now, errval);
stat.ma1d_error.push(now, errval);
};

exports.getStatistics = function() {
return _.reduce(exports.stats, function(memo, stat, key) {
memo[key] = {
lastTime: new Date(stat.lastTime).toISOString(),
lastValue: stat.lastValue,
lastErrorTime: stat.lastErrorTime ? new Date(stat.lastErrorTime).toISOString() : undefined
};
['ma1s', 'ma1m', 'ma1h', 'ma1d'].forEach(function(ma) {
memo[key][ma] = {
movingAverage: stat[ma].movingAverage(),
variance: stat[ma].variance()
};
});
return memo;
}, {});
};

0 comments on commit 9f89b41

Please sign in to comment.