service-router
Version:
router to bounce requests to either api or web servers
84 lines (74 loc) • 2.57 kB
JavaScript
/**
* Manages the all the various servers that make up the docparse
* infastructor. When a new api server spins up, it connects to this seaport
* instance on the port specificed by "seaport_list_port" in config.js. Then
* when a new api request comes in, this module can bounce it to any server in a
* round-robin fashion
*
* A possible future optimization would be to put in additional routing logic to
* bouncy to better utilize server resources. Right now we just pick a server at random
*
* @Author Noah Isaacson
*/
var inspect = require('eyespect').inspector();
var seaport = require('seaport');
var performBounce = require('./lib/performBounce');
var serviceDown = require('./lib/serviceDown');
var bouncy = require('bouncy');
var url = require('url');
module.exports = function(config) {
var seaport_port = config.get('seaport:port');
inspect(seaport_port, 'seaport listening on port')
var server = seaport.createServer();
server.listen(seaport_port);
var apiOnline = false;
var webOnline = false;
server.on('register', function (service) {
var role = service.role;
if (role === 'web') {
webOnline = true;
}
if (role === 'api') {
apiOnline = true;
}
if (apiOnline && webOnline) {
if (process.send) {
process.send('listening');
return;
}
}
});
// Bounce Requests to the appropiate server
var bouncy_port = config.get('application:port');
bouncy(function(req, res, bounce) {
var parts = url.parse(req.url);
var urlPath = parts.path
var service = 'web';
var apiPattern = /^\/api/;
if (apiPattern.test(urlPath)) {
service = 'api'
}
var servicePattern = /^\/static/;
if (servicePattern.test(urlPath)) {
service = 'static'
}
var ps = server.query(service);
// inspect({service: service, req_headers: req.headers}, 'bouncing for service');
// no servers available for the given service
if (ps.length === 0) {
inspect(service, 'no servers available');
return serviceDown(req, res, bounce, service);
}
inspect(urlPath, 'bouncing to service: ' + service + ' for url')
// bounce api request to a random server registered with seaport
var serverIndex = ps[Math.floor(Math.random()*ps.length)];
inspect(serverIndex, 'bouncing now')
var host = serverIndex.host;
var port = serverIndex.port;
inspect(host,'host')
inspect(port,'port')
bounce(host, port)
}).listen(bouncy_port)
inspect(bouncy_port, 'application listening on port');
return server;
}