-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
318 lines (288 loc) · 9.8 KB
/
index.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
const http = require('node:http');
const net = require('node:net');
const process = require('node:process');
const util = require('node:util');
const isPromise = require('p-is-promise');
const HttpTerminator = require('lil-http-terminator');
const debug = util.debuglog('@ladjs/graceful');
class Graceful {
constructor(config) {
this.config = {
servers: [],
brees: [],
redisClients: [],
mongooses: [],
customHandlers: [],
logger: console,
timeoutMs: 5000,
lilHttpTerminator: {},
ignoreHook: 'ignore_hook',
hideMeta: 'hide_meta',
uncaughtExceptionTimeoutMsMs: 100,
...config
};
// noop logger if false
if (this.config.logger === false)
this.config.logger = {
info() {},
warn() {},
error() {}
};
// if lilHttpTerminator does not have a logger set then re-use `this.config.logger`
if (!this.config.lilHttpTerminator.logger)
this.config.lilHttpTerminator.logger = this.config.logger;
// prevent multiple SIGTERM/SIGHUP/SIGINT from firing graceful exit
this._isExiting = false;
//
// create instances of HTTP terminator in advance for faster shutdown
//
for (const server of this.config.servers) {
// backwards compatible support (get the right http or net server object instance)
let serverInstance = server;
if (serverInstance.server instanceof net.Server)
serverInstance = serverInstance.server;
else if (!(serverInstance instanceof net.Server))
throw new Error('Servers passed must be instances of net.Server');
if (serverInstance instanceof http.Server) {
server.terminator = new HttpTerminator({
server: serverInstance,
...this.config.lilHttpTerminator
});
}
}
// bind this to everything
this.listen = this.listen.bind(this);
this.stopServer = this.stopServer.bind(this);
this.stopServers = this.stopServers.bind(this);
this.stopRedisClient = this.stopRedisClient.bind(this);
this.stopRedisClients = this.stopRedisClients.bind(this);
this.stopMongoose = this.stopMongoose.bind(this);
this.stopMongooses = this.stopMongooses.bind(this);
this.stopBree = this.stopBree.bind(this);
this.stopBrees = this.stopBrees.bind(this);
this.stopCustomHandler = this.stopCustomHandler.bind(this);
this.stopCustomHandlers = this.stopCustomHandlers.bind(this);
this.exit = this.exit.bind(this);
}
listen() {
// handle warnings
process.on('warning', (warning) => {
// <https://github.com/pinojs/pino/issues/833#issuecomment-625192482>
warning.emitter = null;
if (this.config.hideMeta)
this.config.logger.warn(warning, { [this.config.hideMeta]: true });
else this.config.logger.warn(warning);
});
// handle uncaught promises
// <https://nodejs.org/api/process.html#event-unhandledrejection>
process.on('unhandledRejection', (err) => {
// we don't want to log here, we want to throw the error
// so that processes exit or bubble up to middleware error handling
// we need to support listening to unhandledRejections (backward compatibility)
// (even though node is deprecating this in future versions)
// <https://developer.ibm.com/blogs/nodejs-15-release-blog/>
throw err;
});
// handle uncaught exceptions
process.once('uncaughtException', (err) => {
if (this.config.hideMeta)
this.config.logger.error(err, { [this.config.hideMeta]: true });
else this.config.logger.error(err);
// artificial timeout to allow logger to store uncaught exception to db
if (this.config.uncaughtExceptionTimeoutMs)
setTimeout(() => {
process.exit(1);
}, this.config.uncaughtExceptionTimeoutMs);
else process.exit(1);
});
// handle windows support (signals not available)
// <http://pm2.keymetrics.io/docs/usage/signals-clean-restart/#windows-graceful-stop>
process.on('message', async (message) => {
if (message === 'shutdown') {
this.config.logger.info('Received shutdown message', {
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
await this.exit();
}
});
// handle graceful restarts
for (const sig of ['SIGTERM', 'SIGHUP', 'SIGINT']) {
process.once(sig, async () => {
await this.exit(sig);
});
}
}
async stopServer(server, code) {
try {
if (server.terminator) {
// HTTP servers
debug('server.terminator');
const { error } = await server.terminator.terminate();
if (error) throw error;
} else if (server.stop) {
// support for `stoppable`
debug('server.stop');
await (isPromise(server.stop)
? server.stop()
: util.promisify(server.stop).bind(server)());
} else if (server.close) {
// all other servers (e.g. SMTP)
debug('server.close');
await (isPromise(server.close)
? server.close()
: util.promisify(server.close).bind(server)());
}
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
}
}
async stopServers(code) {
await Promise.all(
this.config.servers.map((server) => this.stopServer(server, code))
);
}
async stopRedisClient(client, code) {
if (client.status === 'end') return;
try {
await client.disconnect();
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
}
}
async stopRedisClients(code) {
await Promise.all(
this.config.redisClients.map((client) =>
this.stopRedisClient(client, code)
)
);
}
async stopMongoose(mongoose, code) {
try {
await mongoose.disconnect();
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
}
}
async stopMongooses(code) {
await Promise.all(
this.config.mongooses.map((mongoose) => this.stopMongoose(mongoose, code))
);
}
async stopBree(bree, code) {
try {
await bree.stop();
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
}
}
async stopBrees(code) {
await Promise.all(
this.config.brees.map((bree) => this.stopBree(bree, code))
);
}
async stopCustomHandler(handler, code) {
try {
await handler();
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
}
}
stopCustomHandlers(code) {
return Promise.all(
this.config.customHandlers.map((handler) =>
this.stopCustomHandler(handler, code)
)
);
}
async exit(code) {
if (code)
this.config.logger.info('Gracefully exiting', {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
if (this._isExiting) {
this.config.logger.info('Graceful exit already in progress', {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
return;
}
this._isExiting = true;
// give it only X ms to gracefully exit
setTimeout(() => {
this.config.logger.error(
new Error(
`Graceful exit failed, timeout of ${this.config.timeoutMs}ms was exceeded`
),
{
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
}
);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}, this.config.timeoutMs);
try {
await Promise.all([
// servers
this.stopServers(code),
// brees
this.stopBrees(code),
// custom handlers
this.stopCustomHandlers(code)
]);
//
// don't stop redis/mongoose until all other operations have ended
// (a lot of time the server cleanup will release counters/limiters)
// (or the job scheduler or application-layer code will require DB connections)
// (and closing them early may also cause uncaught exceptions)
//
await Promise.all([
// redisClients
this.stopRedisClients(code),
// mongooses
this.stopMongooses(code)
]);
this.config.logger.info('Gracefully exited', {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0);
} catch (err) {
this.config.logger.error(err, {
code,
...(this.config.ignoreHook ? { [this.config.ignoreHook]: true } : {}),
...(this.config.hideMeta ? { [this.config.hideMeta]: true } : {})
});
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
}
}
}
module.exports = Graceful;