This repository has been archived by the owner on Mar 27, 2024. It is now read-only.
forked from bcgov/common-hosted-email-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
260 lines (227 loc) · 7.29 KB
/
app.js
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
251
252
253
254
255
256
257
258
259
260
const compression = require('compression');
const config = require('config');
const express = require('express');
const moment = require('moment');
const Problem = require('api-problem');
const keycloak = require('./src/components/keycloak');
const log = require('./src/components/log')(module.filename);
const httpLogger = require('./src/components/log').httpLogger;
const { authorizedParty } = require('./src/middleware/authorizedParty');
const v1Router = require('./src/routes/v1');
const DataConnection = require('./src/services/dataConn');
const EmailConnection = require('./src/services/emailConn');
const QueueConnection = require('./src/services/queueConn');
const QueueListener = require('./src/services/queueListener');
const apiRouter = express.Router();
const state = {
connections: {
data: false,
email: true, // Assume SMTP is accessible by default
queue: false
},
mounted: false,
ready: false,
shutdown: false
};
let probeId;
const app = express();
app.use(compression());
app.use(express.json({
limit: config.get('server.bodyLimit')
}));
app.use(express.urlencoded({
extended: false
}));
// Print out configuration settings in verbose startup
log.verbose('Config', { config: config });
// Suppresses warning about moment deprecating a default fallback on non ISO/RFC2822 date formats
// We will just force it to use the new Date constructor - https://stackoverflow.com/a/34521624
moment.createFromInputFallback = config => {
config._d = new Date(config._i);
};
// Instantiate application level connection objects
const dataConnection = new DataConnection();
const queueConnection = new QueueConnection();
const emailConnection = new EmailConnection();
// Skip if running tests
if (process.env.NODE_ENV !== 'test') {
// make sure authorized party middleware loaded before the mail api tracking...
app.use(authorizedParty);
// Initialize connections and exit if unsuccessful
initializeConnections();
app.use(httpLogger);
}
// Use Keycloak OIDC Middleware
app.use(keycloak.middleware());
// Block requests until service is ready and mounted
app.use((_req, res, next) => {
if (state.shutdown) {
new Problem(503, { details: 'Server is shutting down' }).send(res);
} else if (!state.ready || !state.mounted) {
new Problem(503, { details: 'Server is not ready' }).send(res);
} else {
next();
}
});
// GetOK Base API Directory
apiRouter.get('/', (_req, res) => {
res.status(200).json({
endpoints: [
'/api/v1'
],
versions: [
1
]
});
});
// v1 Router
apiRouter.use('/v1', v1Router);
// Root level Router
app.use(/(\/api)?/, apiRouter);
// Handle 500
// eslint-disable-next-line no-unused-vars
app.use((err, _req, res, _next) => {
if (err.stack) {
log.error(err);
}
if (err instanceof Problem) {
// Attempt to reset DB connection if 5xx error
if (err.status >= 500 && !state.shutdown) dataConnection.resetConnection();
err.send(res);
} else {
// Attempt to reset DB connection
if (!state.shutdown) dataConnection.resetConnection();
new Problem(500, {
details: (err.message) ? err.message : err
}).send(res);
}
});
// Handle 404
app.use((_req, res) => {
new Problem(404).send(res);
});
// Prevent unhandled promise 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 5 seconds.
*/
function shutdown() {
log.info('Received kill signal. Shutting down...', { function: 'shutdown' });
queueConnection.pause();
// Wait 5 seconds before starting cleanup
if (!state.shutdown) setTimeout(cleanup, 5000);
}
/**
* @function cleanup
* Cleans up connections in this application.
*/
function cleanup() {
log.info('Service no longer accepting traffic', { function: 'cleanup' });
state.shutdown = true;
log.info('Cleaning up...', { function: 'cleanup' });
clearInterval(probeId);
queueConnection.close(() => {
emailConnection.close(() => {
dataConnection.close(() => {
process.exit();
});
});
});
// Wait 10 seconds max before hard exiting
setTimeout(() => process.exit(), 10000);
}
/**
* @function initializeConnections
* Initializes the database, queue and email connections
* This will force the application to exit if it fails
*/
function initializeConnections() {
// Initialize connections and exit if unsuccessful
try {
const tasks = [
dataConnection.checkAll(),
queueConnection.checkReachable()
];
if (process.env.NODE_ENV == 'production') {
tasks.push(emailConnection.checkConnection());
}
Promise.all(tasks)
.then(results => {
state.connections.data = results[0];
state.connections.queue = results[1];
if (results[2] !== undefined) {
state.connections.email = results[2];
}
})
.catch(error => {
log.error(error.message, { function: 'initializeConnections' });
})
.finally(() => {
log.info(`Connection Statuses: Database = ${state.connections.data}, Queue = ${state.connections.queue}, Email = ${state.connections.email}`, { connections: state.connections, function: 'initializeConnections' });
state.ready = Object.values(state.connections).every(x => x);
mountServices();
});
} catch (error) {
log.error('Connection initialization failure', error.message, { function: 'initializeConnections' });
if (!state.ready) {
process.exitCode = 1;
shutdown();
}
}
// Start periodic 10 second connection probe check
probeId = setInterval(checkConnections, 10000);
}
/**
* @function checkConnections
* Checks Database and Redis connectivity
* This will force the application to exit if a connection fails
*/
function checkConnections() {
const wasMounted = state.mounted;
if (!state.shutdown) {
const tasks = [
dataConnection.checkConnection(),
queueConnection.checkConnection()
];
Promise.all(tasks).then(results => {
state.connections.data = results[0];
state.connections.queue = results[1];
state.ready = Object.values(state.connections).every(x => x);
state.mounted = results[1];
if (!wasMounted && state.mounted && state.ready) log.info('Service ready to accept traffic', { function: 'checkConnections' });
log.verbose('State', { function: 'initializeConnections', state: state });
if (!state.ready) {
process.exitCode = 1;
shutdown();
}
});
}
}
/**
* @function mountServices
* Registers the queue listener workers
*/
function mountServices() {
// Register the listener worker when everything is connected
queueConnection.queue.process(QueueListener.onProcess);
queueConnection.queue.on('completed', QueueListener.onCompleted);
queueConnection.queue.on('error', QueueListener.onError);
queueConnection.queue.on('failed', QueueListener.onFailed);
queueConnection.queue.on('drained', QueueListener.onDrained);
queueConnection.queue.on('removed', QueueListener.onRemoved);
log.verbose('Listener workers attached', { function: 'mountServices' });
}
module.exports = app;