turbobreaker
Version:
Exposes circuit breaker metrics through a Hystrix compliant stream
80 lines (60 loc) • 2.15 kB
JavaScript
;
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _http = require('http');
var _http2 = _interopRequireDefault(_http);
var _url = require('url');
require('es6-collections');
var HYSTRIX_STREAM_PATH = '/hystrix.stream';
var clients = new Set();
var noop = function noop() {};
var TurboBreaker = (function () {
function TurboBreaker() {
var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var callback = arguments.length <= 1 || arguments[1] === undefined ? noop : arguments[1];
_classCallCheck(this, TurboBreaker);
if (typeof config === 'function') {
callback = config;
config = {};
}
this.config = config;
this.server = this.createServer(callback);
}
TurboBreaker.prototype.command = function command(data) {
clients.forEach(function (res) {
res.write("data: " + JSON.stringify(data) + "\n\n");
});
};
TurboBreaker.prototype.stop = function stop() {
this.server.close();
};
TurboBreaker.prototype.createServer = function createServer(callback) {
var server = _http2['default'].createServer(function (req, res) {
var path = _url.parse(req.url).path;
if (path === HYSTRIX_STREAM_PATH) {
// Stop the connection from timing out:
req.setTimeout(0);
// Get the client to understand us:
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write("\n");
req.on('close', function () {
clients['delete'](res);
});
clients.add(res);
} else {
// Reject the request:
res.writeHead(404);
res.end();
}
});
server.listen(this.config.port || 8080, callback);
return server;
};
return TurboBreaker;
})();
exports.TurboBreaker = TurboBreaker;