kafka-dance-api/safely-exit.js

41 lines
1009 B
JavaScript

const errorTypes = ['unhandledRejection', 'uncaughtException']
const signalTraps = ['SIGTERM', 'SIGINT', 'SIGUSR2']
const disconnectAll = async (consumers, clusters) => {
await Promise.all([
...Object.values(clusters).map(async cluster => cluster.admin.disconnect()),
...Array.from(consumers.values()).map(async consumer => consumer.consumer.disconnect())
])
}
const buildEscape = (consumers, clusters) => {
const disconnect = async () => disconnectAll(consumers, clusters)
errorTypes.map(type => {
process.on(type, async e => {
try {
console.log(`process.on ${type}`)
console.error(e)
await disconnect()
process.exit(0)
} catch (_) {
process.exit(1)
}
})
})
signalTraps.map(type => {
process.once(type, async () => {
try {
console.log('signalTrap: ' + type)
await disconnect()
} finally {
process.kill(process.pid, type)
}
})
})
}
module.exports = {
buildEscape
}