Files
Online-Topup-V1/index.js
2026-11-26 17:18:30 +07:00

143 lines
5.7 KiB
JavaScript

require('dotenv').config();
require('./infrastructure/transaction-time').configureTransactionClock();
const cluster = require('node:cluster');
const { createServer } = require('node:http');
const { clusterWorkerCount } = require('./infrastructure/runtime-config');
const { createGracefulShutdown, createClusterShutdown } = require('./infrastructure/graceful-shutdown');
require('./knexfile'); // Validate pool limits before starting any workers.
const winston = require('./application/helpers/winston.logger');
const port = parseInt(process.env.PORT) || 3000;
const clustered = process.env.CLUSTER_NODE?.toUpperCase() === 'YES';
const stickySession = process.env.CLUSTER_NODE_STICKY_SESSION?.toUpperCase() === 'YES';
const multiplePorts = process.env.RUNNING_ON_MULTIPLE_PORT?.toUpperCase() === 'YES';
var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_1}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_2}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_2} CONNECTED`;
}
var serverActive = 'DC (DATA CENTER)';
if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
serverActive = 'DRC (DISASTER RECOVERY CENTER)';
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_1}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_2}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_BACKUP_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_BACKUP_2} CONNECTED`;
}
}
function createAppCleanupTasks() {
const knex = require('./infrastructure/database/knex');
const { closePool: closePoolingPool } = require('./application/modules/pooling/pooling.model');
const { closeRedis } = require('./application/middlewares/redis.middleware');
const { close: closeAuditArchive } = require('./application/helpers/response-audit');
return [
{ name: 'postgres-primary', close: () => knex.destroy() },
{ name: 'postgres-pooling', close: () => closePoolingPool() },
{ name: 'redis', close: () => closeRedis() },
{ name: 'audit-archive', close: () => closeAuditArchive() },
];
}
function attachWorkerShutdown(app, servers) {
const gracefulShutdown = createGracefulShutdown({
servers,
cleanupTasks: createAppCleanupTasks(),
onBeforeClose: () => app?.setShuttingDown(true),
logger: winston.logger,
});
gracefulShutdown.installSignalHandlers();
return gracefulShutdown;
}
if (clustered) {
if (cluster.isPrimary) {
const workerCount = clusterWorkerCount();
if (stickySession || multiplePorts) {
winston.logger.warn('CLUSTER_NODE=YES takes precedence over sticky session and multiple ports');
}
const clusterShutdown = createClusterShutdown({
clusterModule: cluster,
logger: winston.logger,
});
clusterShutdown.installSignalHandlers();
winston.logger.info(`Starting Node.js cluster with ${workerCount} workers`);
for (let i = 0; i < workerCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code) => {
if (clusterShutdown.isShuttingDown()) {
winston.logger.info(`Worker ${worker.process.pid} exited with code ${code} during shutdown`);
return;
}
winston.logger.warn(`Worker ${worker.process.pid} exited with code ${code}. Starting replacement`);
cluster.fork();
});
} else {
const app = require('./server');
const server = app.listen(port, () => logListening(port, ' with cluster node'));
attachWorkerShutdown(app, [server]);
}
} else if (stickySession) {
const workerCount = clusterWorkerCount();
const sticky = require('sticky-session');
if (cluster.isPrimary) {
if (multiplePorts) {
winston.logger.warn('CLUSTER_NODE_STICKY_SESSION=YES takes precedence over multiple ports');
}
winston.logger.info(`Starting sticky session cluster with ${workerCount} workers`);
}
let workerApp;
const server = sticky(workerCount, () => {
workerApp = require('./server');
const workerServer = createServer(workerApp);
workerServer.on('connection', (socket) => socket.resume());
return workerServer;
});
if (cluster.isPrimary) {
// Keep the first HTTP bytes on the socket until the worker takes ownership.
server.pauseOnConnect = true;
server.listen(port, () => logListening(port, ' with sticky session'));
const clusterShutdown = createClusterShutdown({
clusterModule: cluster,
servers: [server],
logger: winston.logger,
});
clusterShutdown.installSignalHandlers();
} else {
attachWorkerShutdown(workerApp, [server]);
}
} else {
const app = require('./server');
const ports = new Set([port]);
if (multiplePorts && process.env.PORTS) {
for (const additionalPort of process.env.PORTS.split(',')) {
ports.add(parseInt(additionalPort));
}
} else if (multiplePorts) {
winston.logger.warn('Running on multiple ports is active but PORTS is unset');
}
const servers = [];
for (const listenPort of ports) {
servers.push(app.listen(listenPort, () => logListening(listenPort)));
}
attachWorkerShutdown(app, servers);
}
function logListening(listenPort, mode = '') {
winston.logger.info(
`Server is running${mode} on version ${process.env.VERSION} environment: ${(process.env.NODE_ENV || 'production').toUpperCase()} port: ${listenPort} on ${serverActive}. HSM STATUS : ${serverHSMStatus}`
);
}