/
server.ts
250 lines (225 loc) · 6.42 KB
/
server.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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import "./server/init-sentry.js";
import fastifyStart from "fastify";
import fastifyStatic from "@fastify/static";
import next from "next";
import {
handlerAPIDocsBuild,
handlerAPIDocsPoll,
handlerAPIDocsTrigger,
handlerDocsHTML,
} from "./server/package";
import path from "path";
import { docsRootPath } from "./server/package/utils";
import { createBullBoard } from "@bull-board/api";
import { BullMQAdapter } from "@bull-board/api/bullMQAdapter";
import { FastifyAdapter } from "@bull-board/fastify";
import { allQueues } from "./server/queues";
import {
CustomError,
PackageNotFoundError,
PackageVersionMismatchError,
} from "./server/package/CustomError";
import logger from "./common/logger";
import fastifyBasicAuth from "@fastify/basic-auth";
import "dotenv/config";
import heapdump from "heapdump";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
const fastify = fastifyStart({
logger: {
transport: {
target: "pino-pretty",
options: {
translateTime: "HH:MM:ss Z",
ignore: "pid,hostname",
},
},
level: "warn",
},
});
const app = next({ dev, hostname, port });
const nextHandle = app.getRequestHandler();
const queueDashboardAdapter = new FastifyAdapter();
createBullBoard({
queues: allQueues.map((queue) => new BullMQAdapter(queue)),
serverAdapter: queueDashboardAdapter,
});
queueDashboardAdapter.setBasePath("/queue/ui");
app
.prepare()
.then(() => {
fastify.register(fastifyStatic, {
root: docsRootPath,
index: ["index.html"],
redirect: false,
allowedPath: (pathName) => {
if (pathName.includes("..")) {
return false;
}
return true;
},
extensions: ["html", "js", "css"],
list: false,
// list: {
// format: "html",
// render: (dirs, files) => {
// return `
// <html>
// <head>
// <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/yegor256/tacit@gh-pages/tacit-css-1.6.0.min.css"/>
// </head>
// <body>
//
// <ul>
// ${dirs
// .map(
// (dir) =>
// `<li><a href="${`/docs/` + dir.href}">${dir.name}</a></li>`,
// )
// .join("\n ")}
// </ul>
// <ul>
// ${files
// .map(
// (file) =>
// `<li><a href="${"/docs" + file.href}">${
// file.name
// }</a></li>`,
// )
// .join("\n ")}
// </ul>
// </body></html>
// `;
// },
// },
serve: false,
});
fastify.register(fastifyBasicAuth, {
validate(username, password, _req, reply, done) {
if (
username === "tsdocs" &&
password === process.env["TSDOCS_PASSWORD"]
) {
done();
} else {
reply.status(401).send("Unauthorized");
}
},
authenticate: true,
});
fastify.register(fastifyStatic, {
root: path.join(__dirname, "shared-dist"),
redirect: true,
prefix: "/shared-dist/",
allowedPath: (pathName) => {
if (pathName.includes("..")) {
return false;
}
return true;
},
extensions: ["js", "css"],
list: false,
serve: true,
decorateReply: false,
cacheControl: false,
});
queueDashboardAdapter.setBasePath("/queue/ui");
fastify.register(queueDashboardAdapter.registerPlugin(), {
basePath: "/",
prefix: "/queue/ui",
});
fastify.route({
method: "POST",
url: `/api/docs/trigger/*`,
handler: handlerAPIDocsTrigger,
});
fastify.route({
method: "POST",
url: `/api/docs/build/*`,
handler: handlerAPIDocsBuild,
});
fastify.setErrorHandler(function (error, request, reply) {
logger.error(error);
if (error instanceof CustomError) {
const payload = {
name: error.name,
extra: error.extra,
};
switch (error.name) {
case PackageVersionMismatchError.name:
case PackageNotFoundError.name:
reply.status(404).send(payload);
break;
default:
reply.status(500).send(payload);
}
}
reply.status(500).send(error);
});
fastify.route({
method: "GET",
url: `/api/docs/poll/*`,
handler: async (request, reply) => {
return handlerAPIDocsPoll(request, reply);
},
});
fastify.route({
method: "GET",
url: `/docs/*`,
handler: async (request, reply) => {
return handlerDocsHTML(request, reply);
},
});
fastify.setNotFoundHandler((request, reply) =>
nextHandle(request.raw, reply.raw),
);
fastify.addHook("onRequest", (req, reply, next) => {
if (
!req.url.startsWith("/queue/ui") ||
!process.env["BULL_MQ_DASHBOARD_KEY"]
) {
return next();
}
fastify.basicAuth(req, reply, function (error) {
if (!error) {
return next();
}
if (error.name === "FastifyError") {
reply.redirect(401, "/queue/ui");
}
reply.code(500).send({ error: error.message });
});
});
// Run the server!
const start = async () => {
try {
await fastify.listen({ port });
console.log("Server started at ", `http://localhost:${port}`);
console.log("Queue UI at ", `http://localhost:${port}/queue/ui`);
// For PM2 to know that our server is up
if (process.send) process.send("ready");
} catch (err) {
console.error("server threw error on startup: ", err);
fastify.log.error(err);
process.exit(1);
}
};
start();
})
.catch((err) => {
console.log("Failed to prepare app with error: ", err);
});
// Set your memory limit (in bytes)
const memoryLimit = 1 * 1024 * 1024 * 1024; // 1 GB
let heapDumped = false;
setInterval(function () {
if (heapDumped) return;
const heapUsed = process.memoryUsage().heapUsed;
if (heapUsed > memoryLimit) {
require("fs").mkdirSync("./heapdumps", { recursive: true });
heapdump.writeSnapshot("./heapdumps/" + Date.now() + ".heapsnapshot");
console.log("Memory limit exceeded... writing heapdump");
heapDumped = true;
}
}, 5000);