|
| 1 | +import Client from '../../server' |
| 2 | +import { fatallyLogAndExitGracefully } from '../util' |
| 3 | + |
| 4 | +export default class ShutdownMonitor { |
| 5 | + |
| 6 | + // SIGTERM is raised by AWS Lambda when the function is being shut down |
| 7 | + // SIGINT is raised by the user pressing CTRL+C |
| 8 | + private static KILL_SIGNALS = ['SIGTERM', 'SIGINT'] as const |
| 9 | + |
| 10 | + protected __isReporting: boolean |
| 11 | + protected __client: typeof Client |
| 12 | + protected __listener: (signal: string) => void |
| 13 | + |
| 14 | + constructor() { |
| 15 | + this.__isReporting = false |
| 16 | + this.__listener = this.makeListener() |
| 17 | + } |
| 18 | + |
| 19 | + setClient(client: typeof Client) { |
| 20 | + this.__client = client |
| 21 | + } |
| 22 | + |
| 23 | + makeListener() { |
| 24 | + // noinspection UnnecessaryLocalVariableJS |
| 25 | + const honeybadgerShutdownListener = async (signal: NodeJS.Signals) => { |
| 26 | + if (this.__isReporting || !this.__client) { |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + this.__isReporting = true |
| 31 | + |
| 32 | + await this.__client.flushAsync() |
| 33 | + |
| 34 | + this.__isReporting = false |
| 35 | + |
| 36 | + if (!this.hasOtherShutdownListeners(signal)) { |
| 37 | + fatallyLogAndExitGracefully(signal) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return honeybadgerShutdownListener |
| 42 | + } |
| 43 | + |
| 44 | + maybeAddListener() { |
| 45 | + for (const signal of ShutdownMonitor.KILL_SIGNALS) { |
| 46 | + const signalListeners = process.listeners(signal); |
| 47 | + if (!signalListeners.includes(this.__listener)) { |
| 48 | + process.on(signal, this.__listener) |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + maybeRemoveListener() { |
| 54 | + for (const signal of ShutdownMonitor.KILL_SIGNALS) { |
| 55 | + const signalListeners = process.listeners(signal); |
| 56 | + if (signalListeners.includes(this.__listener)) { |
| 57 | + process.removeListener(signal, this.__listener) |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + hasOtherShutdownListeners(signal: NodeJS.Signals) { |
| 63 | + const otherListeners = process |
| 64 | + .listeners(signal) |
| 65 | + .filter(listener => listener !== this.__listener) |
| 66 | + |
| 67 | + return otherListeners.length > 0; |
| 68 | + |
| 69 | + } |
| 70 | +} |
0 commit comments