UNPKG

1.54 kBJavaScriptView Raw
1"use strict"
2
3const SIGUSR2 = "SIGUSR2"
4const SIGTERM = "SIGTERM"
5
6class Runner {
7 constructor(Application, options={}) {
8 this.config = options.config
9 this.signals = options.stopSignals || [SIGUSR2, SIGTERM]
10 this.application = new Application(this.config)
11
12 this.assignListeners()
13 }
14
15 async start() {
16 await this.application.initDependencies()
17 await this.application.start()
18 this.application.logger.debug("Successfully started!")
19 }
20
21 async exit(status=0, signal=SIGTERM, ) {
22 let killTimer = setTimeout(() => {
23 // eslint-disable-next-line no-console
24 console.log("Tired of waiting for gracefull shutdown. Exiting...")
25 process.exit(133)
26 }, 10000)
27
28 try {
29 await this.application.stop()
30 } catch(e) {
31 // eslint-disable-next-line no-console
32 console.log("Error happened during shutdown ", e)
33 process.exit(131)
34 }
35
36 this.removeListeners()
37 clearTimeout(killTimer)
38 if (status === 0) {
39 process.kill(process.pid, signal)
40 } else {
41 process.exit(status)
42 }
43 }
44
45 assignListeners() {
46 process.on("unhandledRejection", (reason, p) => {
47 // eslint-disable-next-line no-console
48 console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason)
49 this.exit(132)
50 })
51
52 this.signals.forEach((signal) => process.on(signal, this.exit.bind(this, 0, signal)))
53 }
54
55 removeListeners() {
56 this.signals.forEach((signal) => process.removeAllListeners(signal))
57 }
58}
59
60module.exports = Runner