forked from Lilly-Protocol/lily-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
67 lines (54 loc) · 1.68 KB
/
Copy pathserver.ts
File metadata and controls
67 lines (54 loc) · 1.68 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
import { createServer } from "node:http";
import { createApp } from "./app";
import { buildInfo } from "./config/build-info";
import { env } from "./config/env";
import { logger } from "./config/logger";
const app = createApp();
const server = createServer(app);
server.listen(env.PORT, () => {
logger.info(
{
appName: env.APP_NAME,
environment: env.NODE_ENV,
...buildInfo,
},
"Lily backend server started with resolved configuration",
);
});
let isShuttingDown = false;
const shutdown = (signal: string) => {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
logger.info({ signal }, "Graceful shutdown started");
// Force close after 10s if connections fail to drain
const forceTimeout = setTimeout(() => {
logger.error("Graceful shutdown timed out, forcing process exit");
process.exit(1);
}, 10_000);
forceTimeout.unref();
// Close idle connections to speed up draining
if (typeof server.closeIdleConnections === "function") {
server.closeIdleConnections();
}
server.close((error) => {
clearTimeout(forceTimeout);
if (error) {
logger.error({ err: error }, "Error while shutting down server");
process.exit(1);
}
logger.info("HTTP server closed");
process.exit(0);
});
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("unhandledRejection", (reason: unknown) => {
logger.fatal({ err: reason }, "Unhandled Promise Rejection detected");
shutdown("unhandledRejection");
});
process.on("uncaughtException", (error: Error) => {
logger.fatal({ err: error }, "Uncaught Exception detected");
shutdown("uncaughtException");
});