Skip to content

Instantly share code, notes, and snippets.

@stevenleeg
Created August 8, 2013 19:59
Show Gist options
  • Save stevenleeg/6188161 to your computer and use it in GitHub Desktop.
Save stevenleeg/6188161 to your computer and use it in GitHub Desktop.
var EventEmitter = require('events').EventEmitter;
var redis = require("redis");
var StatManager = function() {
var self = this;
self._data_handlers = [];
self._listeners = {};
self.stats = {};
self.aggregate_interval = undefined;
self.redis = redis.createClient();
/*
* Called by the stat object when the data its data is ready to be sent
*/
self.sendUpdate = function(name, data) {
self.emit("statUpdate", name, data);
}
/*
* Registers a listener object
*/
self.registerDataHandler = function(data_handler) {
self._data_handlers.push(data_handler);
}
/*
* Registers an event type
*/
self.registerStat = function(Stat) {
var stat = new Stat(self.sendUpdate);
stat.stats.forEach(function(name) {
self.stats[name] = stat;
});
if(stat.listeners) {
for(var name in stat.listeners) {
self.on("data:" + name, stat.listeners[name]);
}
}
if(stat.onSync) {
stat.onSync();
}
// Setup refresh rate
if(stat.sync_interval != 0 && stat.sync_interval != undefined) {
stat.interval_id = setInterval(stat.onSync, stat.sync_interval * 1000);
}
};
/*
* Called by listener objects every time there is an event
*/
self.onData = function(name, data) {
self.emit("data:" + name, data);
}
self.getData = function(name, callback) {
return self.stats[name].getData(name, callback);
}
/*
* Handle aggregation
*/
//self.aggregate_interval = setInterval(function() {
self.aggregate_interval = setTimeout(function() {
var now = new Date;
//if(now.getHours() == 0 && now.getMinutes() == 0) {
self.aggregateAllStats();
//}
}, 100);
self.aggregateAllStats = function() {
var now = new Date;
var today_stamp = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
for(var name in self.stats) {
if(self.stats[name].aggregators == undefined
|| self.stats[name].aggregators[name] == undefined) {
continue;
}
self.stats[name].aggregators[name](function(data) {
self._completeAggregate(today_stamp, name, data);
});
}
}
// TODO: Make this work for more than just numbers?
self._completeAggregate = function(today_stamp, name, data) {
self.redis.hset("agg:" + today_stamp, name, data);
}
};
StatManager.prototype.__proto__ = EventEmitter.prototype;
// Create a new instance to be used throughout the app
exports.StatManager = new StatManager();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment