Emit structured stdout logs and harden transaction handling

This commit is contained in:
Mohamad Ihsan
2026-11-23 23:12:42 +07:00
parent 7957bf5a64
commit 572444a114
30 changed files with 499 additions and 1012 deletions
+11 -3
View File
@@ -4,7 +4,8 @@ require("winston-daily-rotate-file");
const expressWinston = require("express-winston");
const fs = require("fs");
const moment = require("moment");
const winstonLoki = require("../helpers/loki");
const responseAudit = require("./response-audit");
const { writeStdoutLine, formatLog } = require("./stdout-log");
const knex = require("../../infrastructure/database/knex");
const {
topuponline_metrics,
@@ -100,7 +101,7 @@ async function refreshIssuer(partnerId) {
function recordResponse(event, partnerId, reservationNumber, message) {
const issuerName = getIssuerName(partnerId);
const level = successfulCodes.has(event.status_code) ? 'info' : 'error';
winstonLoki.log.log({
responseAudit.record({
level,
message: typeof message === 'string' ? message : 'HTTP response',
...event,
@@ -143,6 +144,7 @@ const logger = {
load_balance_number: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
route,
method: req.method,
http_status: res.statusCode,
status_code: /^\d{2,4}$/.test(applicationCode) ? applicationCode : 'UNKNOWN',
response_time_ms: responseTime,
};
@@ -154,7 +156,13 @@ const logger = {
try {
recordResponse(event, req.partner_id_token, reservationNumber, res.body?.message);
} catch {
console.error('Failed to record Online TopUp response telemetry');
writeStdoutLine(formatLog({
event: 'response_telemetry_error',
level: 'error',
message: 'Failed to record Online TopUp response telemetry',
request_id: req.id,
route,
}));
}
const body = {
+2 -1
View File
@@ -1,6 +1,7 @@
const CryptoJS = require('crypto-js');
const { randomUUID } = require('crypto');
const knex = require('../../infrastructure/database/knex');
const { logger } = require('./winston.logger');
// ENCRYPT TEXT
const encryptText = (text) => {
@@ -168,7 +169,7 @@ function generateXMLRequest(urn, headers, items) {
</SOAP:Envelope>`;
break;
default:
console.log('Sorry, we are out of ' + urn + '.');
logger.warn('Unsupported SAP XML template');
}
return xmlRequest;
-92
View File
@@ -1,92 +0,0 @@
const axios = require('axios');
// Antrean ini hanya menyimpan salinan untuk Loki. Audit lokal sudah ditulis sebelumnya.
function createLokiDelivery({ url, maxEntries = 2000, maxBytes = 2 * 1024 * 1024,
batchEntries = 250, timeoutMs = 5000, intervalMs = 500, onQueue, onDiscard, onFailure }) {
let queue = [];
let bytes = 0;
let inFlightEntries = 0;
let inFlightBytes = 0;
let timer;
let failures = 0;
let closed = false;
function schedule(delay) {
if (closed || timer || inFlightEntries || queue.length === 0) return;
timer = setTimeout(() => {
timer = undefined;
void flush();
}, delay);
timer.unref?.();
}
function observe() {
onQueue(queue.length + inFlightEntries, bytes + inFlightBytes);
}
function enqueue(line, level, time = Date.now()) {
if (closed) return;
const size = Buffer.byteLength(JSON.stringify(line)) + 64;
if (size + inFlightBytes > maxBytes || inFlightEntries >= maxEntries) {
onDiscard('capacity', 1);
return;
}
while (queue.length + inFlightEntries >= maxEntries || bytes + inFlightBytes + size > maxBytes) {
bytes -= queue.shift().size;
onDiscard('capacity', 1);
}
queue.push({ line, level, time, size });
bytes += size;
observe();
schedule(intervalMs);
}
async function flush() {
const entries = queue.splice(0, batchEntries);
inFlightEntries = entries.length;
inFlightBytes = entries.reduce((total, entry) => total + entry.size, 0);
bytes -= inFlightBytes;
const streams = new Map();
for (const { line, level, time } of entries) {
if (!streams.has(level)) streams.set(level, { stream: { app: 'topuponline', level }, values: [] });
streams.get(level).values.push([`${time}000000`, line]);
}
try {
await axios.post(url, { streams: [...streams.values()] }, {
timeout: timeoutMs,
signal: AbortSignal.timeout(timeoutMs),
maxRedirects: 0,
maxContentLength: 4096,
});
failures = 0;
} catch (error) {
failures = Math.min(failures + 1, 6);
onFailure();
if (error.response?.status >= 400 && error.response.status < 500 &&
![408, 429].includes(error.response.status)) {
onDiscard('rejected', entries.length);
} else if (!closed) {
// Batch gagal didahulukan agar timestamp stream tetap berurutan.
queue = entries.concat(queue);
bytes += inFlightBytes;
}
} finally {
inFlightEntries = 0;
inFlightBytes = 0;
observe();
schedule(intervalMs * 2 ** failures);
}
}
function close() {
closed = true;
clearTimeout(timer);
queue = [];
bytes = 0;
observe();
}
return { enqueue, close };
}
module.exports = createLokiDelivery;
-50
View File
@@ -1,50 +0,0 @@
const { Counter, Gauge } = require('prom-client');
const createAuditArchive = require('./audit-archive');
const createLokiDelivery = require('./loki-delivery');
require('dotenv').config();
const auditErrors = new Counter({
name: 'topuponline_audit_write_errors_total',
help: 'Failed local audit archive writes',
});
const deliveryErrors = new Counter({
name: 'topuponline_loki_delivery_errors_total',
help: 'Failed Loki delivery attempts',
});
const discarded = new Counter({
name: 'topuponline_loki_copies_discarded_total',
help: 'Remote diagnostic copies discarded from the bounded queue',
labelNames: ['reason'],
});
const queueEntries = new Gauge({ name: 'topuponline_loki_buffer_entries', help: 'Queued and in-flight Loki entries' });
const queueBytes = new Gauge({ name: 'topuponline_loki_buffer_bytes', help: 'Estimated serialized bytes queued or in flight for Loki' });
const archive = createAuditArchive(process.env.TOPUP_AUDIT_DIR || './lokiLog/audit');
const lokiUrl = process.env.LOKI_URL?.trim();
const delivery = lokiUrl ? createLokiDelivery({
url: lokiUrl.replace(/\/+$/, '') + '/loki/api/v1/push',
onQueue(entries, bytes) { queueEntries.set(entries); queueBytes.set(bytes); },
onDiscard(reason, count) { discarded.inc({ reason }, count); },
onFailure() { deliveryErrors.inc(); },
}) : null;
let archiveUnavailable = false;
const log = {
log(event) {
const time = Date.now();
const line = JSON.stringify({ ...event, timestamp: new Date(time).toISOString() });
try {
archive.append(line, time);
archiveUnavailable = false;
} catch (error) {
auditErrors.inc();
if (!archiveUnavailable) console.error('Online TopUp audit archive write failed:', error.code || 'UNKNOWN');
archiveUnavailable = true;
if (process.stderr.writable && !process.stderr.writableNeedDrain) {
process.stderr.write(`${line}\n`);
}
}
delivery?.enqueue(line, event.level, time);
},
};
module.exports = { log, lokiMetrics: [auditErrors, deliveryErrors, discarded, queueEntries, queueBytes] };
+34
View File
@@ -0,0 +1,34 @@
const { Counter } = require('prom-client');
const createAuditArchive = require('./audit-archive');
const { formatLog, writeStdoutLine } = require('./stdout-log');
require('dotenv').config();
const auditErrors = new Counter({
name: 'topuponline_audit_write_errors_total',
help: 'Failed local audit archive writes',
});
const archive = createAuditArchive(process.env.TOPUP_AUDIT_DIR || './lokiLog/audit');
let archiveUnavailable = false;
function record(event) {
const time = Date.now();
const line = formatLog(event, time);
try {
archive.append(line, time);
archiveUnavailable = false;
} catch (error) {
auditErrors.inc();
if (!archiveUnavailable) {
writeStdoutLine(formatLog({
level: 'error',
event: 'audit_archive_error',
message: 'Unable to write the local audit archive',
error_code: error.code || 'UNKNOWN',
}, time));
}
archiveUnavailable = true;
}
writeStdoutLine(line);
}
module.exports = { record, auditMetrics: [auditErrors] };
+45
View File
@@ -0,0 +1,45 @@
const { Counter } = require('prom-client');
const skipped = new Counter({
name: 'topuponline_stdout_copies_skipped_total',
help: 'Log copies skipped while stdout was unavailable or under backpressure',
labelNames: ['reason'],
});
function createStdoutWriter(stream, onSkip) {
let failed = false;
stream.on('error', () => { failed = true; });
return (line) => {
// Arsip atau log file sudah menjadi salinan lokal. Jangan menambah antrean stdout.
if (failed || !stream.writable) {
onSkip('unavailable');
return;
}
if (stream.writableNeedDrain) {
onSkip('backpressure');
return;
}
try {
stream.write(`${line}\n`, (error) => {
if (error) onSkip('unavailable');
});
} catch {
failed = true;
onSkip('unavailable');
}
};
}
const writeStdoutLine = createStdoutWriter(process.stdout, (reason) => skipped.inc({ reason }));
function formatLog(event, time = Date.now()) {
return JSON.stringify({
timestamp: new Date(time).toISOString(),
app: 'topuponline',
pid: process.pid,
...event,
});
}
module.exports = { createStdoutWriter, writeStdoutLine, formatLog, stdoutMetrics: [skipped] };
+22 -13
View File
@@ -1,9 +1,30 @@
const moment = require("moment");
const winston = require("winston");
const { formatLog, writeStdoutLine } = require("./stdout-log");
require("winston-daily-rotate-file");
require("dotenv").config();
const { combine, timestamp, printf, colorize, align, json } = winston.format;
function stdoutMessage(message) {
if (typeof message !== "string") return "Application log";
// Legacy log calls append whole payloads after a separator.
const payloadStart = message.search(/[:|]\s+(?:\{|\[\s*[{\]"\d]|<\?xml\b)/i);
const summary = payloadStart === -1 ? message : message.slice(0, payloadStart);
return summary.trim().replace(/\bBearer\s+[\w.+/=-]+/gi, "Bearer [redacted]");
}
class StdoutTransport extends winston.Transport {
log(info, done) {
writeStdoutLine(formatLog({
level: info[Symbol.for("level")],
event: "application_log",
service: info.service,
message: stdoutMessage(info.message),
}));
done();
}
}
const logLevels = {
fatal: 0,
error: 1,
@@ -112,19 +133,7 @@ if (
}
if (process.env.NODE_ENV != "testing" && process.env.NODE_ENV != "TESTING") {
logger.add(
new winston.transports.Console({
// format: winston.format.cli(),
format: combine(
colorize({ all: true }),
timestamp({
format: "YYYY-MM-DD HH:mm:ss.SSS",
}),
align(),
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
),
})
);
logger.add(new StdoutTransport());
}
module.exports = {
@@ -64,10 +64,6 @@ const generateAccessToken = (req) => {
const authenticateToken = async (req, res, next) => {
let authHeader = req.headers['authorization'];
var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;
console.log('INI LHO IP NYA....................: ' + ip);
if (authHeader) {
let token = authHeader && authHeader.split(' ')[1];
+4 -3
View File
@@ -2,6 +2,7 @@ require('dotenv').config();
const redis = require('redis');
const moment = require('moment');
const createRedisOperations = require('../helpers/redis-operations');
const { logger } = require('../helpers/winston.logger');
const redisClient = redis.createClient({
url: process.env.REDIS_URL || 'redis://127.0.0.1:6379',
@@ -10,11 +11,11 @@ const redisClient = redis.createClient({
});
redisClient.on('error', () => {});
redisClient.on('ready', () => console.log('Redis is Ready'));
void redisClient.connect().catch(() => console.error('Redis connection failed'));
redisClient.on('ready', () => logger.info('Redis connection ready'));
void redisClient.connect().catch(() => logger.error('Redis connection failed'));
const execute = createRedisOperations(redisClient, {
onTimeout: () => console.warn('Redis command deadline exceeded; using the database sequence fallback'),
onTimeout: () => logger.warn('Redis command deadline exceeded; database sequence fallback is active'),
});
async function redisMiddleware(req, res, next) {
+2 -4
View File
@@ -81,9 +81,7 @@ const loginPartnerUser = async (req, res, next) => {
// })}`
// );
console.log(
`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify(result)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]`);
// validate
let err = validationResult(req);
@@ -380,7 +378,7 @@ const loginTerminal = async (req, res, next) => {
// log info
winston.logger.info(
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ]: ${JSON.stringify(result)}`
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
);
return res.status(200).json(result);
@@ -739,9 +739,8 @@ const _postingCashIn = async (uniqueCode) => {
xmlHeader,
xmlItem
);
console.log(xmlRequest);
winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP`
);
const url =
@@ -792,7 +792,6 @@ const insertCashInDetailBulk = async (trx, data) => {
};
const writePaynentHistory = async (data, message, i_log_name, trx) => {
console.log(data);
const result = await trx('log.t_log_invoice').insert(
{
// i_log_name : 102,
+7 -1
View File
@@ -1,5 +1,6 @@
const { Buffer } = require('buffer');
const fs = require('fs');
const { formatLog, writeStdoutLine } = require('../../../helpers/stdout-log');
// Generate request data for FeliQ Server
function makeRequestData(transactionId, apiId, data) {
@@ -155,7 +156,12 @@ const logging = (date, title, message, id = 0) => {
return;
} catch (err) {
console.error('Error from logging: ', err.message);
writeStdoutLine(formatLog({
level: 'error',
event: 'hsm_log_write_error',
message: 'Unable to write the HSM log file',
error_code: err.code || 'UNKNOWN',
}));
return;
}
};
@@ -11,7 +11,6 @@ const generateInvoice = async (invoiceDate, repost, trx) => {
}
const insertPostingEt = async (invoice, trx) => {
console.log("invoice : ", invoice)
let type = ['S', 'H']
let et = []
let posting_et = []
@@ -128,7 +127,6 @@ const setReturnSAP = async (invoice, resSAP, trx) => {
}
const writePaynentHistory = async (data, trx) => {
console.log(data)
const result = await trx('log.t_log_invoice').insert({
i_log_name : 102,
d_log : trx.raw('NOW()'),
@@ -155,4 +153,4 @@ module.exports = {
setReturnSAP,
getPostingEt,
writePaynentHistory
};
};
@@ -1338,11 +1338,11 @@ const loadingBalanceInsert = async (req, param) => {
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...`
// );
// check reservation status
for (let index = 0; index < reservation_number.length; index++) {
let reservationStatus = await model.findReservation(
reservation_number[index]
);
const statuses = await model.findReservationsWithLoadedBalance(reservation_number);
const statusByNumber = new Map(statuses.map((status) => [status.c_reservation_no, status]));
// Urutan input menentukan respons pertama, walaupun PostgreSQL mengurutkan hasilnya.
for (const number of reservation_number) {
const reservationStatus = statusByNumber.get(String(number));
// if reservation doesn't exist or has been canceled
if (!reservationStatus) {
@@ -1362,35 +1362,18 @@ const loadingBalanceInsert = async (req, param) => {
return result;
}
// if there are reservation with status active
if (reservationStatus.c_status == 'A') {
// if there are reservation on load balance table transaction but before process on reservation failed update to LOADED
let reservationLoaded = await model.findReservationLoaded(
reservationStatus.i_reservation_balance
if (reservationStatus.loaded_id != null) {
result = {
code: '00',
message:
'reservation has been successfully loaded on ' +
moment(reservationStatus.loaded_at).format('DD MMM YYYY HH:mm:ss'),
data: { load_balance_number: reservationStatus.loaded_number },
};
winston.logger.info(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(result)}`
);
if (reservationLoaded) {
let loadBalanceNumberExisting = reservationLoaded.c_load_balance_no;
let loadDate = reservationLoaded.d_load_balance;
result = {
code: '00',
message:
'reservation has been successfully loaded on ' +
moment(loadDate).format('DD MMM YYYY HH:mm:ss'),
data: {
load_balance_number: loadBalanceNumberExisting,
},
};
// log info
winston.logger.info(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
result
)}`
);
return result;
}
return result;
}
}
@@ -1660,14 +1643,12 @@ const loadingBalanceInsert = async (req, param) => {
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...`
// );
let detail = [];
reservation_number = [];
for (let index = 0; index < getReservationPending.length; index++) {
reservation_number.push(getReservationPending[index].c_reservation_no);
let reservation = await model.findReservation(
getReservationPending[index].c_reservation_no
);
const detail = [];
reservation_number = getReservationPending.map((pending) => pending.c_reservation_no);
const reservations = await model.findReservationDetails(reservation_number);
const detailByNumber = new Map(reservations.map((reservation) => [reservation.c_reservation_no, reservation]));
for (const number of reservation_number) {
const reservation = detailByNumber.get(String(number));
if (!reservation) {
result = {
@@ -1760,9 +1741,6 @@ const loadingBalanceInsert = async (req, param) => {
// balance
// )} [FLAG] : ${JSON.stringify(flag)}`
// );
console.log("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM");
console.log(insertLoadingBalance);
if (insertLoadingBalance > 0) {
result = {
code: '00',
@@ -299,28 +299,45 @@ let inquiryByCardNumber = (cardNumber, startDate, endDate) => {
return result;
};
// FIND RESERVATION LOADED
const findReservationLoaded = (reservationID) => {
let result = knex('trx.t_d_load_balance')
.leftJoin(
'trx.t_d_load_balance_detail',
'trx.t_d_load_balance.i_load_balance',
'trx.t_d_load_balance_detail.i_load_balance'
// Satu query untuk reservasi dan hasil load aktif yang relevan dengan tahap validasi.
function findReservationsWithLoadedBalance(reservationNumbers) {
return knex('trx.t_d_reservation_balance as reservation')
.distinctOn('reservation.c_reservation_no')
.select(
'reservation.c_reservation_no',
'loaded.i_load_balance as loaded_id',
'loaded.c_load_balance_no as loaded_number',
'loaded.d_load_balance as loaded_at'
)
.where('trx.t_d_load_balance_detail.i_reservation_balance', reservationID)
.where('trx.t_d_load_balance.c_status', 'A')
.first();
return result;
};
.joinRaw(`
LEFT JOIN LATERAL (
SELECT balance.i_load_balance, balance.c_load_balance_no, balance.d_load_balance
FROM trx.t_d_load_balance_detail detail
JOIN trx.t_d_load_balance balance ON balance.i_load_balance = detail.i_load_balance
WHERE detail.i_reservation_balance = reservation.i_reservation_balance
AND reservation.c_status = 'A'
AND balance.c_status = 'A'
ORDER BY balance.i_load_balance
LIMIT 1
) loaded ON TRUE
`)
.whereIn('reservation.c_reservation_no', reservationNumbers)
.where('reservation.c_status', '!=', 'X')
.orderBy(['reservation.c_reservation_no', 'reservation.i_reservation_balance']);
}
// FIND RESERVATION
const findReservation = (reservationNumber) => {
let result = knex('trx.t_d_reservation_balance')
.where('c_reservation_no', reservationNumber)
function findReservationDetails(reservationNumbers) {
return knex('trx.t_d_reservation_balance')
.distinctOn('c_reservation_no')
.select(
'c_reservation_no', 'i_reservation_balance', 'i_reservation_amount',
'i_issuer', 'c_issuer_code', 'c_issuer_name', 'i_issuer_fee',
'i_channel', 'c_channel_code', 'c_channel_name', 'i_channel_fee'
)
.whereIn('c_reservation_no', reservationNumbers)
.where('c_status', '!=', 'X')
.first();
return result;
};
.orderBy(['c_reservation_no', 'i_reservation_balance']);
}
// INSERT LOADING BALANCE
const insertLoadingBalance = async (
@@ -336,7 +353,8 @@ const insertLoadingBalance = async (
) => {
return await knex
.transaction((trx) => {
knex('trx.t_d_load_balance')
// Mengembalikan chain memastikan kegagalan SQL memicu rollback otomatis.
return knex('trx.t_d_load_balance')
.transacting(trx)
.insert(data)
.returning('i_load_balance')
@@ -432,25 +450,13 @@ const insertLoadingBalance = async (
i_balance: balance,
c_flag: flag,
});
})
.then(trx.commit)
.catch((error) => {
console.log("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
console.log(error);
trx.rollback
});
})
.then((result) => {
// console.log("result insertLoadingBalance", result);
winston.logger.debug(`XXXXXXXXXXX1 : ${result}`);
winston.logger.debug(`XXXXXXXXXXX2 : ${JSON.stringify(result)}`);
return result.rowCount;
})
.catch((error) => {
// console.log("error.message insertLoadingBalance", error.message);
winston.logger.debug(`YYYYYYYYYYY1 : ${error}`);
winston.logger.debug(`YYYYYYYYYYY2 : ${JSON.stringify(error)}`);
winston.logger.error(`Load balance insert rolled back | sqlstate=${error.code || 'UNKNOWN'}`);
return error.message;
});
};
@@ -1176,8 +1182,8 @@ module.exports = {
getBIRegulationStatus,
getMaxAmountOnTheCard,
getMaxTopupPerMonth,
findReservationLoaded,
findReservation,
findReservationsWithLoadedBalance,
findReservationDetails,
insertLoadingBalance,
updateLoadingBalance,
insertLoadingBalanceHistoryOnly,
@@ -78,6 +78,17 @@ const validate = (method) => {
// *Description:*
// proses yang digunakan untuk melaporkan data transaksi topup online dari partner ke sistem CMS sebagai data rekonsialisasi
function alreadyReconciledResponse(reconciliation) {
return {
code: '04',
message: `success. Transaction has been recon at ${reconciliation.d_payment_recon}`,
data: {
payment_recon_no: reconciliation.c_payment_recon_no,
recon_date: reconciliation.d_payment_recon,
},
};
}
const paymentRecon = async (req, res) => {
try {
// generate unique code
@@ -136,8 +147,6 @@ const paymentRecon = async (req, res) => {
return res.status(200).json(result);
}
console.log(getPartner);
// check payment recon status is enable
if (getPartner.b_payment_recon != true) {
result = {
@@ -196,16 +205,7 @@ const paymentRecon = async (req, res) => {
// jika reservastion number yang di request sudah berhasil di recon sebelumnya
if (checkReservationNumberAndAmountAlreadyRecon) {
result = {
code: '04',
message: `success. Transaction has been recon at ${checkReservationNumberAndAmountAlreadyRecon.d_payment_recon}`,
data: {
payment_recon_no:
checkReservationNumberAndAmountAlreadyRecon.c_payment_recon_no,
recon_date:
checkReservationNumberAndAmountAlreadyRecon.d_payment_recon,
},
};
result = alreadyReconciledResponse(checkReservationNumberAndAmountAlreadyRecon);
// log warn
winston.logger.warn(
@@ -453,67 +453,25 @@ const paymentRecon = async (req, res) => {
return res.status(200).json(result);
}
let data = {
reservation_number: reservation_number,
payment_recon_no: PaymentReconNumber,
date: date,
time: now,
};
const responseData = { payment_recon_no: PaymentReconNumber, recon_date: now };
const committed = await model.completePaymentRecon({
date, time: now, partnerId: partner_id, partnerCode: getPartner.partner_code,
paymentReconNumber: PaymentReconNumber, bankRef: bank_ref, reservationNumber: reservation_number,
amount, expectedAmount: totalAmount, responseData,
});
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: updating payment recon number...`
// );
let update = await model.updatePaymentReconNo(data);
if (!update) {
result = {
if (!committed) {
const already = await model.checkReservationNumberAndAmountAlreadyRecon(reservation_number);
result = already ? alreadyReconciledResponse(already) : {
code: '428',
message:
'failed recon. The other transaction with same data is running.',
data: {
payment_recon_no: PaymentReconNumber,
recon_date: now,
},
message: 'failed recon. The other transaction with same data is running.',
data: responseData,
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE PAYMENT-RECON ]: ${JSON.stringify(result)}`
);
winston.logger.warn(`${uniqueCode} [ RESPONSE PAYMENT-RECON ]: ${JSON.stringify(result)}`);
return res.status(200).json(result);
}
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
// );
result = {
code: '00',
message: 'success',
data: {
payment_recon_no: PaymentReconNumber,
recon_date: now,
},
};
// insert payment recon transaction
await model.insertPaymentReconTransaction(
date,
now,
getPartner.partner_code,
PaymentReconNumber,
bank_ref,
reservation_number,
amount,
'S',
'SUCCESS',
result.code,
result.message.toUpperCase(),
result.data
);
result = { code: '00', message: 'success', data: responseData };
// log info
winston.logger.info(
@@ -86,18 +86,25 @@ const checkReservationNumberAndAmountAlreadyRecon = (reservationNumber) => {
return result;
};
// UPDATE PAYMENT RECON
const updatePaymentReconNo = (data) => {
let result = knex('trx.t_d_reservation_balance')
.update({
c_payment_recon_no: data.payment_recon_no,
d_payment: data.date,
d_payment_recon: data.time,
})
.whereNull('c_payment_recon_no')
.where('c_reservation_no', data.reservation_number);
return result;
};
// Klaim dan audit sukses harus commit bersama agar retry tidak meninggalkan status parsial.
function completePaymentRecon({ date, time, partnerId, partnerCode, paymentReconNumber,
bankRef, reservationNumber, amount, expectedAmount, responseData }) {
return knex.transaction(async (trx) => {
const updated = await trx('trx.t_d_reservation_balance')
.where({ c_reservation_no: reservationNumber, i_partner: partnerId, i_reservation_amount: expectedAmount })
.whereNull('c_payment_recon_no')
.where('c_status', '!=', 'X')
.update({ c_payment_recon_no: paymentReconNumber, d_payment: date, d_payment_recon: time });
if (updated === 0) return false;
if (updated !== 1) throw new Error('Payment reconciliation matched more than one reservation');
await insertPaymentReconTransaction(
date, time, partnerCode, paymentReconNumber, bankRef, reservationNumber, amount,
'S', 'SUCCESS', '00', 'SUCCESS', responseData, trx
);
return true;
});
}
// INSERT PAYMENT RECON
const insertPaymentReconTransaction = (
@@ -112,9 +119,10 @@ const insertPaymentReconTransaction = (
statusName,
responseCode,
responseMessage,
responseData
responseData,
connection = knex
) => {
let result = knex('payment.t_d_payment_recon').insert({
let result = connection('payment.t_d_payment_recon').insert({
d_payment: date,
d_payment_recon: now,
c_partner_code: partnerCode,
@@ -171,7 +179,7 @@ module.exports = {
checkReservationCanceledStatus,
checkReservation,
checkReservationNumberAndAmountAlreadyRecon,
updatePaymentReconNo,
completePaymentRecon,
insertPaymentReconTransaction,
insertPaymentReconNumber,
getLastCounterPaymentReconNo,
+16 -54
View File
@@ -680,9 +680,7 @@ const validateSales = async (req, res) => {
let card_product = false;
let { card_number } = req.body;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-SALES ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`);
// CHECK VALIDATOR
let err = validationResult(req, res);
@@ -867,9 +865,7 @@ const validateTopup = async (req, res) => {
let dataCard = {};
let result = {};
let { card_number, amount, last_balance } = req.body;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-TOPUP ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-TOPUP ]`);
// CHECK VALIDATOR
let err = validationResult(req, res);
@@ -911,11 +907,10 @@ const validateTopup = async (req, res) => {
dataCard = dataCard.detail;
const card_status = dataCard.c_status;
console.log('CARD_STATUS', card_status);
winston.logger.debug(`${uniqueCode} [ VALIDATE-TOPUP CARD STATUS ] status=${card_status}`);
// Status valid => Persoed (P) atau Active (A)
if (card_status != 'P' && card_status != 'A') {
console.log('CARD_STATUS22', card_status);
if (card_status == 'B') {
result = {
code: '445',
@@ -994,7 +989,6 @@ const validateTopup = async (req, res) => {
};
return res.status(200).json(result);
} catch (error) {
console.log('errrrrpr', error);
// create log
winston.logger.error(
`[ RESPONSE VALIDATE-TOPUP ]: 500 internal server error - backend server | ${error.message}`
@@ -1020,9 +1014,7 @@ const checkBlacklist = async (req, res) => {
let result = {};
let { card_number } = req.body;
console.log(
`${uniqueCode} [ REQUEST CHECK-BLACKLIST ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST CHECK-BLACKLIST ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -1095,9 +1087,7 @@ const validateRedeem = async (req, res) => {
let dataCardReplacement = {};
let { card_number, station_code } = req.body;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-REDEEM ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REDEEM ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -1414,11 +1404,7 @@ const validateReplacement = async (req, res) => {
let last_balance = null;
let is_warranty = false;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-REPLACEMENT ]: ${JSON.stringify(
req.body
)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REPLACEMENT ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -1835,11 +1821,7 @@ const validateNewCardReplacement = async (req, res) => {
let result = {};
let { card_number } = req.body;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify(
req.body
)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -2024,11 +2006,7 @@ const replacementConfirm = async (req, res) => {
let uniqueCode = unique_code;
let dataCardReplacement = {};
console.log(
`${uniqueCode} [ REQUEST REPLACEMENT-CONFIRM ]: ${JSON.stringify(
req.body
)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST REPLACEMENT-CONFIRM ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -2379,9 +2357,7 @@ const confirmRedeem = async (req, res) => {
let { card_number, security_code } = req.body;
let dataCardRedeem = {};
console.log(
`${uniqueCode} [ REQUEST REDEEM-CONFIRM ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST REDEEM-CONFIRM ]`);
//CHECK VALIDATOR
let err = validationResult(req, res);
@@ -2608,9 +2584,7 @@ const confirmSales = async (req, res) => {
created_by,
device_time,
} = req.body;
console.log(
`${uniqueCode} [ REQUEST VALIDATE-SALES ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`);
// CHECK VALIDATOR
let err = validationResult(req, res);
@@ -2721,11 +2695,7 @@ const getLastBalanceCTS = async (req, res) => {
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
console.log(
`${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]: ${JSON.stringify(
req.body
)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]`);
//CARD REPLACEMENT VALIDATION
const dataCard = await model.getCardReplacementScheduler();
@@ -2928,7 +2898,7 @@ const completeDataSalesInternal = async (req, res) => {
let uniqueCode = helper.getUniqueCode();
let result = {};
console.log(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL ]`);
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL ]`);
// GET PPN FROM GLOBAL PARAMETER
let ppn = await model.getPPNCardSales();
@@ -2946,15 +2916,11 @@ const completeDataSalesInternal = async (req, res) => {
return res.status(200).json(result);
}
console.log(
`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - PPN ${ppn.c_value} % ]`
);
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - PPN ${ppn.c_value} % ]`);
ppn = parseFloat(ppn.c_value);
console.log(
`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - UPDATE DATA ]`
);
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - UPDATE DATA ]`);
//COMPLETING DATA SALES INTERNAL
const response = await model.completingDataSalesInternal(ppn);
@@ -2979,11 +2945,7 @@ const completeDataSalesInternal = async (req, res) => {
data: {},
};
console.log(
`${uniqueCode} [ COMPLETING DATA SALES INTERNAL SUCCESS : ${JSON.stringify(
result
)} ]`
);
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL SUCCESS ] code=${result.code}`);
return res.status(200).json(result);
} catch (error) {
// create log
@@ -3007,7 +2969,7 @@ const completeDataSalesInternalV2 = async (req, res) => {
let uniqueCode = helper.getUniqueCode();
let result = {};
console.log(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL V2 ]`);
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL V2 ]`);
// GET PPN FROM GLOBAL PARAMETER
let ppn = await model.getPPNCardSales();
@@ -158,7 +158,6 @@ const callbackOy = async (req, res) => {
let axios = require('axios');
const url = urlCMS + '/api/redeem/notifemail';
console.log('urlCMS', url);
// let resp = await axios.post(url, body, config);
const responseMail = await axios({
@@ -115,9 +115,7 @@ const checkReservation = async (req, res) => {
// `${uniqueCode} [ REQUEST RESERVATION-CHECK ]: ${JSON.stringify(req.body)}`
// );
console.log(
`${uniqueCode} [ REQUEST RESERVATION-CHECK ]: ${JSON.stringify(req.body)}`
);
winston.logger.info(`${uniqueCode} [ REQUEST RESERVATION-CHECK ]`);
// trim card number
card_number = card_number.trim();
@@ -281,9 +279,7 @@ const checkReservation = async (req, res) => {
// `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(result)}`
// );
console.log(
`${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(result)}`
);
winston.logger.info(`${uniqueCode} [ RESPONSE RESERVATION-CHECK ] code=${result.code}`);
return res.status(200).json(result);
} catch (error) {
@@ -0,0 +1,79 @@
const model = require('../modules/loadbalance/loadbalance.model');
const { loadingBalanceInsert } = require('../modules/loadbalance/loadbalance.controller');
jest.mock('../helpers/helper', () => ({}));
jest.mock('../helpers/winston.logger', () => ({ logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() } }));
jest.mock('../middlewares/redis.middleware', () => ({ getLoadBalanceNumberSequence2: async () => 1 }));
jest.mock('../modules/loadbalance/loadbalance.model', () => ({
getPartner: jest.fn(),
findReservationsWithLoadedBalance: jest.fn(),
getLastHistory: jest.fn(),
getFraudTransaction: jest.fn(),
getReservationPendingWithoutFraud: jest.fn(),
insertLoadBalanceNumber: jest.fn(),
findReservationDetails: jest.fn(),
insertLoadingBalance: jest.fn(),
}));
const req = { partner_id_token: '1' };
const input = { uid: 'fixture', amount: 30, reservation_number: ['RBL2', 'RBL1'] };
const loaded = { c_reservation_no: 'RBL1', loaded_id: 10, loaded_number: 'LBL1', loaded_at: '2026-11-23' };
beforeEach(() => {
jest.resetAllMocks();
model.getPartner.mockResolvedValue({ i_partner: '1', partner_code: 'TEST' });
});
test.each([
[['missing', 'RBL1'], '414'],
[['RBL1', 'missing'], '00'],
])('uses input order when a batch contains a missing and an already-loaded reservation', async (numbers, code) => {
model.findReservationsWithLoadedBalance.mockResolvedValue([loaded]);
const result = await loadingBalanceInsert(req, { ...input, reservation_number: numbers });
expect(result.code).toBe(code);
if (code === '00') expect(result.data.load_balance_number).toBe('LBL1');
expect(model.findReservationsWithLoadedBalance).toHaveBeenCalledTimes(1);
expect(model.findReservationsWithLoadedBalance).toHaveBeenCalledWith(numbers);
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
});
function setupPending() {
model.findReservationsWithLoadedBalance.mockResolvedValue([
{ c_reservation_no: 'RBL1' }, { c_reservation_no: 'RBL2' },
]);
model.getFraudTransaction.mockResolvedValue([]);
model.getReservationPendingWithoutFraud.mockResolvedValue([
{ c_reservation_no: 'RBL2', i_reservation_amount: 20 },
{ c_reservation_no: 'RBL1', i_reservation_amount: 10 },
]);
model.insertLoadBalanceNumber.mockResolvedValue({ rowCount: 1 });
}
test('fetches pending details once and preserves the pending order and amounts', async () => {
setupPending();
model.findReservationDetails.mockResolvedValue([
{ c_reservation_no: 'RBL1', i_reservation_balance: 1, i_reservation_amount: 10 },
{ c_reservation_no: 'RBL2', i_reservation_balance: 2, i_reservation_amount: 20 },
]);
model.insertLoadingBalance.mockResolvedValue(1);
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({ code: '00' });
expect(model.findReservationDetails).toHaveBeenCalledTimes(1);
expect(model.findReservationDetails).toHaveBeenCalledWith(['RBL2', 'RBL1']);
const [, details, numbers] = model.insertLoadingBalance.mock.calls[0];
expect(numbers).toEqual(['RBL2', 'RBL1']);
expect(details).toMatchObject([
{ c_reservation_no: 'RBL2', i_amount: 20 },
{ c_reservation_no: 'RBL1', i_amount: 10 },
]);
});
test('preserves code 414 if a pending reservation is absent at the new read', async () => {
setupPending();
model.findReservationDetails.mockResolvedValue([]);
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({ code: '414' });
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
});
+34 -79
View File
@@ -1,95 +1,50 @@
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { createServer } = require('node:http');
const { once } = require('node:events');
const { EventEmitter } = require('node:events');
const createAuditArchive = require('../helpers/audit-archive');
const createLokiDelivery = require('../helpers/loki-delivery');
const { createStdoutWriter, formatLog } = require('../helpers/stdout-log');
const createRedisOperations = require('../helpers/redis-operations');
test('an empty Loki URL still accepts audit events locally', () => {
const append = jest.fn();
const previous = process.env.LOKI_URL;
process.env.LOKI_URL = '';
try {
jest.isolateModules(() => {
jest.doMock('../helpers/audit-archive', () => () => ({ append }));
const { log } = require('../helpers/loki');
expect(() => log.log({ level: 'info', request_id: 'local-only' })).not.toThrow();
expect(append).toHaveBeenCalledWith(expect.stringContaining('local-only'), expect.any(Number));
});
} finally {
jest.dontMock('../helpers/audit-archive');
if (previous === undefined) delete process.env.LOKI_URL;
else process.env.LOKI_URL = previous;
}
});
test('a stalled Loki upload is cancelled, the remote queue stays bounded, and every audit stays on disk', async () => {
test('stdout backpressure preserves every audit and a stale Loki URL does not trigger HTTP', () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'topup-audit-'));
const audit = createAuditArchive(directory);
let stall = true;
let firstResponse;
let markRequest;
const sent = new Promise((resolve) => { markRequest = resolve; });
const server = createServer((req, res) => {
req.resume();
if (stall) {
firstResponse = res;
markRequest();
} else {
res.writeHead(204).end();
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
let resolveFailure;
let resolveDrained;
const failed = new Promise((resolve) => { resolveFailure = resolve; });
const drained = new Promise((resolve) => { resolveDrained = resolve; });
const batches = [];
const discarded = jest.fn();
const delivery = createLokiDelivery({
url: `http://127.0.0.1:${server.address().port}`,
maxEntries: 3,
maxBytes: 320,
batchEntries: 1,
timeoutMs: 250,
intervalMs: 15,
onQueue(count, bytes) {
batches.push({ count, bytes });
if (count === 0) resolveDrained();
},
onDiscard: discarded,
onFailure: resolveFailure,
});
const previous = process.env.LOKI_URL;
process.env.LOKI_URL = 'http://127.0.0.1:1';
const stream = new EventEmitter();
stream.writable = true;
stream.writableNeedDrain = false;
stream.write = jest.fn((line, callback) => { callback(); });
const onSkip = jest.fn();
const writeStdoutLine = createStdoutWriter(stream, onSkip);
try {
const append = (id) => {
const line = JSON.stringify({ request_id: id, trx_id: 'ad01', status_code: '00' });
audit.append(line, Date.now());
delivery.enqueue(line, 'info');
};
append(0);
await sent;
for (let id = 1; id < 6; id++) append(id);
const disconnected = once(firstResponse, 'close');
await failed;
stall = false;
await disconnected;
await drained;
expect(batches.every(({ count, bytes }) => count <= 3 && bytes <= 320)).toBe(true);
expect(discarded).toHaveBeenCalledWith('capacity', 1);
jest.isolateModules(() => {
jest.doMock('../helpers/audit-archive', () => () => audit);
jest.doMock('../helpers/stdout-log', () => ({ formatLog, writeStdoutLine }));
jest.doMock('axios', () => { throw new Error('Audit must never load an HTTP client'); });
const { record } = require('../helpers/response-audit');
record({ level: 'info', event: 'http_response', request_id: 'first', message: 'Line one\nLine two' });
stream.writableNeedDrain = true;
record({ level: 'info', event: 'http_response', request_id: 'slow-console' });
stream.writableNeedDrain = false;
record({ level: 'error', event: 'http_response', request_id: 'recovered' });
});
expect(onSkip).toHaveBeenCalledWith('backpressure');
expect(stream.write).toHaveBeenCalledTimes(2);
const emitted = stream.write.mock.calls.map(([line]) => JSON.parse(line));
expect(emitted.map(({ request_id }) => request_id)).toEqual(['first', 'recovered']);
expect(emitted[0]).toMatchObject({ app: 'topuponline', message: 'Line one\nLine two' });
const [file] = fs.readdirSync(directory);
const entries = fs.readFileSync(path.join(directory, file), 'utf8').trim().split('\n').map(JSON.parse);
expect(entries.map(({ request_id }) => request_id)).toEqual([0, 1, 2, 3, 4, 5]);
const archived = fs.readFileSync(path.join(directory, file), 'utf8').trim().split('\n').map(JSON.parse);
expect(archived.map(({ request_id }) => request_id)).toEqual(['first', 'slow-console', 'recovered']);
} finally {
delivery.close();
jest.dontMock('../helpers/audit-archive');
jest.dontMock('../helpers/stdout-log');
jest.dontMock('axios');
if (previous === undefined) delete process.env.LOKI_URL;
else process.env.LOKI_URL = previous;
audit.close();
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
for (const file of fs.readdirSync(directory)) fs.unlinkSync(path.join(directory, file));
fs.rmdirSync(directory);
}
+11 -7
View File
@@ -2,12 +2,12 @@ const express = require('express');
const request = require('supertest');
const responseTime = require('response-time');
const knex = require('../../infrastructure/database/knex');
const winstonLoki = require('../helpers/loki');
const responseAudit = require('../helpers/response-audit');
const { logger } = require('../helpers/getbodyrequest');
const histograms = Object.values(require('../helpers/prometheusmetrics'));
jest.mock('../../infrastructure/database/knex', () => jest.fn());
jest.mock('../helpers/loki', () => ({ log: { log: jest.fn() } }));
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
jest.mock('winston-daily-rotate-file', () => {
const winston = require('winston');
const Transport = require('winston-transport');
@@ -57,14 +57,18 @@ test('distinct transaction IDs and latencies share one histogram series per buck
expect(metric.values.some((entry) => entry.labels.le === 1000)).toBe(true);
}
const logs = winstonLoki.log.log.mock.calls.map(([info]) => info);
const logs = responseAudit.record.mock.calls.map(([info]) => info);
const requestIds = responses.map(({ headers }) => headers['x-request-id']);
expect(new Set(requestIds).size).toBe(transactionIds.length);
responses.forEach(({ headers, body }, index) => {
const record = logs.find((entry) => entry.request_id === headers['x-request-id']);
expect(headers['x-response-time']).toMatch(/ms$/);
expect(body.data.trxID).toBe(transactionIds[index]);
expect(record).toMatchObject({ event: 'http_response', trx_id: transactionIds[index] });
expect(record).toMatchObject({
event: 'http_response',
http_status: 200,
trx_id: transactionIds[index],
});
expect(record.response_time_ms).toBeGreaterThanOrEqual(200 + index * 100);
expect(record).not.toHaveProperty('labels');
});
@@ -79,7 +83,7 @@ test('logs the valid request transaction ID on HSM failure even if issuer lookup
const response = await request(app).post('/api/topup2').send({ trxID: 'ABCD', card_number: 'fixture-card' });
expect(response.status).toBe(200);
const [info] = winstonLoki.log.log.mock.calls[0];
const [info] = responseAudit.record.mock.calls[0];
expect(info).toMatchObject({
level: 'error',
status_code: '5001',
@@ -101,8 +105,8 @@ test('a slow issuer lookup is shared and audit records are emitted while it is p
try {
await Promise.all(Array.from({ length: 12 }, () => request(app).post('/api/topup3')));
expect(timeout).toHaveBeenCalledTimes(1);
expect(winstonLoki.log.log).toHaveBeenCalledTimes(12);
expect(winstonLoki.log.log).toHaveBeenCalledWith(expect.objectContaining({
expect(responseAudit.record).toHaveBeenCalledTimes(12);
expect(responseAudit.record).toHaveBeenCalledWith(expect.objectContaining({
issuer_name: 'UNDEFINED',
partner_id: '9917',
}));
@@ -0,0 +1,63 @@
const express = require('express');
const request = require('supertest');
const model = require('../modules/paymentrecon/paymentrecon.model');
const { paymentRecon, validate } = require('../modules/paymentrecon/paymentrecon.controller');
jest.mock('../helpers/helper', () => ({ getUniqueCode: () => 'fixture', randomNumberInt: () => 0 }));
jest.mock('../helpers/winston.logger', () => ({ logger: {
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
} }));
jest.mock('../modules/paymentrecon/paymentrecon.model', () => ({
getPartnerByID: jest.fn(),
checkReservation: jest.fn(),
checkReservationNumberAndAmountAlreadyRecon: jest.fn(),
getLastCounterPaymentReconNo: jest.fn(),
insertPaymentReconNumber: jest.fn(),
checkReservationCanceledStatus: jest.fn(),
checkReservationNumberAndAmount: jest.fn(),
completePaymentRecon: jest.fn(),
insertPaymentReconTransaction: jest.fn(),
}));
const app = express();
app.use(express.json());
app.post('/api/payment-recon', (req, res, next) => {
req.partner_id_token = '1';
next();
}, validate('paymentRecon'), paymentRecon);
const body = { date: '2026-11-23', reservation_number: 'RBL1', bank_ref: 'BANK1', amount: 1000 };
beforeEach(() => {
jest.resetAllMocks();
model.getPartnerByID.mockResolvedValue({ b_payment_recon: true, partner_code: 'TST' });
model.checkReservation.mockResolvedValue({ i_partner: 1 });
model.insertPaymentReconNumber.mockResolvedValue({ rowCount: 1 });
model.checkReservationNumberAndAmount.mockResolvedValue({ total_transaction: 1, total_amount: '1000' });
});
test('the loser of a concurrent reconciliation returns the winner’s number and code 04', async () => {
const winner = { c_payment_recon_no: 'RC-WINNER', d_payment_recon: '2026-11-23 10:00:00' };
model.checkReservationNumberAndAmountAlreadyRecon
.mockResolvedValueOnce(undefined)
.mockResolvedValueOnce(winner);
model.completePaymentRecon.mockResolvedValue(false);
const response = await request(app).post('/api/payment-recon').send(body);
expect(response.status).toBe(200);
expect(response.body).toMatchObject({ code: '04', data: { payment_recon_no: 'RC-WINNER' } });
expect(model.completePaymentRecon).toHaveBeenCalledWith(expect.objectContaining({
reservationNumber: 'RBL1', expectedAmount: '1000',
}));
expect(model.insertPaymentReconTransaction).not.toHaveBeenCalled();
});
test('a failed atomic commit returns an error instead of reporting reconciliation success', async () => {
model.completePaymentRecon.mockRejectedValue(new Error('transaction failed'));
const response = await request(app).post('/api/payment-recon').send(body);
expect(response.status).toBe(200);
expect(response.body.code).toBe('500');
expect(model.insertPaymentReconTransaction).not.toHaveBeenCalled();
});
+31
View File
@@ -16,6 +16,7 @@ request ID, atau durasi minimum.
- Loki menyimpan `trx_id`, `request_id`, dan `response_time_ms` di isi JSON log.
ID HSM dicatat dalam huruf kecil. Log respons sukses dipublikasikan di level
`info`, sedangkan respons gagal dipublikasikan di level `error`.
- `http_status` memuat status HTTP, sedangkan `status_code` memuat kode aplikasi.
```logql
{app="topuponline"} |= "http_response" | json | event="http_response" | trx_id="a1b2"
@@ -29,6 +30,36 @@ request ID, atau durasi minimum.
{app="topuponline"} |= "http_response" | json | event="http_response" | response_time_ms >= 1000 | __error__=""
```
## Mengambil stdout melalui Promtail
Aplikasi menulis satu objek JSON per baris ke stdout. URL tujuan Loki berada
di konfigurasi Promtail. Tambahkan label stream `app=topuponline` di target
scrape agar dashboard dan kueri di atas tetap menemukan log.
Untuk service yang menulis stdout ke file, arahkan `__path__` ke file stdout
yang sebenarnya. Contoh ini berlaku untuk file yang memuat pesan aplikasi
langsung sebagai JSONL.
```yaml
scrape_configs:
- job_name: topuponline
static_configs:
- targets: [localhost]
labels:
app: topuponline
__path__: /var/log/onlinetopup/stdout*.log
```
Jika Promtail membaca file log Docker dengan driver `json-file`, gunakan stage
`docker` pada target tersebut untuk membuka bungkus log kontainer. Gunakan satu
sumber ingest untuk log yang sama agar event stdout dan arsip tidak masuk ganda.
Pertahankan ID dan durasi sebagai field JSON. Gunakan `event=http_response`
untuk mencari respons transaksi dan `event=application_log` untuk log proses.
Grafana Explore dapat merapikan tampilan dengan
`| line_format "{{.method}} {{.route}} HTTP {{.http_status}} app={{.status_code}} {{.response_time_ms}}ms request={{.request_id}} trx={{.trx_id}}"`
setelah `| json`. Jika proses memakai PM2, temukan nama file stdout yang
dipakai instance melalui `pm2 describe`.
## Menyesuaikan dashboard yang sudah terpasang
Gunakan time picker untuk filter tanggal dan hapus filter atau variabel
+20 -11
View File
@@ -2,8 +2,9 @@
## Arsip dan Loki
Setiap respons yang dipantau ditulis sebagai JSONL sebelum salinannya masuk
antrean Loki. Arsip dapat dicari dengan `request_id`, `trx_id`,
Setiap respons yang dipantau ditulis sebagai JSONL sebelum salinannya dikirim
ke stdout. Promtail mengambil stdout dari log process manager atau kontainer
dan mengirimkannya ke Loki. Arsip dapat dicari dengan `request_id`, `trx_id`,
`reservation_number`, atau `load_balance_number` jika tersedia. Riwayat
transaksi PostgreSQL tetap menjadi sumber status bisnis.
@@ -11,16 +12,24 @@ Gunakan `TOPUP_AUDIT_DIR` pada volume persisten yang dapat ditulis oleh proses
aplikasi. Path bawaan adalah `./lokiLog/audit`. File dibagi per tanggal UTC dan
proses. Atur pemantauan ruang disk dan pengarsipan sesuai retensi audit organisasi.
Aplikasi tidak menghapus file JSONL. Jika penulisan gagal, aplikasi menaikkan
`topuponline_audit_write_errors_total` dan mencoba stderr selama stream masih
menerima data. Ketersediaan audit saat disk gagal bergantung pada penampung
stderr atau Loki yang terpisah.
`topuponline_audit_write_errors_total` dan tetap mencoba mencatat ke stdout.
Ketersediaan audit saat disk gagal bergantung pada penampung stdout yang terpisah.
Salinan Loki dibatasi 2.000 entri dan sekitar 2 MiB data serialisasi per proses,
termasuk batch yang sedang dikirim. Upload dibatalkan setelah 5 detik. Saat
antrean penuh, metrik `topuponline_loki_copies_discarded_total` menunjukkan
jumlah salinan yang dilepas. Gunakan arsip JSONL untuk menemukan entri tersebut.
Metrik `topuponline_loki_buffer_entries`, `topuponline_loki_buffer_bytes`, dan
`topuponline_loki_delivery_errors_total` menunjukkan penumpukan serta kegagalan.
Tambahkan variabel ke environment service atau file `.env` yang dibaca dari
direktori kerja aplikasi. Contoh di Linux untuk volume yang sudah dipasang.
```dotenv
TOPUP_AUDIT_DIR=/var/lib/onlinetopup/audit
```
Restart aplikasi melalui service manager setelah mengubah environment. Lakukan
satu request ke endpoint yang dipantau dan cocokkan nilai `X-Request-Id` dengan
arsip JSONL pada direktori tersebut. Gunakan akun service yang sama saat
memeriksa izin tulis, dan simpan arsip setiap replika di volume persisten.
Jika stdout sedang tersendat, aplikasi melewatkan salinan terminal dan menaikkan
`topuponline_stdout_copies_skipped_total`. Cari audit respons tersebut di arsip
JSONL. Log Winston tetap memiliki salinan di file log aplikasi sesuai levelnya.
```powershell
rg --fixed-strings '<request-id>' ./lokiLog/audit
-513
View File
@@ -33,7 +33,6 @@
"superagent": "^10.2.3",
"winston": "^3.7.2",
"winston-daily-rotate-file": "^4.7.1",
"winston-loki": "^6.0.6",
"ws": "^8.5.0",
"xml2js": "^0.6.2"
},
@@ -630,17 +629,6 @@
"kuler": "^2.0.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.6.0.tgz",
"integrity": "sha512-zq/ay+9fNIJJtJiZxdTnXS20PllcYMX3OE23ESc4HK/bdYu3cOWYVhsOhVnXALfU/uqJIxn5NBPd9z4v+SfoSg==",
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.1.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/core/node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -648,16 +636,6 @@
"license": "0BSD",
"optional": true
},
"node_modules/@emnapi/runtime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.6.0.tgz",
"integrity": "sha512-obtUmAHTMjll499P+D9A3axeJFlhdjOWdKUNs/U6QIGT7V5RjcUW1xToAzjvmgTSQhDbYn/NwfTRoJcQ2rNBxA==",
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime/node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -665,16 +643,6 @@
"license": "0BSD",
"optional": true
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.1.0.tgz",
"integrity": "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==",
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads/node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -1451,306 +1419,6 @@
"node-pre-gyp": "bin/node-pre-gyp"
}
},
"node_modules/@napi-rs/snappy-android-arm-eabi": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-android-arm-eabi/-/snappy-android-arm-eabi-7.3.3.tgz",
"integrity": "sha512-d4vUFFzNBvazGfB/KU8MnEax6itTIgRWXodPdZDnWKHy9HwVBndpCiedQDcSNHcZNYV36rx034rpn7SAuTL2NA==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-android-arm64": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-android-arm64/-/snappy-android-arm64-7.3.3.tgz",
"integrity": "sha512-Uh+w18dhzjVl85MGhRnojb7OLlX2ErvMsYIunO/7l3Frvc2zQvfqsWsFJanu2dwqlE2YDooeNP84S+ywgN9sxg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-darwin-arm64": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-darwin-arm64/-/snappy-darwin-arm64-7.3.3.tgz",
"integrity": "sha512-AmJn+6yOu/0V0YNHLKmRUNYkn93iv/1wtPayC7O1OHtfY6YqHQ31/MVeeRBiEYtQW9TwVZxXrDirxSB1PxRdtw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-darwin-x64": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-darwin-x64/-/snappy-darwin-x64-7.3.3.tgz",
"integrity": "sha512-biLTXBmPjPmO7HIpv+5BaV9Gy/4+QJSUNJW8Pjx1UlWAVnocPy7um+zbvAWStZssTI5sfn/jOClrAegD4w09UA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-freebsd-x64": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-freebsd-x64/-/snappy-freebsd-x64-7.3.3.tgz",
"integrity": "sha512-E3R3ewm8Mrjm0yL2TC3VgnphDsQaCPixNJqBbGiz3NTshVDhlPlOgPKF0NGYqKiKaDGdD9PKtUgOR4vagUtn7g==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm-gnueabihf": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm-gnueabihf/-/snappy-linux-arm-gnueabihf-7.3.3.tgz",
"integrity": "sha512-ZuNgtmk9j0KyT7TfLyEnvZJxOhbkyNR761nk04F0Q4NTHMICP28wQj0xgEsnCHUsEeA9OXrRL4R7waiLn+rOQA==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm64-gnu": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm64-gnu/-/snappy-linux-arm64-gnu-7.3.3.tgz",
"integrity": "sha512-KIzwtq0dAzshzpqZWjg0Q9lUx93iZN7wCCUzCdLYIQ+mvJZKM10VCdn0RcuQze1R3UJTPwpPLXQIVskNMBYyPA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-arm64-musl": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-arm64-musl/-/snappy-linux-arm64-musl-7.3.3.tgz",
"integrity": "sha512-AAED4cQS74xPvktsyVmz5sy8vSxG/+3d7Rq2FDBZzj3Fv6v5vux6uZnECPCAqpALCdTtJ61unqpOyqO7hZCt1Q==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-ppc64-gnu": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-ppc64-gnu/-/snappy-linux-ppc64-gnu-7.3.3.tgz",
"integrity": "sha512-pofO5eSLg8ZTBwVae4WHHwJxJGZI8NEb4r5Mppvq12J/1/Hq1HecClXmfY3A7bdT2fsS2Td+Q7CI9VdBOj2sbA==",
"cpu": [
"ppc64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-riscv64-gnu": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-riscv64-gnu/-/snappy-linux-riscv64-gnu-7.3.3.tgz",
"integrity": "sha512-OiHYdeuwj0TVBXADUmmQDQ4lL1TB+8EwmXnFgOutoDVXHaUl0CJFyXLa6tYUXe+gRY8hs1v7eb0vyE97LKY06Q==",
"cpu": [
"riscv64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-s390x-gnu": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-s390x-gnu/-/snappy-linux-s390x-gnu-7.3.3.tgz",
"integrity": "sha512-66QdmuV9CTq/S/xifZXlMy3PsZTviAgkqqpZ+7vPCmLtuP+nqhaeupShOFf/sIDsS0gZePazPosPTeTBbhkLHg==",
"cpu": [
"s390x"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-x64-gnu": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-x64-gnu/-/snappy-linux-x64-gnu-7.3.3.tgz",
"integrity": "sha512-g6KURjOxrgb8yXDEZMuIcHkUr/7TKlDwSiydEQtMtP3n4iI4sNjkcE/WNKlR3+t9bZh1pFGAq7NFRBtouQGHpQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-linux-x64-musl": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-linux-x64-musl/-/snappy-linux-x64-musl-7.3.3.tgz",
"integrity": "sha512-6UvOyczHknpaKjrlKKSlX3rwpOrfJwiMG6qA0NRKJFgbcCAEUxmN9A8JvW4inP46DKdQ0bekdOxwRtAhFiTDfg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-openharmony-arm64": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-openharmony-arm64/-/snappy-openharmony-arm64-7.3.3.tgz",
"integrity": "sha512-I5mak/5rTprobf7wMCk0vFhClmWOL/QiIJM4XontysnadmP/R9hAcmuFmoMV2GaxC9MblqLA7Z++gy8ou5hJVw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-wasm32-wasi": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-wasm32-wasi/-/snappy-wasm32-wasi-7.3.3.tgz",
"integrity": "sha512-+EroeygVYo9RksOchjF206frhMkfD2PaIun3yH4Zp5j/Y0oIEgs/+VhAYx/f+zHRylQYUIdLzDRclcoepvlR8Q==",
"cpu": [
"wasm32"
],
"license": "MIT",
"optional": true,
"dependencies": {
"@napi-rs/wasm-runtime": "^1.0.3"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@napi-rs/snappy-win32-arm64-msvc": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-arm64-msvc/-/snappy-win32-arm64-msvc-7.3.3.tgz",
"integrity": "sha512-rxqfntBsCfzgOha/OlG8ld2hs6YSMGhpMUbFjeQLyVDbooY041fRXv3S7yk52DfO6H4QQhLT5+p7cW0mYdhyiQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-win32-ia32-msvc": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-ia32-msvc/-/snappy-win32-ia32-msvc-7.3.3.tgz",
"integrity": "sha512-joRV16DsRtqjGt0CdSpxGCkO0UlHGeTZ/GqvdscoALpRKbikR2Top4C61dxEchmOd3lSYsXutuwWWGg3Nr++WA==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/snappy-win32-x64-msvc": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@napi-rs/snappy-win32-x64-msvc/-/snappy-win32-x64-msvc-7.3.3.tgz",
"integrity": "sha512-cEnQwcsdJyOU7HSZODWsHpKuQoSYM4jaqw/hn9pOXYbRN1+02WxYppD3fdMuKN6TOA6YG5KA5PHRNeVilNX86Q==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.0.7.tgz",
"integrity": "sha512-SeDnOO0Tk7Okiq6DbXmmBODgOAb9dp9gjlphokTUxmt8U3liIP1ZsozBahH69j/RJv+Rfs6IwUKHTgQYJ/HBAw==",
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "^1.5.0",
"@emnapi/runtime": "^1.5.0",
"@tybys/wasm-util": "^0.10.1"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
@@ -2151,70 +1819,6 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/@protobufjs/aspromise": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
"integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/base64": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
"integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/codegen": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz",
"integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/eventemitter": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz",
"integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/fetch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz",
"integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==",
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.1",
"@protobufjs/inquire": "^1.1.0"
}
},
"node_modules/@protobufjs/float": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
"integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/inquire": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz",
"integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/path": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
"integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/pool": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
"integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
"license": "BSD-3-Clause"
},
"node_modules/@protobufjs/utf8": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz",
"integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==",
"license": "BSD-3-Clause"
},
"node_modules/@redis/bloom": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz",
@@ -2324,16 +1928,6 @@
"integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
"license": "MIT"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
"integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tybys/wasm-util/node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -2665,15 +2259,6 @@
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
"node_modules/async-exit-hook": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/async-exit-hook/-/async-exit-hook-2.0.1.tgz",
"integrity": "sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==",
"license": "MIT",
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -3053,18 +2638,6 @@
"node-int64": "^0.4.0"
}
},
"node_modules/btoa": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==",
"license": "(MIT OR Apache-2.0)",
"bin": {
"btoa": "bin/btoa.js"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
@@ -7130,12 +6703,6 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -8410,30 +7977,6 @@
"node": ">= 6"
}
},
"node_modules/protobufjs": {
"version": "7.5.4",
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz",
"integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==",
"hasInstallScript": true,
"license": "BSD-3-Clause",
"dependencies": {
"@protobufjs/aspromise": "^1.1.2",
"@protobufjs/base64": "^1.1.2",
"@protobufjs/codegen": "^2.0.4",
"@protobufjs/eventemitter": "^1.1.0",
"@protobufjs/fetch": "^1.1.0",
"@protobufjs/float": "^1.0.2",
"@protobufjs/inquire": "^1.1.0",
"@protobufjs/path": "^1.1.2",
"@protobufjs/pool": "^1.1.0",
"@protobufjs/utf8": "^1.1.0",
"@types/node": ">=13.7.0",
"long": "^5.0.0"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -9076,40 +8619,6 @@
"npm": ">= 3.0.0"
}
},
"node_modules/snappy": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/snappy/-/snappy-7.3.3.tgz",
"integrity": "sha512-UDJVCunvgblRpfTOjo/uT7pQzfrTsSICJ4yVS4aq7SsGBaUSpJwaVP15nF//jqinSLpN7boe/BqbUmtWMTQ5MQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/snappy-android-arm-eabi": "7.3.3",
"@napi-rs/snappy-android-arm64": "7.3.3",
"@napi-rs/snappy-darwin-arm64": "7.3.3",
"@napi-rs/snappy-darwin-x64": "7.3.3",
"@napi-rs/snappy-freebsd-x64": "7.3.3",
"@napi-rs/snappy-linux-arm-gnueabihf": "7.3.3",
"@napi-rs/snappy-linux-arm64-gnu": "7.3.3",
"@napi-rs/snappy-linux-arm64-musl": "7.3.3",
"@napi-rs/snappy-linux-ppc64-gnu": "7.3.3",
"@napi-rs/snappy-linux-riscv64-gnu": "7.3.3",
"@napi-rs/snappy-linux-s390x-gnu": "7.3.3",
"@napi-rs/snappy-linux-x64-gnu": "7.3.3",
"@napi-rs/snappy-linux-x64-musl": "7.3.3",
"@napi-rs/snappy-openharmony-arm64": "7.3.3",
"@napi-rs/snappy-wasm32-wasi": "7.3.3",
"@napi-rs/snappy-win32-arm64-msvc": "7.3.3",
"@napi-rs/snappy-win32-ia32-msvc": "7.3.3",
"@napi-rs/snappy-win32-x64-msvc": "7.3.3"
}
},
"node_modules/socks": {
"version": "2.8.7",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",
@@ -9704,12 +9213,6 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/url-polyfill": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/url-polyfill/-/url-polyfill-1.1.14.tgz",
"integrity": "sha512-p4f3TTAG6ADVF3mwbXw7hGw+QJyw5CnNGvYh5fCuQQZIiuKUswqcznyV3pGDP9j0TSmC4UvRKm8kl1QsX1diiQ==",
"license": "MIT"
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -9883,22 +9386,6 @@
"winston": "^3"
}
},
"node_modules/winston-loki": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/winston-loki/-/winston-loki-6.1.3.tgz",
"integrity": "sha512-DjWtJ230xHyYQWr9mZJa93yhwHttn3JEtSYWP8vXZWJOahiQheUhf+88dSIidbGXB3u0oLweV6G1vkL/ouT62Q==",
"license": "MIT",
"dependencies": {
"async-exit-hook": "2.0.1",
"btoa": "^1.2.1",
"protobufjs": "^7.2.4",
"url-polyfill": "^1.1.12",
"winston-transport": "^4.3.0"
},
"optionalDependencies": {
"snappy": "^7.2.2"
}
},
"node_modules/winston-transport": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
-1
View File
@@ -46,7 +46,6 @@
"superagent": "^10.2.3",
"winston": "^3.7.2",
"winston-daily-rotate-file": "^4.7.1",
"winston-loki": "^6.0.6",
"ws": "^8.5.0",
"xml2js": "^0.6.2"
},
+3 -2
View File
@@ -21,7 +21,8 @@ require('dotenv').config();
moment.locale('id');
const responseTime = require('response-time');
const { logger } = require('../application/helpers/getbodyrequest');
const { lokiMetrics } = require('../application/helpers/loki');
const { auditMetrics } = require('../application/helpers/response-audit');
const { stdoutMetrics } = require('../application/helpers/stdout-log');
const client = require('prom-client');
const register = new client.Registry();
const {
@@ -38,7 +39,7 @@ client.collectDefaultMetrics({ register });
register.registerMetric(topuponline_metrics);
register.registerMetric(topuponline_metrics_response_time);
register.registerMetric(topuponline_metrics_load_balance);
for (const metric of lokiMetrics) register.registerMetric(metric);
for (const metric of [...auditMetrics, ...stdoutMetrics]) register.registerMetric(metric);
app.get('/metrics', (req, res) => {
res.setHeader('Content-Type', register.contentType);