-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.ts
More file actions
188 lines (164 loc) · 5.72 KB
/
Copy pathserver.ts
File metadata and controls
188 lines (164 loc) · 5.72 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import "dotenv/config";
import { Pool } from "./pool";
import * as http from "http";
import httpProxy from "http-proxy";
import ejs from "ejs";
import fs from "fs/promises";
import path from "path";
import { contentType, sleep } from "./util";
import gracefulShutdown from "http-graceful-shutdown";
import { entryPath, installURL, serverPort, sessionTime, showEntry, websiteName } from "./config";
// Catch unexpected errors here
let unexpectedErrorHandler = (error : unknown) => {
console.trace(error);
};
process.addListener("unhandledRejection", unexpectedErrorHandler);
process.addListener("uncaughtException", unexpectedErrorHandler);
const pool = new Pool();
const proxy = httpProxy.createProxyServer();
await pool.clearInstance();
const server = http.createServer(async (req, res) => {
try {
await requestHandler(req, res);
} catch (e) {
console.error(e);
res.writeHead(500);
res.end("Internal server error");
}
});
console.log(`Listening on port ${serverPort}`);
server.listen(serverPort);
gracefulShutdown(server, {
signals: "SIGINT SIGTERM",
timeout: 30000, // timeout: 30 secs
development: false, // not in dev mode
forceExit: true, // triggers process.exit() at the end of shutdown process
onShutdown: shutdownFunction, // shutdown function (async) - e.g. for cleanup DB, ...
finally: finalFunction, // finally function (sync) - e.g. for logging
});
/**
* Get session ID from cookie
* @param req
*/
function getSessionID(req : http.IncomingMessage) {
let cookieList = req.headers.cookie?.split(";") || [];
let sessionID = "";
for (let cookie of cookieList) {
let [ key, value ] = cookie.split("=");
if (key.trim() === "session-id") {
sessionID = value.trim();
}
}
return sessionID;
}
async function requestHandler(req : http.IncomingMessage, res : http.ServerResponse) {
if (!req.url) {
res.end("No url");
return;
}
// Handle request
if (req.url === "/") {
let sessionID = getSessionID(req);
let target = pool.getServiceURL(sessionID);
// If a session is found, proxy it
if (sessionID && target) {
await proxyWeb(req, res);
} else {
// Redirect to "/start"
res.writeHead(302, {
"Location": "/start-demo",
});
res.end();
}
} else if (req.url === "/start-demo" || req.url === "/start-demo") {
res.writeHead(200, { "Content-Type": "text/html" });
let indexTemplate = ejs.render(await fs.readFile("./views/index.ejs", "utf-8"), {
websiteName,
installURL,
autoStart: !showEntry,
entryPath,
});
res.end(indexTemplate);
} else if (req.url.startsWith("/demo-kuma/")) {
if (req.url === "/demo" || req.url === "/demo-kuma/") {
res.writeHead(200, { "Content-Type": "text/html" });
let indexTemplate = ejs.render(await fs.readFile("./views/index.ejs", "utf-8"), {
websiteName,
installURL,
autoStart: !showEntry,
entryPath,
});
res.end(indexTemplate);
} else if (req.url === "/demo-kuma/start-instance") {
try {
let { endSessionTime, sessionID } = await pool.startInstance();
res.writeHead(200, {
"Content-Type": "application/json",
"Set-Cookie": `session-id=${sessionID}; Max-Age=${sessionTime}; Path=/;`
});
res.end(JSON.stringify({
ok: true,
sessionID,
endSessionTime,
}));
} catch (e) {
console.error(e);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({
ok: false,
}));
}
} else if (req.url === "/demo-kuma/validate-session") {
let sessionID = getSessionID(req);
res.writeHead(200, {
"Content-Type": "application/json",
});
res.end(JSON.stringify({
ok: pool.sessionList[sessionID] !== undefined,
}));
} else {
try {
let data = await fs.readFile(path.join("./public", req.url));
res.writeHead(200, { "Content-Type": contentType(req.url) });
res.end(data);
} catch (e) {
res.writeHead(404);
res.end("Not found");
}
}
} else {
await proxyWeb(req, res);
}
}
async function proxyWeb(req : http.IncomingMessage, res : http.ServerResponse, retryCount = 0) {
// Get the sessionID from cookie
let sessionID = getSessionID(req);
let target = pool.getServiceURL(sessionID);
if (sessionID && target) {
proxy.web(req, res, {
target,
}, async (err) => {
if (retryCount <= 10) {
await sleep(2000);
await proxyWeb(req, res, retryCount + 1);
} else {
res.writeHead(500);
res.end("Unable to connect to the instance");
}
});
} else {
res.writeHead(404);
res.end("Session not found");
}
}
async function shutdownFunction(signal : string | undefined) {
console.info("Shutdown requested");
console.info("server", "Called signal: " + signal);
await pool.clearInstance();
}
/**
* Final function called before application exits
*/
function finalFunction() {
console.info("Graceful shutdown successful!");
}