-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (64 loc) · 1.84 KB
/
index.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const fastify = require("fastify");
// You will be able to access the demo on http://localhost:7200
const PROXY_PORT = 7200;
// Just a serial ID to track which server we are using.
let UPSTREAM_ID = 0;
// Reference to the upstream server.
let UPSTREAM_INST;
const createServer = () => {
return fastify({
logger: {
level: "debug",
prettyPrint: true,
},
disableRequestLogging: true,
});
};
const createUpstream = async () => {
const srv = createServer();
const id = ++UPSTREAM_ID;
console.log(`Upstream [${id}] starting`);
srv.get("/", (req, rep) => {
console.log(`Upstream [${id}] serving [${req.id}]`);
rep.statusCode = 200;
rep.send({
instanceId: id,
from: "upstream",
});
});
srv.addHook("onClose", () => {
console.log(`Upstream [${id}] closed`);
});
await srv.listen(0);
console.log(`Upstream [${id}] started`);
// Upstream already running, will serve the active keep alive connections before switching
if (UPSTREAM_INST) {
UPSTREAM_INST.close();
}
// Swap instance, server new request from the new instance.
UPSTREAM_INST = srv;
};
(async () => {
const proxy = createServer();
proxy.all("/*", (req, rep) => {
console.log("Proxy serving fallback until the first upstream is ready...");
rep.statusCode = 503;
rep.send({
from: "proxy",
status: "waiting for upstream",
onPort: PROXY_PORT,
});
});
proxy.addHook("onRequest", (req, rep, done) => {
// Upstream is ready to accept
if (UPSTREAM_INST) {
console.log("Proxy passing request to upstream", req.id);
UPSTREAM_INST.routing(req.raw, rep.hijack().raw);
}
done();
});
await proxy.listen(PROXY_PORT, "0.0.0.0");
await createUpstream();
// DEMO starting new upstream server every 5 second
setInterval(() => createUpstream(), 5_000);
})();