mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-06 08:56:28 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a723626209 | |||
| 3792b455e8 | |||
| e496e34fae |
@@ -5,4 +5,39 @@
|
|||||||
## In PRODUCTION environment, online topup log and error log will be active.
|
## In PRODUCTION environment, online topup log and error log will be active.
|
||||||
# debugging log contains log all validation checks step by step, request data from client, error log, and response data to client
|
# debugging log contains log all validation checks step by step, request data from client, error log, and response data to client
|
||||||
# online topup log contains request data from client, error log, and response data to client
|
# online topup log contains request data from client, error log, and response data to client
|
||||||
# error log contains only error system or error service
|
# error log contains only error system or error service
|
||||||
|
|
||||||
|
## Kapasitas koneksi PostgreSQL
|
||||||
|
|
||||||
|
Pengaturan pool utama dan pool tambahan ada di `knexfile.js`.
|
||||||
|
|
||||||
|
Titik awal untuk satu replika dengan dua worker dan kedua pool pada server
|
||||||
|
PostgreSQL yang sama adalah maksimal 20 koneksi aplikasi.
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
DB_POOL_MAX=8
|
||||||
|
DB_POOLING_POOL_MAX=2
|
||||||
|
DB_POOL_ACQUIRE_TIMEOUT_MS=5000
|
||||||
|
CLUSTER_WORKERS=2
|
||||||
|
```
|
||||||
|
|
||||||
|
Kedua pool memakai minimum 0 dan melepas koneksi yang idle setelah sekitar 30
|
||||||
|
detik. Timeout akuisisi membatasi waktu tunggu mendapatkan koneksi, dalam
|
||||||
|
milidetik. `CLUSTER_WORKERS` berlaku untuk cluster Node dan sticky session.
|
||||||
|
Jika tidak diisi, batas bawaan adalah dua worker atau jumlah CPU yang tersedia
|
||||||
|
jika lebih kecil. Mode biasa, termasuk mode multi-port, memakai satu proses
|
||||||
|
per instans. Hitung juga proses yang dibuat PM2 atau orchestrator.
|
||||||
|
|
||||||
|
Untuk tiap server PostgreSQL, kurangi `max_connections` dengan slot cadangan,
|
||||||
|
koneksi puncak layanan lain, dan ruang untuk operasi. Jika kedua pool menuju
|
||||||
|
server yang sama, bagi jatah TopUp dengan jumlah maksimum proses aplikasi yang
|
||||||
|
bisa hidup bersamaan, termasuk saat rolling deploy. Hasilnya adalah batas
|
||||||
|
gabungan kedua pool per proses. Jika kedua pool menuju server berbeda, hitung
|
||||||
|
jatah masing-masing server.
|
||||||
|
|
||||||
|
Contoh dengan jatah 40 koneksi dan maksimum empat proses bersamaan.
|
||||||
|
Batas 8 + 2 per proses menggunakan paling banyak 40 koneksi. Jumlah pengguna
|
||||||
|
aktif tidak langsung menentukan ukuran pool. Uji dengan trafik representatif,
|
||||||
|
lalu pantau latensi query, timeout akuisisi Knex, dan sesi `active`,
|
||||||
|
`idle`, serta `idle in transaction` pada `pg_stat_activity` sebelum menaikkan
|
||||||
|
batas.
|
||||||
|
|||||||
@@ -1,17 +1,5 @@
|
|||||||
require("dotenv").config();
|
const { pooling: poolingConfig } = require("../../../knexfile");
|
||||||
let host = process.env.DB_HOST_POOLING;
|
const dbPooling = require("knex")(poolingConfig);
|
||||||
let user = process.env.DB_USER_POOLING;
|
|
||||||
let name = process.env.DB_NAME_POOLING;
|
|
||||||
let password = process.env.DB_PASSWORD_POOLING;
|
|
||||||
const dbPooling = require("knex")({
|
|
||||||
client: "pg",
|
|
||||||
connection: {
|
|
||||||
host: host,
|
|
||||||
user: user,
|
|
||||||
password: password,
|
|
||||||
database: name,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const knex = require("../../../infrastructure/database/knex");
|
const knex = require("../../../infrastructure/database/knex");
|
||||||
const moment = require("moment");
|
const moment = require("moment");
|
||||||
moment.locale("id");
|
moment.locale("id");
|
||||||
|
|||||||
@@ -1785,6 +1785,10 @@ const validateReplacement = async (req, res) => {
|
|||||||
last_balance: last_balance,
|
last_balance: last_balance,
|
||||||
is_warranty: is_warranty,
|
is_warranty: is_warranty,
|
||||||
unique_code: uniqueCode,
|
unique_code: uniqueCode,
|
||||||
|
card_category: {
|
||||||
|
id: dataCardReplacement.card_category_id,
|
||||||
|
name: dataCardReplacement.card_category_name
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
// var http = require('http');
|
|
||||||
const cluster = require('node:cluster');
|
const cluster = require('node:cluster');
|
||||||
const totalCPUs = require('node:os').cpus().length;
|
const { createServer } = require('node:http');
|
||||||
const process = require('node:process');
|
const { clusterWorkerCount } = require('./infrastructure/runtime-config');
|
||||||
|
require('./knexfile'); // Validate pool limits before starting any workers.
|
||||||
const winston = require('./application/helpers/winston.logger');
|
const winston = require('./application/helpers/winston.logger');
|
||||||
const app = require('./server');
|
|
||||||
const sticky = require('sticky-session');
|
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';
|
var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
|
||||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||||
@@ -29,122 +32,60 @@ if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// jika mau di cluster gunakan script berikut:
|
if (clustered) {
|
||||||
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') {
|
if (cluster.isPrimary) {
|
||||||
if (cluster.isMaster) {
|
const workerCount = clusterWorkerCount();
|
||||||
console.log(`Number of CPUs is ${totalCPUs}`);
|
if (stickySession || multiplePorts) {
|
||||||
console.log(`Master ${process.pid} is running`);
|
winston.logger.warn('CLUSTER_NODE=YES takes precedence over sticky session and multiple ports');
|
||||||
|
}
|
||||||
// Fork workers.
|
winston.logger.info(`Starting Node.js cluster with ${workerCount} workers`);
|
||||||
for (let i = 0; i < totalCPUs; i++) {
|
for (let i = 0; i < workerCount; i++) {
|
||||||
cluster.fork();
|
cluster.fork();
|
||||||
}
|
}
|
||||||
|
|
||||||
cluster.on('exit', (worker, code, signal) => {
|
cluster.on('exit', (worker, code) => {
|
||||||
console.log(`worker ${worker.process.pid} died`);
|
winston.logger.warn(`Worker ${worker.process.pid} exited with code ${code}. Starting replacement`);
|
||||||
console.log("Let's fork another worker!");
|
|
||||||
console.log('with code: ' + code);
|
|
||||||
cluster.fork();
|
cluster.fork();
|
||||||
});
|
});
|
||||||
|
|
||||||
// console.log(`worker pid=${process.pid}`);
|
|
||||||
} else {
|
} else {
|
||||||
startExpress();
|
require('./server').listen(port, () => logListening(port, ' with cluster node'));
|
||||||
|
}
|
||||||
|
} 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`);
|
||||||
|
}
|
||||||
|
const server = sticky(workerCount, () => {
|
||||||
|
const workerServer = createServer(require('./server'));
|
||||||
|
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'));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// jika tidak mau di cluster langsung call function startExpress
|
const app = require('./server');
|
||||||
startExpress();
|
const ports = new Set([port]);
|
||||||
}
|
if (multiplePorts && process.env.PORTS) {
|
||||||
|
for (const additionalPort of process.env.PORTS.split(',')) {
|
||||||
function startExpress() {
|
ports.add(parseInt(additionalPort));
|
||||||
// set port, listen for requests
|
|
||||||
const PORT = parseInt(process.env.PORT) || 3000;
|
|
||||||
|
|
||||||
// jika settingan running on multiple
|
|
||||||
if (
|
|
||||||
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
|
|
||||||
process.env.CLUSTER_NODE.toUpperCase() == 'NO'
|
|
||||||
) {
|
|
||||||
const PORTS = process.env.PORTS;
|
|
||||||
|
|
||||||
if (!PORTS) {
|
|
||||||
winston.logger.warn(
|
|
||||||
`Running on multiple port is active but the ports not yet set in .env`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
let ports = PORTS.split(',');
|
|
||||||
|
|
||||||
for (let index = 0; index < ports.length; index++) {
|
|
||||||
const port = parseInt(ports[index]);
|
|
||||||
|
|
||||||
app.listen(port, () => {
|
|
||||||
winston.logger.info(
|
|
||||||
`Server is running on version ${
|
|
||||||
process.env.VERSION
|
|
||||||
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${port} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if (
|
} else if (multiplePorts) {
|
||||||
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
|
winston.logger.warn('Running on multiple ports is active but PORTS is unset');
|
||||||
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
|
|
||||||
) {
|
|
||||||
winston.logger.warn(
|
|
||||||
`If you want running the service on multiple port, please set CLUSTER_NODE = NO in .env file `
|
|
||||||
);
|
|
||||||
} else if (
|
|
||||||
process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES' &&
|
|
||||||
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
|
|
||||||
) {
|
|
||||||
winston.logger.warn(
|
|
||||||
`If you want running the service with sticky session, please set CLUSTER_NODE = NO in .env file `
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
for (const listenPort of ports) {
|
||||||
let message = `Server is running on version ${
|
app.listen(listenPort, () => logListening(listenPort));
|
||||||
process.env.VERSION
|
|
||||||
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
|
|
||||||
|
|
||||||
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') {
|
|
||||||
message = `Server is running with cluster node on version ${
|
|
||||||
process.env.VERSION
|
|
||||||
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
|
|
||||||
} else if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
|
|
||||||
message = `Server is running with sticky session on version ${
|
|
||||||
process.env.VERSION
|
|
||||||
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
|
|
||||||
const server = app.listen(PORT, () => {
|
|
||||||
console.log(
|
|
||||||
`Worker ${process.pid} started. Listening on port ${
|
|
||||||
server.address().port
|
|
||||||
}`
|
|
||||||
);
|
|
||||||
winston.logger.info(message);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Use sticky-session with the server instance
|
|
||||||
sticky.listen(server);
|
|
||||||
} else {
|
|
||||||
app.listen(PORT, () => {
|
|
||||||
winston.logger.info(message);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use sticky-session to handle sticky sessions
|
function logListening(listenPort, mode = '') {
|
||||||
// if (!sticky.listen(cluster, port)) {
|
winston.logger.info(
|
||||||
// // This is the master process, and it should not be listening to the port
|
`Server is running${mode} on version ${process.env.VERSION} environment: ${(process.env.NODE_ENV || 'production').toUpperCase()} port: ${listenPort} on ${serverActive}. HSM STATUS : ${serverHSMStatus}`
|
||||||
// cluster.on('listening', (worker, address) => {
|
);
|
||||||
// console.log(
|
}
|
||||||
// `Worker ${worker.id} is now connected to ${address.address}:${address.port}`
|
|
||||||
// );
|
|
||||||
// });
|
|
||||||
|
|
||||||
// cluster.on('exit', (worker) => {
|
|
||||||
// console.log(`Worker ${worker.id} has exited`);
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
const os = require('node:os');
|
||||||
|
|
||||||
|
function positiveIntegerFromEnv(name, fallback) {
|
||||||
|
const value = process.env[name]?.trim();
|
||||||
|
if (!value) return fallback;
|
||||||
|
|
||||||
|
const number = Number(value);
|
||||||
|
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < 1) {
|
||||||
|
throw new Error(`${name} must be a positive integer`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clusterWorkerCount() {
|
||||||
|
const availableCPUs = os.availableParallelism?.() ?? os.cpus().length;
|
||||||
|
return positiveIntegerFromEnv('CLUSTER_WORKERS', Math.min(2, availableCPUs));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { positiveIntegerFromEnv, clusterWorkerCount };
|
||||||
+29
-14
@@ -1,4 +1,16 @@
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
|
const { positiveIntegerFromEnv } = require('./infrastructure/runtime-config');
|
||||||
|
|
||||||
|
const poolOptions = {
|
||||||
|
min: 0,
|
||||||
|
idleTimeoutMillis: 30000,
|
||||||
|
acquireTimeoutMillis: positiveIntegerFromEnv('DB_POOL_ACQUIRE_TIMEOUT_MS', 5000),
|
||||||
|
};
|
||||||
|
|
||||||
|
const primaryPostgresPool = {
|
||||||
|
...poolOptions,
|
||||||
|
max: positiveIntegerFromEnv('DB_POOL_MAX', 8),
|
||||||
|
};
|
||||||
|
|
||||||
let host;
|
let host;
|
||||||
let database;
|
let database;
|
||||||
@@ -68,13 +80,7 @@ module.exports = {
|
|||||||
password: password,
|
password: password,
|
||||||
},
|
},
|
||||||
// connection: process.env.DB_URL,
|
// connection: process.env.DB_URL,
|
||||||
pool: {
|
pool: primaryPostgresPool,
|
||||||
min: 2,
|
|
||||||
max: 100,
|
|
||||||
idleTimeoutMillis: 30000, // ← Contoh: 30 detik idle timeout
|
|
||||||
acquireTimeoutMillis: 20000, // Maksimal waktu tunggu koneksi dari pool
|
|
||||||
// maxLifetimeMillis: 300000 // maksimal umur koneksi: 5 menit (300.000 ms)
|
|
||||||
},
|
|
||||||
migrations: {
|
migrations: {
|
||||||
directory: './infrastructure/database/migrations',
|
directory: './infrastructure/database/migrations',
|
||||||
},
|
},
|
||||||
@@ -83,12 +89,27 @@ module.exports = {
|
|||||||
testing: {
|
testing: {
|
||||||
client: 'pg',
|
client: 'pg',
|
||||||
connection: process.env.DB_URL,
|
connection: process.env.DB_URL,
|
||||||
|
pool: primaryPostgresPool,
|
||||||
migrations: {
|
migrations: {
|
||||||
directory: './infrastructure/database/migrations',
|
directory: './infrastructure/database/migrations',
|
||||||
},
|
},
|
||||||
seeds: { directory: './infrastructure/database/seeds' },
|
seeds: { directory: './infrastructure/database/seeds' },
|
||||||
},
|
},
|
||||||
|
|
||||||
|
pooling: {
|
||||||
|
client: 'pg',
|
||||||
|
connection: {
|
||||||
|
host: process.env.DB_HOST_POOLING,
|
||||||
|
user: process.env.DB_USER_POOLING,
|
||||||
|
password: process.env.DB_PASSWORD_POOLING,
|
||||||
|
database: process.env.DB_NAME_POOLING,
|
||||||
|
},
|
||||||
|
pool: {
|
||||||
|
...poolOptions,
|
||||||
|
max: positiveIntegerFromEnv('DB_POOLING_POOL_MAX', 2),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
production: {
|
production: {
|
||||||
client: 'pg',
|
client: 'pg',
|
||||||
connection: {
|
connection: {
|
||||||
@@ -98,13 +119,7 @@ module.exports = {
|
|||||||
password: password,
|
password: password,
|
||||||
},
|
},
|
||||||
// connection: process.env.DB_URL,
|
// connection: process.env.DB_URL,
|
||||||
pool: {
|
pool: primaryPostgresPool,
|
||||||
min: 2,
|
|
||||||
max: 100,
|
|
||||||
idleTimeoutMillis: 30000, // ← Contoh: 30 detik idle timeout
|
|
||||||
acquireTimeoutMillis: 20000, // Maksimal waktu tunggu koneksi dari pool
|
|
||||||
// maxLifetimeMillis: 300000 // maksimal umur koneksi: 5 menit (300.000 ms)
|
|
||||||
},
|
|
||||||
migrations: {
|
migrations: {
|
||||||
directory: './infrastructure/database/migrations',
|
directory: './infrastructure/database/migrations',
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user