CartoDB-SQL-API/lib/stats/client.js

74 lines
2.9 KiB
JavaScript
Raw Normal View History

2018-10-24 21:42:33 +08:00
'use strict';
2017-03-30 22:13:17 +08:00
var _ = require('underscore');
var debug = require('debug')('windshaft:stats_client');
var StatsD = require('node-statsd').StatsD;
module.exports = {
/**
* Returns an StatsD instance or an stub object that replicates the StatsD public interface so there is no need to
* keep checking if the stats_client is instantiated or not.
*
* The first call to this method implies all future calls will use the config specified in the very first call.
*
* TODO: It's far from ideal to use make this a singleton, improvement desired.
* We proceed this way to be able to use StatsD from several places sharing one single StatsD instance.
*
* @param config Configuration for StatsD, if undefined it will return an stub
* @returns {StatsD|Object}
*/
2019-12-24 01:19:08 +08:00
getInstance: function (config) {
2017-03-30 22:13:17 +08:00
if (!this.instance) {
var instance;
if (config) {
instance = new StatsD(config);
instance.last_error = { msg: '', count: 0 };
instance.socket.on('error', function (err) {
2019-12-27 00:46:27 +08:00
var lastErr = instance.last_error;
var lastMsg = lastErr.msg;
var thisMsg = '' + err;
if (thisMsg !== lastMsg) {
2019-12-24 01:19:08 +08:00
debug('statsd client socket error: ' + err);
2017-03-30 22:13:17 +08:00
instance.last_error.count = 1;
2019-12-27 00:46:27 +08:00
instance.last_error.msg = thisMsg;
2017-03-30 22:13:17 +08:00
} else {
2019-12-27 00:46:27 +08:00
++lastErr.count;
if (!lastErr.interval) {
2017-03-30 22:13:17 +08:00
instance.last_error.interval = setInterval(function () {
var count = instance.last_error.count;
if (count > 1) {
2019-12-24 01:19:08 +08:00
debug('last statsd client socket error repeated ' + count + ' times');
2017-03-30 22:13:17 +08:00
instance.last_error.count = 1;
clearInterval(instance.last_error.interval);
instance.last_error.interval = null;
}
}, 1000);
}
}
});
} else {
var stubFunc = function (stat, value, sampleRate, callback) {
if (_.isFunction(callback)) {
callback(null, 0);
}
};
instance = {
timing: stubFunc,
increment: stubFunc,
decrement: stubFunc,
gauge: stubFunc,
unique: stubFunc,
set: stubFunc,
sendAll: stubFunc,
send: stubFunc
};
}
this.instance = instance;
}
return this.instance;
}
2018-10-24 21:42:33 +08:00
};