forked from bcgov/common-hosted-form-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
220 lines (188 loc) · 7.38 KB
/
Copy pathapp.js
File metadata and controls
220 lines (188 loc) · 7.38 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
208
209
210
211
212
213
214
215
216
217
218
219
220
const compression = require('compression');
const config = require('config');
const express = require('express');
const path = require('node:path');
const Problem = require('api-problem');
const querystring = require('node:querystring');
const qs = require('qs');
const clsRtracer = require('cls-rtracer');
const log = require('./src/components/log')(module.filename);
const httpLogger = require('./src/components/log').httpLogger;
const middleware = require('./src/forms/common/middleware');
const rateLimiter = require('./src/forms/common/middleware').apiKeyRateLimiter;
const v1Router = require('./src/routes/v1');
const webcomponentRouter = require('./src/webcomponents');
const gatewayRouter = require('./src/gateway');
const DataConnection = require('./src/db/dataConnection');
const dataConnection = new DataConnection();
const { eventStreamService } = require('./src/components/eventStreamService');
const clamAvScanner = require('./src/components/clamAvScanner');
const uploadCleanup = require('./src/forms/file/uploadCleanup');
const statusService = require('./src/components/statusService');
statusService.registerConnection('dataConnection', 'Database', dataConnection, 'checkAll', 'checkConnection');
statusService.registerConnection('eventStreamService', 'Event Stream Service', eventStreamService, 'checkConnection', 'checkConnection');
statusService.registerConnection('clamAvScanner', 'Virus Scanner', clamAvScanner, 'checkConnection', 'checkConnection');
const apiRouter = express.Router();
let probeId;
const app = express();
// Configure query parser to use qs for nested query parameters
app.set('query parser', qs.parse);
app.use(compression());
app.use(express.json({ limit: config.get('server.bodyLimit') }));
app.use(express.urlencoded({ extended: true }));
// Express needs to know about the OpenShift proxy. With this setting Express
// pulls the IP address from the headers, rather than use the proxy IP address.
// This gives the correct IP address in the logs and for the rate limiting.
// See https://express-rate-limit.github.io/ERR_ERL_UNEXPECTED_X_FORWARDED_FOR
app.set('trust proxy', 1);
app.set('x-powered-by', false);
// Add correlation ID middleware early in the chain
// useHeader: true - Use existing X-Request-ID header if present, otherwise generate one
// echoHeader: true - Add the request ID to response headers
app.use(clsRtracer.expressMiddleware({ enableRequestId: true, useHeader: true, echoHeader: true }));
// Skip if running tests
if (process.env.NODE_ENV !== 'test') {
// Initialize connections and exit if unsuccessful
// Initialize connections and wait for completion
statusService.initializeAllConnections();
app.use(httpLogger);
if (config.has('files.uploads.cleanup')) {
uploadCleanup.startUploadCleanupScheduler(config.get('files.uploads.cleanup'));
}
}
const statusPath = `${config.get('server.basePath')}${config.get('server.apiPath')}/status`;
// Block requests until service is ready, except for /config and /status
app.use((req, res, next) => {
// Only skip for exact /config or /status
if (req.path === '/config' || req.path === statusPath) {
return next();
}
const status = statusService.getStatus();
if (status.ready) {
next();
} else if (status.stopped) {
new Problem(503, { details: { message: 'Server is shutting down', ...status } }).send(res);
} else {
new Problem(503, { details: { message: 'Server is not ready', ...status } }).send(res);
}
});
app.use(config.get('server.basePath') + config.get('server.apiPath'), rateLimiter);
// Frontend configuration endpoint
apiRouter.get('/config', (_req, res, next) => {
try {
const frontend = config.get('frontend');
// we will need to pass
const uploads = config.get('files.uploads');
const feConfig = { ...frontend, uploads: uploads };
let ess = config.util.cloneDeep(config.get('eventStreamService'));
if (ess) {
delete ess['username'];
delete ess['password'];
feConfig['eventStreamService'] = {
...ess,
};
}
// Slim feature-flag catalog (codes + global enabled only; no allowlists).
if (config.has('features')) {
feConfig['features'] = config.get('features');
}
res.status(200).json(feConfig);
} catch (err) {
next(err);
}
});
// Base API Directory
apiRouter.get('/api', (_req, res) => {
const status = statusService.getStatus();
if (status.stopped) {
throw new Error('Server shutting down');
} else {
res.status(200).json('ok');
}
});
// Host API endpoints
apiRouter.use(config.get('server.apiPath'), v1Router);
app.use(config.get('server.basePath'), apiRouter);
// Host web component endpoints (separate from API) and apply rate limiting
app.use(`${config.get('server.basePath')}/webcomponents`, rateLimiter, webcomponentRouter);
// Host gateway endpoints (separate from API) and apply rate limiting
app.use(`${config.get('server.basePath')}/gateway`, rateLimiter, gatewayRouter);
app.use(middleware.errorHandler);
// Host the static frontend assets
const staticFilesPath = config.get('frontend.basePath');
app.use('/favicon.ico', (_req, res) => {
res.redirect(`${staticFilesPath}/favicon.ico`);
});
app.use(staticFilesPath, express.static(path.join(__dirname, 'frontend/dist')));
// Handle 500
// eslint-disable-next-line no-unused-vars
app.use((err, _req, res, _next) => {
if (err.stack) {
log.error(err);
}
const status = statusService.getStatus();
if (err instanceof Problem) {
// Attempt to reset DB connection if 5xx error
if (err.status >= 500 && !status.stopped) dataConnection.resetConnection();
err.send(res, null);
} else {
// Attempt to reset DB connection
if (!status.stopped) dataConnection.resetConnection();
new Problem(500, 'Server Error', {
detail: err.message ? err.message : err,
}).send(res);
}
});
// Handle 404
app.use((req, res) => {
if (req.originalUrl.startsWith(`${config.get('server.basePath')}/api`)) {
// Return a 404 problem if attempting to access API
new Problem(404, 'Page Not Found', {
detail: req.originalUrl,
}).send(res);
} else {
// Redirect any non-API requests to static frontend with redirect breadcrumb
const query = querystring.stringify({ ...req.query, r: req.path });
res.redirect(`${staticFilesPath}/?${query}`);
}
});
// Prevent unhandled errors from crashing application
process.on('unhandledRejection', (err) => {
if (err && err.stack) {
log.error(err);
}
});
// Graceful shutdown support
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('SIGUSR1', shutdown);
process.on('SIGUSR2', shutdown);
process.on('exit', () => {
log.info('Exiting...');
});
/**
* @function shutdown
* Shuts down this application after at least 3 seconds.
*/
function shutdown() {
log.info('Received kill signal. Shutting down...');
const status = statusService.getStatus();
// Wait 3 seconds before starting cleanup
if (!status.stopped) setTimeout(cleanup, 3000);
}
/**
* @function cleanup
* Cleans up connections in this application.
*/
function cleanup() {
log.info('Service no longer accepting traffic', { function: 'cleanup' });
statusService.stopAll();
log.info('Cleaning up...', { function: 'cleanup' });
clearInterval(probeId);
uploadCleanup.stopUploadCleanupScheduler();
eventStreamService.closeConnection();
dataConnection.close(() => process.exit());
// Wait 10 seconds max before hard exiting
setTimeout(() => process.exit(), 10000);
}
module.exports = app;