-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlb.js
More file actions
executable file
·66 lines (57 loc) · 1.65 KB
/
lb.js
File metadata and controls
executable file
·66 lines (57 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#! /usr/bin/env node
const Server = require("./server");
const { roundRobin, performHealthCheck } = require("./utils");
class LoadBalancer extends Server {
constructor(port) {
super(port);
this.backendServerPorts = [8080, 8081, 8082];
this.healthyServerPorts = [];
this.performHealthCheck();
this.choice;
this.handleRequest();
}
handleRequest() {
this.server.on("request", async (req, res) => {
// choose backend server
this.choice = roundRobin(this.healthyServerPorts.length, this.choice);
/** forward request to backend server */
await this.forwardRequest(this.healthyServerPorts[this.choice], req, res);
});
}
async forwardRequest(port, req, res) {
// make request to backend server using the
// same request made to loadBalancer
const response = await fetch(
`http://${this.hostname}:${port}${req.url}`,
req
);
console.log(
`\nResponse from server: HTTP/${req.httpVersion} ${response.status} ${response.statusText}`
);
const serverRes = await response.text();
console.log(`\n${serverRes}`);
res
.writeHead(response.status, {
"Content-Type": "text/plain",
})
.end(serverRes);
}
performHealthCheck() {
performHealthCheck(
this.backendServerPorts,
this.healthyServerPorts,
this.hostname
);
// seconds
const healthCheckPeriod = +process.argv[process.argv.length - 1] || 10;
//periodic health checks
setInterval(
performHealthCheck,
1000 * healthCheckPeriod,
this.backendServerPorts,
this.healthyServerPorts,
this.hostname
);
}
}
new LoadBalancer(3000);