-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.ts
65 lines (56 loc) · 1.87 KB
/
index.ts
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
/* SPDX-FileCopyrightText: 2014-present Kriasoft */
/* SPDX-License-Identifier: MIT */
import { applyWSSHandler } from "@trpc/server/adapters/ws";
import { WebSocketServer } from "ws";
import { app } from "./app";
import { logger } from "./core/logging";
import { createWsContext as createContext } from "./core/trpc";
import { router } from "./routes";
// Detect if running in Google Cloud environment
const isCloudRun = !!process.env.K_SERVICE;
/**
* Starts the HTTP and WebSocket servers.
*/
export function listen(port: number) {
const server = app.listen(port, () => {
logger.info(`API listening on ${port}`);
});
const wss = new WebSocketServer({ server, path: "/trpc" });
const handler = applyWSSHandler({ wss, router, createContext });
wss.on("connection", (ws) => {
logger.info({ clients: wss.clients.size }, "wss:connection");
ws.once("close", () => {
logger.info({ clients: wss.clients.size }, "wss:close");
});
});
return function dispose(cb?: () => void) {
handler.broadcastReconnectNotification();
wss.close((err) => {
if (err) logger.error(err);
if (isCloudRun) logger.info("WebSocket server closed");
server.close((err) => {
if (err) logger.error(err);
if (isCloudRun) logger.info("HTTP server closed");
logger.flush((err) => {
if (err) console.error(err);
if (isCloudRun) {
process.exit(0);
} else {
cb?.();
}
});
});
});
};
}
if (process.env.PORT && process.env.K_SERVICE?.startsWith("server")) {
const port = parseInt(process.env.PORT);
const dispose = listen(port);
/* eslint-disable-next-line no-inner-declarations */
function handleClose(code: NodeJS.Signals) {
logger.info(`${code} signal received`);
dispose();
}
process.on("SIGINT", handleClose);
process.on("SIGTERM", handleClose);
}