http-alive
Version:
keep your web service always online
57 lines (56 loc) • 1.93 kB
JavaScript
;
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const http = __importStar(require("http"));
const http_proxy_lite_1 = require("http-proxy-lite");
const util_1 = require("./util");
const port = process.env.PORT;
const proxy = http_proxy_lite_1.createProxyServer();
const endpoints = [
{ url: `http://localhost:${process.env.MASTER_PORT}`, healthy: true, fall: 0 },
{ url: `http://localhost:${process.env.SLAVE_PORT}`, healthy: true, fall: 0 }
];
http
.createServer((req, res) => {
const ep1 = util_1.sample(endpoints.filter(e => e.healthy));
if (!ep1) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
proxy
.web(req, res, { target: ep1.url })
.on('error', e => {
console.error(e);
ep1.healthy = false;
ep1.fall++;
setTimeout(() => {
ep1.healthy = true;
}, 10 * 1000 * ep1.fall);
const ep2 = endpoints.find(e => e.url !== ep1.url);
proxy
.web(req, res, { target: ep2.url })
.on('error', e => {
console.error(e);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
})
.on('end', () => {
ep2.fall = 0;
});
})
.on('end', () => {
ep1.fall = 0;
});
})
.listen(port);
console.log(`Listening on http://localhost:${port} ..`);
process.on('uncaughtException', err => {
console.error('uncaughtException:', err);
});