-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.js
More file actions
207 lines (185 loc) · 6.16 KB
/
app.js
File metadata and controls
207 lines (185 loc) · 6.16 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* The application entry point
*/
require("./app-bootstrap");
const _ = require("lodash");
const config = require("config");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const HttpStatus = require("http-status-codes");
const logger = require("./src/common/logger");
// Global error and signal handlers to improve crash visibility.
// Note: SIGSEGV cannot be handled in userland, but these cover other fatal cases.
process.on("uncaughtException", (err) => {
try {
logger.error("Uncaught exception:", err);
if (process.report && typeof process.report.writeReport === "function") {
const reportPath = process.report.writeReport();
if (reportPath) logger.error(`Diagnostic report written: ${reportPath}`);
}
} finally {
// Exit to avoid undefined state after an unhandled exception
process.exit(1);
}
});
process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled rejection:", { reason, promise });
try {
if (process.report && typeof process.report.writeReport === "function") {
const reportPath = process.report.writeReport();
if (reportPath) logger.error(`Diagnostic report written: ${reportPath}`);
}
} catch (_) {}
});
const interceptor = require("express-interceptor");
const fileUpload = require("express-fileupload");
const YAML = require("yamljs");
const swaggerUi = require("swagger-ui-express");
const challengeAPISwaggerDoc = YAML.load("./docs/swagger.yaml");
const { withAuthMetadata } = require("./src/common/swagger");
const challengeAPIWithAuthDoc = withAuthMetadata(challengeAPISwaggerDoc);
const { ForbiddenError } = require("./src/common/errors");
const { getClient } = require("./src/common/prisma");
// setup express app
const app = express();
// Use extended query parsing so bracket syntax like types[]=F2F is handled as arrays
app.set("query parser", "extended");
// Disable POST, PUT, PATCH, DELETE operations if READONLY is set to true
app.use((req, res, next) => {
if (config.READONLY === true && ["POST", "PUT", "PATCH", "DELETE"].includes(req.method)) {
throw new ForbiddenError("Action is temporarely not allowed!");
}
next();
});
// serve challenge API swagger definition with auth metadata
app.use(
"/v6/challenges/api-docs",
swaggerUi.serveFiles(challengeAPIWithAuthDoc),
swaggerUi.setup(challengeAPIWithAuthDoc, { explorer: true })
);
app.use(
cors({
origin: "*",
exposedHeaders: [
"X-Prev-Page",
"X-Next-Page",
"X-Page",
"X-Per-Page",
"X-Total",
"X-Total-Pages",
"Link",
],
})
);
app.use(
fileUpload({
limits: { fileSize: config.FILE_UPLOAD_SIZE_LIMIT },
})
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set("port", config.PORT);
// intercept the response body from jwtAuthenticator
app.use(
interceptor((req, res) => {
return {
isInterceptable: () => {
return res.statusCode === 403;
},
intercept: (body, send) => {
let obj;
try {
obj = JSON.parse(body);
} catch (e) {
logger.error("Invalid response body.");
}
if (obj && obj.result && obj.result.content && obj.result.content.message) {
const ret = { message: obj.result.content.message };
res.statusCode = 401;
send(JSON.stringify(ret));
} else {
send(body);
}
},
};
})
);
// Register routes
require("./app-routes")(app);
// The error handler
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
logger.logFullError(err, req.signature || `${req.method} ${req.url}`);
const errorResponse = {};
let status = err.isJoi
? HttpStatus.BAD_REQUEST
: err.httpStatus || _.get(err, "response.status") || HttpStatus.INTERNAL_SERVER_ERROR;
// Check if err is a GrpcError
if (err.details != null && err.code != null) {
status = err.code == 5 ? HttpStatus.NOT_FOUND : HttpStatus.BAD_REQUEST; // TODO: Use @topcoder-framework/lib-common to map GrpcError codes to HTTP codes
errorResponse.code = err.code;
errorResponse.message = err.details;
}
if (_.isArray(err.details)) {
if (err.isJoi) {
_.map(err.details, (e) => {
if (e.message) {
if (_.isUndefined(errorResponse.message)) {
errorResponse.message = e.message;
} else {
errorResponse.message += `, ${e.message}`;
}
}
});
}
}
if (_.get(err, "response.status")) {
// extra error message from axios http response(v4 and v5 tc api)
errorResponse.message =
_.get(err, "response.data.result.content.message") || _.get(err, "response.data.message");
}
if (_.isUndefined(errorResponse.message)) {
if (err.message && status !== HttpStatus.INTERNAL_SERVER_ERROR) {
errorResponse.message = err.message;
} else {
errorResponse.message = "Internal server error";
}
}
res.status(status).json(errorResponse);
});
const server = app.listen(app.get("port"), () => {
logger.info(`Express server listening on port ${app.get("port")}`);
});
// Graceful shutdown: close HTTP server and disconnect Prisma
const prisma = getClient();
const gracefulShutdown = (signal) => {
try {
logger.info(`[${signal}] Received. Starting graceful shutdown...`);
// Stop accepting new connections
server.close(async () => {
logger.info("HTTP server closed. Disconnecting Prisma...");
try {
await prisma.$disconnect();
logger.info("Prisma disconnected. Exiting.");
} catch (err) {
logger.error("Error during Prisma disconnect:", err);
} finally {
process.exit(0);
}
});
// Fallback: force exit if shutdown takes too long
const timeout = setTimeout(() => {
logger.error("Forced shutdown due to timeout.");
process.exit(1);
}, 10000);
// Don't keep the process alive solely for the timeout
timeout.unref();
} catch (err) {
logger.error("Unexpected error during graceful shutdown:", err);
process.exit(1);
}
};
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
module.exports = app;