|
| 1 | +/* |
| 2 | + This file is part of Nest GraphQL Fastify Template |
| 3 | +
|
| 4 | + This project is dual-licensed under the Mozilla Public License 2.0 (MPLv2) and the |
| 5 | + GNU General Public License version 3 (GPLv3). |
| 6 | +
|
| 7 | + You may use, distribute, and modify this file under the terms of either the MPLv2 |
| 8 | + or GPLv3, at your option. If a copy of these licenses was not distributed with this |
| 9 | + file. You may obtain a copy of the licenses at https://www.mozilla.org/en-US/MPL/2.0/ |
| 10 | + and https://www.gnu.org/licenses/gpl-3.0.en.html respectively. |
| 11 | +
|
| 12 | + Copyright © 2023 |
| 13 | + Afonso Barracha |
| 14 | +*/ |
| 15 | + |
| 16 | +import { Logger } from '@nestjs/common'; |
| 17 | +import cluster from 'cluster'; |
| 18 | +import os from 'os'; |
| 19 | +import { isUndefined } from './config/utils/validation.util'; |
| 20 | + |
| 21 | +export class Cluster { |
| 22 | + private static readonly loggerService = new Logger(Cluster.name); |
| 23 | + |
| 24 | + public static createCluster(main: () => Promise<void>): void { |
| 25 | + const cpuCount = Cluster.getCpuCount(); |
| 26 | + |
| 27 | + if (cluster.isMaster) { |
| 28 | + Cluster.loggerService.log(`Starting cluster with ${cpuCount} workers...`); |
| 29 | + Cluster.loggerService.log( |
| 30 | + `Master server is running on process ${process.pid}`, |
| 31 | + ); |
| 32 | + |
| 33 | + for (let i = 0; i < cpuCount; i++) { |
| 34 | + Cluster.loggerService.log(`Forking process number ${i + 1}...`); |
| 35 | + cluster.fork(); |
| 36 | + } |
| 37 | + |
| 38 | + cluster.on('exit', (worker) => { |
| 39 | + Cluster.loggerService.warn(`Worker ${worker.id} died. `); |
| 40 | + Cluster.loggerService.warn('Starting a new worker...'); |
| 41 | + cluster.fork(); |
| 42 | + }); |
| 43 | + } else { |
| 44 | + main(); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private static getCpuCount(): number { |
| 49 | + if (!isUndefined(process.env.WORKERS_COUNT)) { |
| 50 | + return parseInt(process.env.WORKERS_COUNT, 10); |
| 51 | + } |
| 52 | + if ( |
| 53 | + !isUndefined(process.env.NODE_ENV) && |
| 54 | + process.env.NODE_ENV === 'production' |
| 55 | + ) { |
| 56 | + return os.cpus().length; |
| 57 | + } |
| 58 | + return 2; |
| 59 | + } |
| 60 | +} |
0 commit comments