-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
167 lines (145 loc) · 3.91 KB
/
server.js
File metadata and controls
167 lines (145 loc) · 3.91 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
const express = require("express");
const http = require("http");
const { Server } = require("ws");
const { wsListener } = require("./controllers/websocket.js");
const routes = require("./routes/api");
const {
connectMongo,
disconnectMongo,
runMandatoryStartupTasks,
validateConfig,
onMongoConnected,
onMongoDisconnected,
onMongoError,
} = require("./scripts/bootstrap");
const startupState = require("./scripts/startupState");
require("dotenv").config();
validateConfig();
startupState.markPhase("bootstrapping");
const app = express()
.use(express.json({ limit: "100kb" }))
.get("/health/liveness", (req, res) => {
res.status(200).json({
status: "alive",
state: startupState.cloneState(),
});
})
.get("/health/readiness", (req, res) => {
const state = startupState.cloneState();
res.status(state.ready ? 200 : 503).json({
status: state.ready ? "ready" : "not_ready",
state,
});
})
.use("/public", express.static(process.cwd() + "/public")) //make public static
.use((req, res, next) => {
if (startupState.cloneState().ready) {
return next();
}
return res.status(503).json({
error: "Service unavailable",
details: "Application is still bootstrapping dependencies",
});
})
.use("/", routes);
const server = http.createServer(app);
let shuttingDown = false;
let websocketServer = null;
const listen = () =>
new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(process.env.PORT || 3000, () => {
server.off("error", reject);
console.log(`Listening on ${server.address().port}`);
resolve();
});
});
const closeWebsocketServer = () =>
new Promise((resolve) => {
if (!websocketServer) {
resolve();
return;
}
websocketServer.close(() => resolve());
});
const closeServer = () =>
new Promise((resolve, reject) => {
if (!server.listening) {
resolve();
return;
}
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const shutdown = async (reason, error) => {
if (shuttingDown) {
return;
}
shuttingDown = true;
startupState.markPhase("shutting_down");
startupState.setReady(false);
if (error) {
startupState.setLastError(error);
console.error(`${reason}:`, error);
} else {
console.log(reason);
}
try {
await closeWebsocketServer();
await closeServer();
await disconnectMongo();
} finally {
process.exit(error ? 1 : 0);
}
};
const bootstrap = async () => {
try {
await connectMongo();
await runMandatoryStartupTasks();
if (!websocketServer) {
websocketServer = new Server({ server });
wsListener(websocketServer);
}
startupState.markPhase("ready");
startupState.setReady(true);
} catch (error) {
startupState.setLastError(error);
startupState.markPhase("failed");
await shutdown("Startup failure", error);
}
};
onMongoConnected(() => {
startupState.setMongoConnected(true);
const { phase } = startupState.cloneState();
if (!shuttingDown && (phase === "ready" || phase === "degraded")) {
startupState.markPhase("ready");
startupState.setReady(true);
}
});
onMongoDisconnected(() => {
startupState.setMongoConnected(false);
if (!shuttingDown) {
startupState.markPhase("degraded");
startupState.setReady(false);
}
});
onMongoError((error) => {
startupState.setLastError(error);
});
process.on("SIGINT", () => shutdown("Received SIGINT"));
process.on("SIGTERM", () => shutdown("Received SIGTERM"));
process.on("unhandledRejection", (reason) => {
const error = reason instanceof Error ? reason : new Error(String(reason));
shutdown("Unhandled promise rejection", error);
});
process.on("uncaughtException", (error) => {
shutdown("Uncaught exception", error);
});
listen()
.then(bootstrap)
.catch((error) => shutdown("Failed to bind HTTP server", error));