import { Injectable } from "@nestjs/common"; import axios, { AxiosInstance } from "axios"; import { CONST, resolveExecutionMode, resolveWorkerCount } from "@shopstack/cc-core-lib/core"; // Need to change to required. since upgrade the node to 24 and the typescript conflict for ES import // import * as cluster from "node:cluster"; // not working TS Conflict const cluster = require("node:cluster") as any; CONST.INTERNAL_DOMAIN = `http://${process.env.LOOP_BACK_IP}:${process.env.PORT || 3000}/api/v1`; @Injectable() export class AppClusterService { static async clusterize(callback: Function): Promise { resolveExecutionMode(); const workerCount = resolveWorkerCount(); if (cluster.isPrimary) { console.log(`Master server started on ${process.pid}`); console.log("MAXIMUM WORKER PROCESS: " + workerCount); CONST.MAIN_PROCESS = true; for (let i = 0; i < workerCount; i++) { const env = { WORKER_NO: String(i + 1) }; const worker = cluster.fork(env); worker.process["env"] = env; } cluster.on("listening", (worker, address) => { console.log(`A worker is now connected to ${address.address}:${address.port}`); const http: AxiosInstance = axios.create(); if (worker.process["env"].WORKER_NO == "1") { http.get(`${CONST.INTERNAL_DOMAIN}/entities/init_data`); http.get(`${CONST.INTERNAL_DOMAIN}/setting/update_version`); } http.get(`${CONST.INTERNAL_DOMAIN}/user_role/reload_system`); http.get(`${CONST.INTERNAL_DOMAIN}/translate/generate`); http.get(`${CONST.INTERNAL_DOMAIN}/health_check/init`); }); cluster.on("exit", (worker, code, signal, ...other) => { const env = worker.process["env"]; console.log(`Worker ${worker.process.pid} (${code},${signal}) died. Restarting`); const newWorker = cluster.fork(env); newWorker.process["env"] = env; }); } else { console.log(`Cluster server started on ${process.pid}`); await callback(); } } }