Skip to content

Instantly share code, notes, and snippets.

@Dante-101
Last active October 17, 2024 19:42
Show Gist options
  • Save Dante-101/8f327a9cd886292d21636356e6ba7258 to your computer and use it in GitHub Desktop.
Save Dante-101/8f327a9cd886292d21636356e6ba7258 to your computer and use it in GitHub Desktop.
Master process class managing workers
import * as cluster from 'cluster'
class Master {
private shutdownInProgress: boolean = false
private hasCleanWorkerExit: boolean = true
private processStr = `${cluster.isMaster ? "master" : "worker"} process ${process.pid}`
gracefulClusterShutdown = (signal: NodeJS.Signals) => async () => {
//defined in worker-shutdown.ts (https://gist.github.com/Dante-101/de2fbd5071bec0c0647f5c9fa1cfa179)
}
shutdownWorkers = (signal: NodeJS.Signals) => {
//defined in worker-shutdown.ts (https://gist.github.com/Dante-101/de2fbd5071bec0c0647f5c9fa1cfa179)
}
async stop() {
//stop listening
//disconnect with db
//any other cleanup
}
async start() {
if (cluster.isMaster) {
await this.bootWorkers(4)
}
process.on('SIGTERM', this.gracefulClusterShutdown('SIGTERM'))
process.on('SIGINT', this.gracefulClusterShutdown('SIGINT'))
}
bootWorkers = async (numWorkers: number) => {
log.info(`Setting ${numWorkers} workers...`);
for (let i = 0; i < numWorkers; i++) {
cluster.fork() //create the workers
}
//Setting up lifecycle event listeners for worker processes
cluster.on('online', worker => {
log.info(`worker process ${worker.process.pid} is online`)
})
cluster.on('exit', (worker, code, signal) => {
log.info(`worker ${worker.process.pid} exited with code ${code} and signal ${signal}`)
if (this.shutdownInProgress && code != 0) {
this.hasCleanWorkerExit = false
}
})
cluster.on('disconnect', worker => {
log.info(`worker process ${worker.process.pid} has disconnected`)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment