-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
64 lines (52 loc) · 1.78 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
const duration = require('parse-duration');
const format = require('util').format;
const signals = ['SIGINT', 'SIGTERM'];
module.exports = (system, options = {}) => {
if (!system) throw new Error('system is required');
const config = Object.assign({ restart: { window: '60s' } }, options);
const logger = options.logger || console;
let timeout;
const start = (cb) => {
system.start((err, components) => {
if (err) return cb(err);
const scheduleRestart = () => {
const delay = Math.ceil((Math.random() * duration(config.restart.window)) / 1000) * 1000;
logger.info(format('Service will restart in %s seconds.', delay / 1000));
clearTimeout(timeout);
timeout = setTimeout(() => {
system.restart((err) => {
if (err) {
logger.error('Error restarting system.');
logger.error(err);
process.exit(1);
}
});
}, delay);
timeout.unref();
};
process.on('systemic_restart', scheduleRestart);
process.on('error', (err) => {
logger.error('Unhandled error. Invoking shutdown.');
if (err) logger.error(err.stack);
system.stop(() => process.exit(1));
});
process.on('unhandledRejection', (err) => {
logger.error('Unhandled rejection. Invoking shutdown.');
if (err) logger.error(err.stack);
system.stop(() => process.exit(1));
});
signals.forEach((signal) => {
process.on(signal, () => {
logger.info(format('Received %s. Attempting to shutdown gracefully.', signal));
system.stop(() => process.exit(0));
});
});
cb(null, components);
});
};
const stop = (cb) => system.stop(cb);
return {
start,
stop,
};
};