mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Compare commits
3 Commits
5762f218fd
...
572444a114
| Author | SHA1 | Date | |
|---|---|---|---|
| 572444a114 | |||
| 7957bf5a64 | |||
| ff06c45dc5 |
@@ -1,6 +1,7 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
/lokiLog/audit/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
// Satu deskriptor append per proses membatasi memori tanpa menunggu layanan log eksternal.
|
||||
function createAuditArchive(directory) {
|
||||
let day;
|
||||
let descriptor;
|
||||
const runId = randomUUID();
|
||||
|
||||
function append(line, time) {
|
||||
const date = new Date(time).toISOString().slice(0, 10);
|
||||
if (day !== date) {
|
||||
close();
|
||||
fs.mkdirSync(directory, { recursive: true, mode: 0o750 });
|
||||
descriptor = fs.openSync(path.join(directory, `${date}-${process.pid}-${runId}.jsonl`), 'a', 0o640);
|
||||
day = date;
|
||||
}
|
||||
fs.appendFileSync(descriptor, `${line}\n`);
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (descriptor !== undefined) fs.closeSync(descriptor);
|
||||
descriptor = undefined;
|
||||
day = undefined;
|
||||
}
|
||||
|
||||
return { append, close };
|
||||
}
|
||||
|
||||
module.exports = createAuditArchive;
|
||||
@@ -1,9 +1,11 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const winston = require("winston");
|
||||
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,
|
||||
@@ -12,21 +14,7 @@ const {
|
||||
} = require("../helpers/prometheusmetrics");
|
||||
|
||||
const filename = () => {
|
||||
if (!fs.existsSync(`./expresswinstonlog`)) {
|
||||
fs.mkdirSync(`./expresswinstonlog`);
|
||||
}
|
||||
if (!fs.existsSync(`./expresswinstonlog/${moment().format("YYYY")}`)) {
|
||||
fs.mkdirSync(`./expresswinstonlog/${moment().format("YYYY")}`);
|
||||
}
|
||||
if (
|
||||
!fs.existsSync(
|
||||
`./expresswinstonlog/${moment().format("YYYY")}/${moment().format("MM")}`
|
||||
)
|
||||
) {
|
||||
fs.mkdirSync(
|
||||
`./expresswinstonlog/${moment().format("YYYY")}/${moment().format("MM")}`
|
||||
);
|
||||
}
|
||||
fs.mkdirSync(`./expresswinstonlog/${moment().format("YYYY/MM")}`, { recursive: true });
|
||||
|
||||
return `expresswinstonlog/${moment().format("YYYY")}-${moment().format(
|
||||
"MM"
|
||||
@@ -35,7 +23,7 @@ const filename = () => {
|
||||
|
||||
filename();
|
||||
|
||||
const routes = [
|
||||
const routes = new Set([
|
||||
"/api/reservation",
|
||||
"/api/reservation/v2",
|
||||
"/api/loadbalance/request",
|
||||
@@ -47,9 +35,91 @@ const routes = [
|
||||
"/api/topup6",
|
||||
"/api/topup7",
|
||||
"/api/topup8",
|
||||
];
|
||||
]);
|
||||
|
||||
function getRoute(url) {
|
||||
return url.split('?', 1)[0];
|
||||
}
|
||||
|
||||
// Tandai respons yang dipantau dengan ID unik per request, termasuk ketika HSM gagal.
|
||||
function correlation(req, res, next) {
|
||||
if (routes.has(getRoute(req.originalUrl))) {
|
||||
req.id = randomUUID();
|
||||
res.setHeader('X-Request-Id', req.id);
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function getTransactionId(responseId, requestId) {
|
||||
// ID transaksi HSM terdiri dari empat digit hex. Abaikan nilai mentah lain dari body.
|
||||
for (const value of [responseId, requestId]) {
|
||||
if (typeof value === 'string' && /^[0-9a-f]{4}$/i.test(value)) return value.toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
|
||||
function getLoadBalanceNumber(responseNumber, requestNumber) {
|
||||
return [responseNumber, requestNumber].find((value) =>
|
||||
typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
const issuerCache = new Map();
|
||||
const issuerLookups = new Set();
|
||||
|
||||
// Enrichment tidak boleh menahan respons atau mengantrekan lookup per transaksi.
|
||||
function getIssuerName(partnerId) {
|
||||
if (!partnerId) return 'UNDEFINED';
|
||||
const cached = issuerCache.get(partnerId);
|
||||
if (cached?.expiresAt > Date.now()) return cached.name;
|
||||
if (issuerLookups.size < 4 && !issuerLookups.has(partnerId)) {
|
||||
issuerLookups.add(partnerId);
|
||||
void refreshIssuer(partnerId);
|
||||
}
|
||||
return cached?.name || 'UNDEFINED';
|
||||
}
|
||||
|
||||
async function refreshIssuer(partnerId) {
|
||||
let name = 'UNDEFINED';
|
||||
try {
|
||||
const partner = await knex('t_m_partner').where('i_partner', partnerId)
|
||||
.first('c_name').timeout(500, { cancel: true });
|
||||
name = partner?.c_name || name;
|
||||
} catch {
|
||||
// PostgreSQL sedang sibuk. Tetap catat audit dan coba lagi setelah jeda.
|
||||
} finally {
|
||||
issuerLookups.delete(partnerId);
|
||||
issuerCache.delete(partnerId);
|
||||
if (issuerCache.size >= 256) issuerCache.delete(issuerCache.keys().next().value);
|
||||
issuerCache.set(partnerId, { name, expiresAt: Date.now() + (name === 'UNDEFINED' ? 5000 : 300000) });
|
||||
}
|
||||
}
|
||||
|
||||
function recordResponse(event, partnerId, reservationNumber, message) {
|
||||
const issuerName = getIssuerName(partnerId);
|
||||
const level = successfulCodes.has(event.status_code) ? 'info' : 'error';
|
||||
responseAudit.record({
|
||||
level,
|
||||
message: typeof message === 'string' ? message : 'HTTP response',
|
||||
...event,
|
||||
issuer_name: issuerName,
|
||||
...(reservationNumber && { reservation_number: reservationNumber }),
|
||||
});
|
||||
|
||||
const labels = { route: event.route, status_code: event.status_code, issuer_name: issuerName };
|
||||
|
||||
topuponline_metrics.observe(labels, event.response_time_ms);
|
||||
topuponline_metrics_response_time.observe(labels, event.response_time_ms);
|
||||
if (isTopupRoute(event.route)) {
|
||||
topuponline_metrics_load_balance.observe(labels, event.response_time_ms);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = {
|
||||
correlation,
|
||||
response: expressWinston.logger({
|
||||
transports: [
|
||||
new winston.transports.DailyRotateFile({
|
||||
@@ -61,159 +131,56 @@ const logger = {
|
||||
],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf(async (info) => {
|
||||
let body = {};
|
||||
body.id = info.meta.req.id;
|
||||
body.tag = "RES";
|
||||
body.from = info.meta.req.ip;
|
||||
body.method = info.meta.req.method;
|
||||
body.endpoint = info.meta.req.originalUrl;
|
||||
body.time = moment().format();
|
||||
body.responseTime = `${info.meta.responseTime} ms`;
|
||||
winston.format.printf((info) => {
|
||||
const { req, res, responseTime } = info.meta;
|
||||
const route = getRoute(req.originalUrl);
|
||||
const data = res.body?.data;
|
||||
const applicationCode = String(res.body?.code ?? '');
|
||||
const event = {
|
||||
event: 'http_response',
|
||||
request_id: req.id,
|
||||
partner_id: /^\d{1,16}$/.test(req.partner_id_token) ? String(req.partner_id_token) : undefined,
|
||||
trx_id: isTopupRoute(route) ? getTransactionId(data?.trxID, req.body?.trxID) : null,
|
||||
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,
|
||||
};
|
||||
|
||||
let issuerName;
|
||||
|
||||
let partnerId = info.meta.req.partner_id_token;
|
||||
|
||||
if (!partnerId) {
|
||||
issuerName = "UNDEFINED";
|
||||
} else {
|
||||
let getIssuerName = await getPartner(info.meta.req.partner_id_token);
|
||||
if (!getIssuerName.c_name) {
|
||||
issuerName = "UNDEFINED";
|
||||
} else {
|
||||
issuerName = getIssuerName.c_name;
|
||||
}
|
||||
// Format Winston harus sinkron agar log file tetap berisi respons yang dapat dibaca.
|
||||
const reservationNumber = route.startsWith('/api/reservation') && successfulCodes.has(event.status_code)
|
||||
? data?.reservation_number
|
||||
: undefined;
|
||||
try {
|
||||
recordResponse(event, req.partner_id_token, reservationNumber, res.body?.message);
|
||||
} catch {
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'response_telemetry_error',
|
||||
level: 'error',
|
||||
message: 'Failed to record Online TopUp response telemetry',
|
||||
request_id: req.id,
|
||||
route,
|
||||
}));
|
||||
}
|
||||
|
||||
let statusCode = info.meta.res.body.code;
|
||||
let message = info.meta.res.body.message;
|
||||
let url = info.meta.req.originalUrl;
|
||||
|
||||
let date = moment().format("D");
|
||||
let month = moment().format("M");
|
||||
let year = moment().format("Y");
|
||||
|
||||
// Topup Metrics
|
||||
if (
|
||||
url == "/api/topup1" ||
|
||||
url == "/api/topup2" ||
|
||||
url == "/api/topup3" ||
|
||||
url == "/api/topup4" ||
|
||||
url == "/api/topup5" ||
|
||||
url == "/api/topup6" ||
|
||||
url == "/api/topup7" ||
|
||||
url == "/api/topup8"
|
||||
) {
|
||||
let trxId = info.meta.res.body.data.trxID;
|
||||
if (!trxId) {
|
||||
trxId = "UNDEFINED";
|
||||
}
|
||||
|
||||
topuponline_metrics_load_balance
|
||||
.labels({
|
||||
trxId: trxId,
|
||||
route: url,
|
||||
issuer_name: issuerName,
|
||||
date: date,
|
||||
month: month,
|
||||
year: year,
|
||||
})
|
||||
.observe(info.meta.responseTime);
|
||||
}
|
||||
|
||||
// Reservation Loki Logs
|
||||
if (url == "/api/reservation" || url == "/api/reservation/v2") {
|
||||
if (
|
||||
statusCode != "00" &&
|
||||
statusCode != "01" &&
|
||||
statusCode != "02" &&
|
||||
statusCode != "03" &&
|
||||
statusCode != "04"
|
||||
) {
|
||||
console.log(statusCode);
|
||||
winstonLoki.log.error({
|
||||
message: message,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
issuer_name: issuerName,
|
||||
});
|
||||
} else {
|
||||
let reservation_number = info.meta.res.body.data.reservation_number;
|
||||
let card_number = info.meta.res.body.data.card_number;
|
||||
winstonLoki.log.info({
|
||||
message: message,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
issuer_name: issuerName,
|
||||
reservation_number: reservation_number,
|
||||
card_number: card_number,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let trxID = info.meta.res.body.data.trxID;
|
||||
if (
|
||||
statusCode != "00" &&
|
||||
statusCode != "01" &&
|
||||
statusCode != "02" &&
|
||||
statusCode != "03" &&
|
||||
statusCode != "04"
|
||||
) {
|
||||
winstonLoki.log.error({
|
||||
message: message,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
issuer_name: issuerName,
|
||||
trxID: trxID,
|
||||
});
|
||||
} else {
|
||||
winstonLoki.log.info({
|
||||
message: message,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
issuer_name: issuerName,
|
||||
trxID: trxID,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
topuponline_metrics
|
||||
.labels({
|
||||
issuer_name: issuerName,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
date: date,
|
||||
month: month,
|
||||
year: year,
|
||||
})
|
||||
.observe(info.meta.responseTime);
|
||||
|
||||
topuponline_metrics_response_time
|
||||
.labels({
|
||||
issuer_name: issuerName,
|
||||
route: url,
|
||||
status_code: statusCode,
|
||||
date: date,
|
||||
month: month,
|
||||
year: year,
|
||||
response_time: info.meta.responseTime,
|
||||
})
|
||||
.observe(info.meta.responseTime);
|
||||
|
||||
return `[${moment().format()}] | ${JSON.stringify(body)}`;
|
||||
const body = {
|
||||
id: req.id,
|
||||
tag: "RES",
|
||||
from: req.ip,
|
||||
endpoint: route,
|
||||
time: moment().format(),
|
||||
responseTime: `${responseTime} ms`,
|
||||
...event,
|
||||
};
|
||||
return `[${body.time}] | ${JSON.stringify(body)}`;
|
||||
})
|
||||
),
|
||||
skip: (req, res) => {
|
||||
return routes.indexOf(req.originalUrl) === -1;
|
||||
},
|
||||
ignoreRoute: (req) => !routes.has(getRoute(req.originalUrl)),
|
||||
responseWhitelist: [...expressWinston.responseWhitelist, "body"],
|
||||
requestWhitelist: [
|
||||
...expressWinston.requestWhitelist,
|
||||
"body",
|
||||
"id",
|
||||
"ip",
|
||||
"partner_id_token",
|
||||
],
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip", "partner_id_token"],
|
||||
bodyWhitelist: ["trxID", "load_balance_number"],
|
||||
}),
|
||||
request: expressWinston.logger({
|
||||
transports: [
|
||||
@@ -237,14 +204,8 @@ const logger = {
|
||||
return `[${moment().format()}] | ${JSON.stringify(body)}`;
|
||||
})
|
||||
),
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip"],
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "id", "ip"],
|
||||
}),
|
||||
};
|
||||
|
||||
const getPartner = async (id) => {
|
||||
let result = await knex("t_m_partner").where("i_partner", "=", id).first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = { logger, filename };
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
const moment = require("moment");
|
||||
const winston = require("winston");
|
||||
const loki = require("winston-loki");
|
||||
require("winston-daily-rotate-file");
|
||||
require("dotenv").config();
|
||||
const { combine, timestamp, printf, colorize, align, json } = winston.format;
|
||||
let lokiUrl = process.env.LOKI_URL;
|
||||
|
||||
const logLevels = {
|
||||
fatal: 0,
|
||||
error: 1,
|
||||
warn: 2,
|
||||
info: 3,
|
||||
debug: 4,
|
||||
trace: 5,
|
||||
};
|
||||
var log;
|
||||
|
||||
const fileRotateTransport = new winston.transports.DailyRotateFile({
|
||||
filename: `./lokiLog/%DATE%-onlinetopup.log`,
|
||||
datePattern: "YYYY-MM-DD",
|
||||
maxFiles: "1d",
|
||||
});
|
||||
|
||||
if (
|
||||
process.env.NODE_ENV == "production" ||
|
||||
process.env.NODE_ENV == "PRODUCTION"
|
||||
) {
|
||||
log = winston.createLogger({
|
||||
levels: logLevels,
|
||||
level: process.env.LOG_LEVEL || "info",
|
||||
exitOnError: false,
|
||||
// format: combine(timestamp(), json()),
|
||||
format: combine(
|
||||
// colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
align(),
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`),
|
||||
),
|
||||
defaultMeta: { service: "topuponline" },
|
||||
transports: [
|
||||
new loki({
|
||||
host: lokiUrl,
|
||||
labels: { app: "topuponline" },
|
||||
json: true,
|
||||
format: json(),
|
||||
replaceTimestamp: true,
|
||||
onConnectionError: (err) => console.error(err),
|
||||
}),
|
||||
new winston.transports.Console({
|
||||
format: combine(colorize()),
|
||||
}),
|
||||
],
|
||||
});
|
||||
} else {
|
||||
log = winston.createLogger({
|
||||
transports: [
|
||||
new loki({
|
||||
host: lokiUrl,
|
||||
labels: { app: "topuponline" },
|
||||
handleExceptions: true,
|
||||
handleRejections: true,
|
||||
clearOnError: true,
|
||||
json: true,
|
||||
format: json(),
|
||||
replaceTimestamp: true,
|
||||
onConnectionError: (err) => console.log(`Loki error ${err}`),
|
||||
}),
|
||||
new winston.transports.Console({
|
||||
format: combine(colorize()),
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV != "testing" && process.env.NODE_ENV != "TESTING") {
|
||||
log.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}`),
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
log,
|
||||
};
|
||||
@@ -1,37 +1,27 @@
|
||||
const client = require("prom-client");
|
||||
|
||||
const responseBucketsMs = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 15000, 30000, 60000];
|
||||
const responseLabels = ["route", "status_code", "issuer_name"];
|
||||
|
||||
const topuponline_metrics = new client.Histogram({
|
||||
name: "topuponline",
|
||||
help: "this is the metric for getting request data based on code status",
|
||||
labelNames: ["route", "status_code", "issuer_name", "date", "month", "year"],
|
||||
help: "Durasi request Online TopUp dalam milidetik berdasarkan kode aplikasi",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
const topuponline_metrics_response_time = new client.Histogram({
|
||||
name: "topuponline_response_time",
|
||||
help: "this is the metric for getting request data based on response time",
|
||||
labelNames: [
|
||||
"route",
|
||||
"status_code",
|
||||
"issuer_name",
|
||||
"date",
|
||||
"month",
|
||||
"year",
|
||||
"response_time",
|
||||
],
|
||||
help: "Durasi respons Online TopUp dalam milidetik",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
const topuponline_metrics_load_balance = new client.Histogram({
|
||||
name: "topuponline_load_balance",
|
||||
help: "this is the metric for getting request data based on response time",
|
||||
labelNames: [
|
||||
"route",
|
||||
"status_code",
|
||||
"issuer_name",
|
||||
"date",
|
||||
"month",
|
||||
"year",
|
||||
"trxId",
|
||||
],
|
||||
help: "Durasi respons tahap TopUp dalam milidetik",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Perintah yang sudah terkirim baru dilepas oleh node-redis saat socket ditutup.
|
||||
function createRedisOperations(client, { timeoutMs = 500, onTimeout = () => {} } = {}) {
|
||||
let reconnecting = false;
|
||||
|
||||
function resetConnection() {
|
||||
if (reconnecting) return;
|
||||
reconnecting = true;
|
||||
if (client.isOpen) {
|
||||
client.disconnect().catch(() => {}).then(reconnect);
|
||||
} else {
|
||||
reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function reconnect() {
|
||||
// Setelah socket lama dilepas, isReady milik klien menentukan kapan socket baru dapat dipakai.
|
||||
reconnecting = false;
|
||||
if (!client.isOpen) void client.connect().catch(() => {});
|
||||
}
|
||||
|
||||
async function execute(command) {
|
||||
if (!client.isReady || reconnecting) return null;
|
||||
let timer;
|
||||
try {
|
||||
return await Promise.race([
|
||||
command(client),
|
||||
new Promise((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
onTimeout();
|
||||
resetConnection();
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
return execute;
|
||||
}
|
||||
|
||||
module.exports = createRedisOperations;
|
||||
@@ -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] };
|
||||
@@ -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] };
|
||||
@@ -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];
|
||||
|
||||
|
||||
@@ -1,233 +1,77 @@
|
||||
require('dotenv').config();
|
||||
const redis = require('redis');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
|
||||
let redisClient;
|
||||
(async () => {
|
||||
let redisUrl = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
|
||||
let redisPass = process.env.REDIS_PASSWORD || '';
|
||||
const redisClient = redis.createClient({
|
||||
url: process.env.REDIS_URL || 'redis://127.0.0.1:6379',
|
||||
disableOfflineQueue: true,
|
||||
commandsQueueMaxLength: 256,
|
||||
});
|
||||
|
||||
redisClient = redis.createClient({
|
||||
url: redisUrl,
|
||||
password: '',
|
||||
redisClient.on('error', () => {});
|
||||
redisClient.on('ready', () => logger.info('Redis connection ready'));
|
||||
void redisClient.connect().catch(() => logger.error('Redis connection failed'));
|
||||
|
||||
const execute = createRedisOperations(redisClient, {
|
||||
onTimeout: () => logger.warn('Redis command deadline exceeded; database sequence fallback is active'),
|
||||
});
|
||||
|
||||
async function redisMiddleware(req, res, next) {
|
||||
const value = await execute((client) => client.get('cardproduct'));
|
||||
if (value) {
|
||||
try {
|
||||
res.status(200).json({ code: 200, message: 'Success get from redis', data: JSON.parse(value) });
|
||||
return;
|
||||
} catch {
|
||||
// Payload cache yang rusak dapat dibaca ulang dari sumbernya.
|
||||
}
|
||||
}
|
||||
res.once('finish', () => {
|
||||
if (res.body !== undefined) void execute((client) => client.set('cardproduct', JSON.stringify(res.body), { EX: 10 }));
|
||||
});
|
||||
|
||||
redisClient.on('error', (error) =>
|
||||
// process.env.NODE_ENV.toUpperCase() != 'PRODUCTION'
|
||||
// ? console.error(`Error : ${error}`)
|
||||
// : ''
|
||||
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION' ? '' : ''
|
||||
);
|
||||
|
||||
redisClient.on('connect', () => console.log('Redis is Connected'));
|
||||
|
||||
redisClient.on('ready', () => console.log('Redis is Ready'));
|
||||
|
||||
redisClient.on('reconnecting', () =>
|
||||
// process.env.NODE_ENV.toUpperCase() != 'PRODUCTION'
|
||||
// ? console.log('Redis is Reconnecting')
|
||||
// : ''
|
||||
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION' ? '' : ''
|
||||
);
|
||||
|
||||
await redisClient.connect();
|
||||
})();
|
||||
|
||||
const redisMiddleware = async (req, res, next) => {
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
if (!isRedisReady) {
|
||||
next();
|
||||
} else {
|
||||
let getValue = await redisClient.get('cardproduct');
|
||||
let parsedValue = JSON.parse(getValue);
|
||||
|
||||
if (getValue) {
|
||||
res.status(200).json({
|
||||
code: 200,
|
||||
message: 'Success get from redis',
|
||||
data: parsedValue,
|
||||
});
|
||||
} else {
|
||||
res.on('finish', async () => {
|
||||
await redisClient.set('cardproduct', JSON.stringify(res.body), {
|
||||
EX: 10,
|
||||
NX: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
};
|
||||
|
||||
const getReservationNumberSequence = async (req, res, next) => {
|
||||
// set default reservation_number_sequence dari partner apapun is null
|
||||
req.reservation_number_sequence = null;
|
||||
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
// data req.partner_id_token di dapat dari authenticateToken di jwt middleware
|
||||
let getValue = await redisClient.GET(
|
||||
'reservation_number_sequence_' + req.partner_id_token
|
||||
);
|
||||
|
||||
if (getValue) {
|
||||
// parsing data menjadi json format
|
||||
let parsedValue = JSON.parse(getValue);
|
||||
|
||||
// cek apakah tanggal sequence yang di redis sama dengan hari ini atau bukan
|
||||
if (parsedValue.date == moment().format('YYYY-MM-DD')) {
|
||||
// jika tanggal nya sama dengan hari ini maka ambil sequence untuk reservation number yang di generate dari redis
|
||||
req.reservation_number_sequence = parseInt(parsedValue.sequence);
|
||||
|
||||
// langsung update sequence walaupun transaksi insert nya belum selesai
|
||||
// impact menggunakan redis, untuk nomor sequence bisa saja ada yg loncat karena bisa saja ada transaksi insert reservation yang gagal
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(parsedValue.sequence) + 1,
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`reservation_number_sequence_${req.partner_id_token}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
const setReservationNumberSequence = async (partner_id, sequence) => {
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
// Redis hanya memberi perkiraan nomor. Klaim unik di PostgreSQL memutuskan nomor yang dapat dipakai.
|
||||
async function getSequence(prefix, partnerId) {
|
||||
const key = prefix + partnerId;
|
||||
const value = await execute((client) => client.get(key));
|
||||
if (!value) return null;
|
||||
const today = moment().format('YYYY-MM-DD');
|
||||
let cached;
|
||||
try { cached = JSON.parse(value); } catch { return null; }
|
||||
const sequence = Number(cached?.sequence);
|
||||
if (cached?.date !== today || !Number.isSafeInteger(sequence) || sequence <= 0) return null;
|
||||
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(sequence),
|
||||
};
|
||||
const updated = await execute((client) => client.set(key, JSON.stringify({ date: today, sequence: sequence + 1 })));
|
||||
return updated === 'OK' ? sequence : null;
|
||||
}
|
||||
|
||||
await redisClient.SET(
|
||||
`reservation_number_sequence_${partner_id}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
};
|
||||
function setSequence(prefix, partnerId, sequence) {
|
||||
const value = { date: moment().format('YYYY-MM-DD'), sequence: Number(sequence) };
|
||||
return execute((client) => client.set(prefix + partnerId, JSON.stringify(value)));
|
||||
}
|
||||
|
||||
const getLoadBalanceNumberSequence = async (req, res, next) => {
|
||||
// set default load_balance_number_sequence dari partner apapun is null
|
||||
req.load_balance_number_sequence = null;
|
||||
const reservationPrefix = 'reservation_number_sequence_';
|
||||
const loadBalancePrefix = 'load_balance_number_sequence_';
|
||||
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
// data req.partner_id_token di dapat dari authenticateToken di jwt middleware
|
||||
let getValue = await redisClient.GET(
|
||||
'load_balance_number_sequence_' + req.partner_id_token
|
||||
);
|
||||
|
||||
if (getValue) {
|
||||
// parsing data menjadi json format
|
||||
let parsedValue = JSON.parse(getValue);
|
||||
|
||||
// cek apakah tanggal sequence yang di redis sama dengan hari ini atau bukan
|
||||
if (parsedValue.date == moment().format('YYYY-MM-DD')) {
|
||||
// jika tanggal nya sama dengan hari ini maka ambil sequence untuk reservation number yang di generate dari redis
|
||||
req.load_balance_number_sequence = parseInt(parsedValue.sequence);
|
||||
|
||||
// langsung update sequence walaupun transaksi insert nya belum selesai
|
||||
// impact menggunakan redis, untuk nomor sequence bisa saja ada yg loncat karena bisa saja ada transaksi insert reservation yang gagal
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(parsedValue.sequence) + 1,
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`load_balance_number_sequence_${req.partner_id_token}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function getReservationNumberSequence(req, res, next) {
|
||||
req.reservation_number_sequence = await getSequence(reservationPrefix, req.partner_id_token);
|
||||
next();
|
||||
};
|
||||
const getLoadBalanceNumberSequence2 = async (req) => {
|
||||
// set default load_balance_number_sequence dari partner apapun is null
|
||||
let load_balance_number_sequence = null;
|
||||
}
|
||||
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
// data req.partner_id_token di dapat dari authenticateToken di jwt middleware
|
||||
let getValue = await redisClient.GET(
|
||||
'load_balance_number_sequence_' + req.partner_id_token
|
||||
);
|
||||
async function getLoadBalanceNumberSequence(req, res, next) {
|
||||
req.load_balance_number_sequence = await getLoadBalanceNumberSequence2(req);
|
||||
next();
|
||||
}
|
||||
|
||||
if (getValue) {
|
||||
// parsing data menjadi json format
|
||||
let parsedValue = JSON.parse(getValue);
|
||||
|
||||
// cek apakah tanggal sequence yang di redis sama dengan hari ini atau bukan
|
||||
if (parsedValue.date == moment().format('YYYY-MM-DD')) {
|
||||
// jika tanggal nya sama dengan hari ini maka ambil sequence untuk reservation number yang di generate dari redis
|
||||
load_balance_number_sequence = parseInt(parsedValue.sequence);
|
||||
|
||||
// langsung update sequence walaupun transaksi insert nya belum selesai
|
||||
// impact menggunakan redis, untuk nomor sequence bisa saja ada yg loncat karena bisa saja ada transaksi insert reservation yang gagal
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(parsedValue.sequence) + 1,
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`load_balance_number_sequence_${req.partner_id_token}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return load_balance_number_sequence;
|
||||
// next();
|
||||
};
|
||||
|
||||
const setLoadBalanceNumberSequence = async (partner_id, sequence) => {
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(sequence),
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`load_balance_number_sequence_${partner_id}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
};
|
||||
const getLoadBalanceNumberSequence2 = (req) => getSequence(loadBalancePrefix, req.partner_id_token);
|
||||
const setReservationNumberSequence = (id, value) => setSequence(reservationPrefix, id, value);
|
||||
const setLoadBalanceNumberSequence = (id, value) => setSequence(loadBalancePrefix, id, value);
|
||||
|
||||
module.exports = {
|
||||
redisMiddleware,
|
||||
getReservationNumberSequence,
|
||||
setReservationNumberSequence,
|
||||
getLoadBalanceNumberSequence,
|
||||
setLoadBalanceNumberSequence,
|
||||
getLoadBalanceNumberSequence2,
|
||||
redisMiddleware, getReservationNumberSequence, setReservationNumberSequence,
|
||||
getLoadBalanceNumberSequence, setLoadBalanceNumberSequence, getLoadBalanceNumberSequence2,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1590,142 +1573,33 @@ const loadingBalanceInsert = async (req, param) => {
|
||||
// maxLoop++;
|
||||
// } while (loadBalanceNumber == 'XX');
|
||||
|
||||
//================== Start nested if condition ====================
|
||||
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
|
||||
console.log('DEBUGING loadBalanceNoSequence START', loadBalanceNoSequence);
|
||||
|
||||
if (!loadBalanceNoSequence) {
|
||||
getLoadBalanceSequence = await model.getLoadBalanceSequence(
|
||||
getPartner,
|
||||
today
|
||||
);
|
||||
loadBalanceNoSequence = getLoadBalanceSequence
|
||||
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
|
||||
: 1;
|
||||
await setLoadBalanceNumberSequence(
|
||||
req.partner_id_token,
|
||||
loadBalanceNoSequence + 1
|
||||
);
|
||||
console.log(
|
||||
'Masuk kondisi !loadBalanceNoSequence',
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
const latest = await model.getLoadBalanceSequence(getPartner, today);
|
||||
loadBalanceNoSequence = (Number(latest?.i_load_balance_no_seq) || 0) + 1;
|
||||
await setLoadBalanceNumberSequence(req.partner_id_token, loadBalanceNoSequence + 1);
|
||||
}
|
||||
|
||||
// Percobaan 1
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
moment(today).format('YYMMDD'),
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 1 ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
console.log('DEBUGING loadBalanceNumber PERCOBAAN 1', loadBalanceNumber);
|
||||
|
||||
if (loadBalanceNumber == 'DUPLICATE') {
|
||||
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNoSequence PERCOBAAN 2',
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// Percobaan 2
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
moment(today).format('YYMMDD'),
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 2 ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
console.log('DEBUGING loadBalanceNumber PERCOBAAN 2', loadBalanceNumber);
|
||||
if (loadBalanceNumber == 'DUPLICATE') {
|
||||
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNoSequence PERCOBAAN 3',
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// Percobaan 3
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
moment(today).format('YYMMDD'),
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 3 ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNumber PERCOBAAN 3',
|
||||
loadBalanceNumber
|
||||
);
|
||||
if (loadBalanceNumber == 'DUPLICATE') {
|
||||
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNoSequence PERCOBAAN 4',
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// Percobaan 4
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
moment(today).format('YYMMDD'),
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 4 ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNumber PERCOBAAN 4',
|
||||
loadBalanceNumber
|
||||
);
|
||||
if (loadBalanceNumber == 'DUPLICATE') {
|
||||
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNoSequence PERCOBAAN 5',
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// Percobaan 5
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
moment(today).format('YYMMDD'),
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 5 ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
console.log(
|
||||
'DEBUGING loadBalanceNumber PERCOBAAN 5',
|
||||
loadBalanceNumber
|
||||
);
|
||||
if (loadBalanceNumber == 'DUPLICATE') {
|
||||
// log warn
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number sequence is ${loadBalanceNoSequence}.`
|
||||
);
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 505 internal server error. Server is busy. please try again`
|
||||
);
|
||||
|
||||
return {
|
||||
code: '505',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? '505 internal server error (max loop) - backend server.'
|
||||
: '505 Server is busy. please try again.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const numberDate = moment(today).format('YYMMDD');
|
||||
// Klaim unik PostgreSQL tetap dipakai ketika Redis tidak dapat memberi nomor.
|
||||
for (let attempt = 1; attempt <= 5; attempt++) {
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(getPartner, numberDate, loadBalanceNoSequence);
|
||||
if (loadBalanceNumber !== 'DUPLICATE' || attempt === 5) break;
|
||||
const cached = await getLoadBalanceNumberSequence2(req);
|
||||
loadBalanceNoSequence = Math.max(loadBalanceNoSequence + 1, cached || 0);
|
||||
}
|
||||
|
||||
if (loadBalanceNumber === 'DUPLICATE') {
|
||||
winston.logger.error(`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 505 Server is busy. please try again.`);
|
||||
return {
|
||||
code: '505',
|
||||
message: process.env.NODE_ENV !== 'production'
|
||||
? '505 internal server error (max loop) - backend server.'
|
||||
: '505 Server is busy. please try again.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
//================== End nested if condition ====================
|
||||
let data = {
|
||||
c_load_balance_no: loadBalanceNumber,
|
||||
d_load_balance: now,
|
||||
@@ -1769,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 = {
|
||||
@@ -1869,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,
|
||||
|
||||
@@ -1,442 +1,52 @@
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
const model = require("../pooling/pooling.model");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./pooling.model");
|
||||
const { logger } = require("../../helpers/winston.logger");
|
||||
|
||||
const pooling = async (req, res) => {
|
||||
function respond(res, code, message, data = []) {
|
||||
return res.status(200).json({ code, message, data });
|
||||
}
|
||||
|
||||
function failure(res, error) {
|
||||
logger.error("Pooling failed | " + (error.code || error.name));
|
||||
if (error.code === "POOLING_CARD_CONFLICT") return respond(res, "409", "Fail insert data card product");
|
||||
return respond(res, "500", process.env.NODE_ENV === "production"
|
||||
? "500 internal server error - backend server." : error.message);
|
||||
}
|
||||
|
||||
async function runBatches(res, operation, name, empty, complete) {
|
||||
let count = 0;
|
||||
try {
|
||||
let { batch } = req.body;
|
||||
// return console.log(batch);
|
||||
let dataInsert = [];
|
||||
if (batch) {
|
||||
let { data } = req.body;
|
||||
|
||||
if (!data) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Data is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let resObj = {
|
||||
c_card_number: data[i].card_number,
|
||||
c_idm: data[i].uid,
|
||||
};
|
||||
dataInsert.push(resObj);
|
||||
}
|
||||
|
||||
await model.insertDataPooling("raw", dataInsert);
|
||||
} else {
|
||||
let { card_number, uid } = req.body;
|
||||
|
||||
if (!card_number) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Card Number is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (!uid) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "uid is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let obj = {
|
||||
c_card_number: card_number,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
await model.insertDataPooling("raw", obj);
|
||||
for (;;) {
|
||||
const batch = await operation();
|
||||
if (batch.busy) return respond(res, "409", "Pooling is being processed. Please retry.");
|
||||
if (!batch.count) return respond(res, ...(count ? complete : empty));
|
||||
count += batch.count;
|
||||
logger.info("Pooling " + name + " batch committed | count=" + batch.count);
|
||||
}
|
||||
|
||||
let dataPooling = await model.getDataPooling();
|
||||
|
||||
if (dataPooling.length == 0) {
|
||||
return res.status(200).json({
|
||||
code: "00",
|
||||
message: "No Pooling Data",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let valid = [];
|
||||
let invalid = [];
|
||||
let validCardNo = [];
|
||||
let invalidCardNo = [];
|
||||
|
||||
// Validate data
|
||||
for (let i = 0; i < dataPooling.length; i++) {
|
||||
let cardno = dataPooling[i].c_card_number;
|
||||
let uid = dataPooling[i].c_idm;
|
||||
// Check duplikat card number
|
||||
let checkCardNo = await model.checkCardProduct(cardno, uid);
|
||||
let dataObject = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
if (!checkCardNo) {
|
||||
valid.push(dataObject);
|
||||
validCardNo.push(cardno);
|
||||
} else {
|
||||
invalid.push(dataObject);
|
||||
invalidCardNo.push(cardno);
|
||||
}
|
||||
}
|
||||
|
||||
if (valid.length > 0) {
|
||||
await model.insertDataPooling("valid", valid, validCardNo);
|
||||
}
|
||||
|
||||
if (invalid.length > 0) {
|
||||
await model.insertDataPooling("invalid", invalid, invalidCardNo);
|
||||
}
|
||||
|
||||
let dataInsertCardNumber = await model.getDataValid();
|
||||
|
||||
if (dataInsertCardNumber.length == 0) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "No data valid",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let insertCardProduct = [];
|
||||
let cardNumber = [];
|
||||
for (let i = 0; i < dataInsertCardNumber.length; i++) {
|
||||
let cardno = dataInsertCardNumber[i].c_card_number;
|
||||
let uid = dataInsertCardNumber[i].c_idm;
|
||||
let obj = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
cardNumber.push(cardno);
|
||||
insertCardProduct.push(obj);
|
||||
}
|
||||
|
||||
let insertingCardNumber = await model.insertCardNumber(insertCardProduct);
|
||||
if (insertingCardNumber == "success") {
|
||||
let flagValid = await model.updateDataValid(dataCardNumber);
|
||||
if (flagValid == "error") {
|
||||
await model.deleteCardNumber(dataCardNumber);
|
||||
}
|
||||
}
|
||||
console.log(insertingCardNumber);
|
||||
if (insertingCardNumber == "error") {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Fail insert data card product",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
code: "00",
|
||||
message: "Success",
|
||||
data: [],
|
||||
});
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
});
|
||||
return failure(res, error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const validateData = (req, res) => runBatches(res, model.validateBatch, "validate",
|
||||
["00", "No Pooling Data"], ["00", "Validate success"]);
|
||||
|
||||
const insertCardProduct = (req, res) => runBatches(res, model.syncBatch, "sync",
|
||||
["409", "No data valid"], ["00", "Success"]);
|
||||
|
||||
async function insertPooling(req, res) {
|
||||
const { batch, data, card_number, uid } = req.body || {};
|
||||
const cards = batch ? data : [{ card_number, uid }];
|
||||
if (!Array.isArray(cards) || cards.length === 0) return respond(res, "409", "Data is required");
|
||||
if (cards.some((card) => !card?.card_number)) return respond(res, "409", "Card Number is required");
|
||||
if (cards.some((card) => !card?.uid)) return respond(res, "409", "uid is required");
|
||||
|
||||
const validateData = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let data = await model.getDataPooling();
|
||||
|
||||
if (data.length == 0) {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "No Pooling Data",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let valid = [];
|
||||
let invalid = [];
|
||||
let validCardNo = [];
|
||||
let invalidCardNo = [];
|
||||
|
||||
winston.logger.debug(
|
||||
`[ PROCESSING VALIDATE-POOLING ]: checking and separating valid and invalid data...`
|
||||
);
|
||||
|
||||
// Validate data
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let cardno = data[i].c_card_number;
|
||||
let uid = data[i].c_idm;
|
||||
// Check duplikat card number
|
||||
let checkCardNo = await model.checkCardProduct(cardno, uid);
|
||||
let dataObject = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
if (!checkCardNo) {
|
||||
valid.push(dataObject);
|
||||
validCardNo.push(cardno);
|
||||
} else {
|
||||
invalid.push(dataObject);
|
||||
invalidCardNo.push(cardno);
|
||||
}
|
||||
}
|
||||
|
||||
winston.logger.debug(`[ PROCESSING VALIDATE-POOLING ]: inserting data...`);
|
||||
|
||||
if (valid.length > 0) {
|
||||
await model.insertDataPooling("valid", valid, validCardNo);
|
||||
}
|
||||
|
||||
if (invalid.length > 0) {
|
||||
await model.insertDataPooling("invalid", invalid, invalidCardNo);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Validate success",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
await model.insertRawCards(cards);
|
||||
logger.info("Pooling raw batch committed | count=" + cards.length);
|
||||
return respond(res, "00", "Success insert data");
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
return failure(res, error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const insertCardProduct = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let data = await model.getDataValid();
|
||||
|
||||
if (data.length == 0) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "No data valid",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let dataInsert = [];
|
||||
let dataCardNumber = [];
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let cardno = data[i].c_card_number;
|
||||
let uid = data[i].c_idm;
|
||||
let obj = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
dataCardNumber.push(cardno);
|
||||
dataInsert.push(obj);
|
||||
}
|
||||
|
||||
winston.logger.debug(
|
||||
`[ PROCESSING INSERT-CARD-PRODUCT ]: inserting data...`
|
||||
);
|
||||
|
||||
let insertCardNumber = await model.insertCardNumber(dataInsert);
|
||||
if (insertCardNumber == "success") {
|
||||
let flagValid = await model.updateDataValid(dataCardNumber);
|
||||
if (flagValid == "error") {
|
||||
await model.deleteCardNumber(dataCardNumber);
|
||||
}
|
||||
}
|
||||
|
||||
if (insertCardNumber == "error") {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Fail insert data card product",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Success",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
const insertPooling = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let { batch } = req.body;
|
||||
|
||||
let dataInsert = [];
|
||||
if (batch) {
|
||||
let { data } = req.body;
|
||||
|
||||
winston.logger.warn(
|
||||
`[ REQUEST INSERT-POOLING ]: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Data is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let resObj = {
|
||||
c_card_number: data[i].card_number,
|
||||
c_idm: data[i].uid,
|
||||
};
|
||||
dataInsert.push(resObj);
|
||||
}
|
||||
|
||||
winston.logger.debug(`[ PROCESSING INSERT-POOLING ]: inserting data...`);
|
||||
|
||||
await model.insertDataPooling("raw", dataInsert);
|
||||
} else {
|
||||
let { card_number, uid } = req.body;
|
||||
|
||||
winston.logger.warn(
|
||||
`[ REQUEST INSERT-POOLING ]: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
if (!card_number) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Card Number is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (!uid) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "uid is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let obj = {
|
||||
c_card_number: card_number,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
winston.logger.debug(`[ PROCESSING INSERT-POOLING ]: inserting data...`);
|
||||
|
||||
await model.insertDataPooling("raw", obj);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Success insert data",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { pooling, validateData, insertCardProduct, insertPooling };
|
||||
module.exports = { validateData, insertCardProduct, insertPooling };
|
||||
|
||||
@@ -2,142 +2,81 @@ const { pooling: poolingConfig } = require("../../../knexfile");
|
||||
const dbPooling = require("knex")(poolingConfig);
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
|
||||
const insertData = (table, data) => {
|
||||
let result = knex(table).insert(data);
|
||||
return result;
|
||||
};
|
||||
const BATCH_SIZE = 500;
|
||||
const validateLock = 3824001;
|
||||
const syncLock = 3824002;
|
||||
|
||||
const insertDataPooling = async (table, data, cardno) => {
|
||||
if (table == "raw") {
|
||||
await dbPooling(table).insert(data);
|
||||
} else if (table == "valid") {
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx(table).insert(data);
|
||||
await trx("raw")
|
||||
.whereIn("c_card_number", cardno)
|
||||
.update({
|
||||
b_validate: true,
|
||||
d_validate: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
} else if (table == "invalid") {
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx(table).insert(data);
|
||||
await trx("raw")
|
||||
.whereIn("c_card_number", cardno)
|
||||
.update({
|
||||
b_validate: true,
|
||||
d_validate: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await dbPooling(table).insert(data);
|
||||
}
|
||||
};
|
||||
const cardColumns = ["c_card_number", "c_idm"];
|
||||
const cardKey = (row) => JSON.stringify(cardColumns.map((column) => row[column]));
|
||||
|
||||
const checkCardProduct = (card_number, uid) => {
|
||||
let result = knex("t_m_card_product")
|
||||
.where("c_card_number", "=", card_number)
|
||||
.where("c_idm", "=", uid)
|
||||
.first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const pooling = async (valid, invalid, dataDelete) => {
|
||||
let sts;
|
||||
await dbPooling.transaction(async (trx2) => {
|
||||
try {
|
||||
if (valid.length > 0) {
|
||||
await trx2("valid").insert(valid);
|
||||
}
|
||||
if (invalid.length > 0) {
|
||||
await trx2("invalid").insert(invalid);
|
||||
}
|
||||
await trx2("pooling").whereIn("c_card_number", dataDelete).del();
|
||||
|
||||
await trx2.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
sts = "error";
|
||||
await trx2.rollback();
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
|
||||
const insertCardNumber = async (data) => {
|
||||
let sts;
|
||||
await knex.transaction(async (trx) => {
|
||||
try {
|
||||
await trx("t_m_card_product").insert(data);
|
||||
await trx.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
sts = "error";
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
|
||||
const updateDataValid = async (data) => {
|
||||
let sts;
|
||||
async function insertRawCards(cards) {
|
||||
// Satu request insert tetap atomik meski SQL dikirim dalam potongan kecil.
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx("valid")
|
||||
.whereIn("c_card_number", data)
|
||||
.update({
|
||||
b_sync: true,
|
||||
d_sync: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
sts = "error";
|
||||
for (let start = 0; start < cards.length; start += BATCH_SIZE) {
|
||||
const rows = cards.slice(start, start + BATCH_SIZE).map((card) => ({
|
||||
c_card_number: card.card_number, c_idm: card.uid,
|
||||
}));
|
||||
await trx("raw").insert(rows);
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
}
|
||||
|
||||
const getDataPooling = () => {
|
||||
let result = dbPooling("raw").where("b_validate", "=", false);
|
||||
return result;
|
||||
};
|
||||
async function existingKeys(trx, table, cards) {
|
||||
const tuples = [];
|
||||
const nullable = [];
|
||||
for (const card of cards) {
|
||||
const tuple = cardColumns.map((column) => card[column]);
|
||||
if (tuple.includes(null)) nullable.push(card);
|
||||
else tuples.push(tuple);
|
||||
}
|
||||
const query = trx(table).select(cardColumns).whereIn(cardColumns, tuples);
|
||||
for (const card of nullable) query.orWhere(card);
|
||||
const existing = await query;
|
||||
return new Set(existing.map(cardKey));
|
||||
}
|
||||
|
||||
const getDataValid = () => {
|
||||
let result = dbPooling("valid").where("b_sync", "=", false);
|
||||
return result;
|
||||
};
|
||||
async function ensureCards(trx, table, cards) {
|
||||
if (!cards.length) return;
|
||||
const unique = [...new Map(cards.map((card) => [cardKey(card), card])).values()];
|
||||
const existing = await existingKeys(trx, table, unique);
|
||||
const missing = unique.filter((card) => !existing.has(cardKey(card)));
|
||||
if (!missing.length) return;
|
||||
await trx(table).insert(missing).onConflict().ignore();
|
||||
const stored = await existingKeys(trx, table, missing);
|
||||
if (stored.size !== missing.length) {
|
||||
const error = new Error("Card conflict in pooling destination");
|
||||
error.code = "POOLING_CARD_CONFLICT";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCardNumber = (data) => {
|
||||
let result = knex("t_m_card_product")
|
||||
.whereIn("c_card_number", "=", data)
|
||||
.del();
|
||||
return result;
|
||||
};
|
||||
function processBatch(table, pendingColumn, lock, apply) {
|
||||
return dbPooling.transaction(async (trx) => {
|
||||
const { rows: [{ acquired }] } = await trx.raw("SELECT pg_try_advisory_xact_lock(?::bigint) AS acquired", [lock]);
|
||||
if (!acquired) return { busy: true, count: 0 };
|
||||
// CTID hanya dipakai selama baris terkunci pada transaksi ini.
|
||||
const rows = await trx(table).select(...cardColumns, trx.raw("ctid::text AS row_id"))
|
||||
.where(pendingColumn, false).limit(BATCH_SIZE).forUpdate().skipLocked();
|
||||
if (!rows.length) return { busy: false, count: 0 };
|
||||
const cards = rows.map(({ c_card_number, c_idm }) => ({ c_card_number, c_idm }));
|
||||
await apply(trx, cards);
|
||||
const timestampColumn = pendingColumn === "b_validate" ? "d_validate" : "d_sync";
|
||||
await trx(table).whereIn(trx.raw("ctid::text"), rows.map(({ row_id }) => row_id))
|
||||
.update({ [pendingColumn]: true, [timestampColumn]: moment().format("YYYY-MM-DD HH:mm:ss") });
|
||||
return { busy: false, count: rows.length };
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
deleteCardNumber,
|
||||
updateDataValid,
|
||||
getDataValid,
|
||||
insertDataPooling,
|
||||
insertCardNumber,
|
||||
pooling,
|
||||
insertData,
|
||||
checkCardProduct,
|
||||
getDataPooling,
|
||||
};
|
||||
const validateBatch = () => processBatch("raw", "b_validate", validateLock, async (trx, cards) => {
|
||||
const existing = await existingKeys(knex, "t_m_card_product", cards);
|
||||
await ensureCards(trx, "valid", cards.filter((card) => !existing.has(cardKey(card))));
|
||||
await ensureCards(trx, "invalid", cards.filter((card) => existing.has(cardKey(card))));
|
||||
});
|
||||
|
||||
const syncBatch = () => processBatch("valid", "b_sync", syncLock, async (trx, cards) => {
|
||||
// Jika commit utama berhasil tetapi penandaan gagal, retry mengenali pasangan yang sudah ada.
|
||||
await knex.transaction((main) => ensureCards(main, "t_m_card_product", cards));
|
||||
});
|
||||
|
||||
module.exports = { insertRawCards, validateBatch, syncBatch };
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
const { default: axios } = require('axios');
|
||||
|
||||
// Kegagalan CTS harus selesai pada jalur error yang sudah dimiliki endpoint.
|
||||
function postWithDeadline(url, data, config) {
|
||||
const timeout = 5000;
|
||||
return axios.post(url, data, { ...config, timeout, signal: AbortSignal.timeout(timeout) });
|
||||
}
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
@@ -312,6 +318,7 @@ const validateBlacklist = async (card_number, uniqueCode) => {
|
||||
|
||||
//CHECK LAST BALANCE CTR
|
||||
const checkLastBalanceCTS = async (card_number, uniqueCode, req) => {
|
||||
let token_api;
|
||||
let result = {};
|
||||
|
||||
//LOG-INFO
|
||||
@@ -350,7 +357,7 @@ const checkLastBalanceCTS = async (card_number, uniqueCode, req) => {
|
||||
};
|
||||
const dataPost = { card_number: card_number };
|
||||
const url = current_url + `/api/pos/card-lastbalance`;
|
||||
const resp = await axios.post(url, dataPost, config);
|
||||
const resp = await postWithDeadline(url, dataPost, config);
|
||||
|
||||
if (
|
||||
resp.data.data == undefined ||
|
||||
@@ -673,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);
|
||||
@@ -860,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);
|
||||
@@ -904,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',
|
||||
@@ -987,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}`
|
||||
@@ -1013,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);
|
||||
@@ -1080,6 +1079,7 @@ const checkBlacklist = async (req, res) => {
|
||||
};
|
||||
|
||||
const validateRedeem = async (req, res) => {
|
||||
let dataCard;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
@@ -1087,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);
|
||||
@@ -1323,7 +1321,7 @@ const validateRedeem = async (req, res) => {
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await axios.post(url, payload, config);
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
@@ -1397,6 +1395,7 @@ const validateRedeem = async (req, res) => {
|
||||
};
|
||||
|
||||
const validateReplacement = async (req, res) => {
|
||||
let dataCard;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
@@ -1405,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);
|
||||
@@ -1702,7 +1697,7 @@ const validateReplacement = async (req, res) => {
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await axios.post(url, payload, config);
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
@@ -1820,16 +1815,13 @@ const validateReplacement = async (req, res) => {
|
||||
};
|
||||
|
||||
const validateNewCardReplacement = async (req, res) => {
|
||||
let dataCardNew;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
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);
|
||||
@@ -2000,6 +1992,7 @@ const validateNewCardReplacement = async (req, res) => {
|
||||
};
|
||||
|
||||
const replacementConfirm = async (req, res) => {
|
||||
let dataCardNew;
|
||||
try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
@@ -2013,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);
|
||||
@@ -2368,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);
|
||||
@@ -2597,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);
|
||||
@@ -2703,17 +2688,14 @@ const confirmSales = async (req, res) => {
|
||||
};
|
||||
|
||||
const getLastBalanceCTS = async (req, res) => {
|
||||
let last_balance;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
// 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();
|
||||
@@ -2729,7 +2711,7 @@ const getLastBalanceCTS = async (req, res) => {
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await axios.post(url, payload, config);
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
@@ -2916,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();
|
||||
@@ -2934,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);
|
||||
@@ -2967,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
|
||||
@@ -2995,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) {
|
||||
@@ -4556,12 +4552,12 @@ const decrpytRequest = async (req, res) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST DECRYPT ]: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST DECRYPT ]: received`
|
||||
);
|
||||
|
||||
reservationData = helper.decryptText(reservation_data);
|
||||
const reservationData = helper.decryptText(reservation_data);
|
||||
// parsing data to json format
|
||||
parseData = JSON.parse(reservationData);
|
||||
const parseData = JSON.parse(reservationData);
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'decrypted successfully.',
|
||||
@@ -4570,12 +4566,12 @@ const decrpytRequest = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE DECRYPT ]: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE DECRYPT ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
const result = {
|
||||
code: '500',
|
||||
message: 'decrypted failed.',
|
||||
data: {},
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const createAuditArchive = require('../helpers/audit-archive');
|
||||
const { createStdoutWriter, formatLog } = require('../helpers/stdout-log');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
|
||||
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);
|
||||
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 {
|
||||
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 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 {
|
||||
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();
|
||||
for (const file of fs.readdirSync(directory)) fs.unlinkSync(path.join(directory, file));
|
||||
fs.rmdirSync(directory);
|
||||
}
|
||||
});
|
||||
|
||||
test('Redis deadline releases outstanding commands and later requests use the recovered connection', async () => {
|
||||
let rejectCommand;
|
||||
const client = {
|
||||
isReady: true,
|
||||
isOpen: true,
|
||||
disconnect: jest.fn(async () => {
|
||||
client.isReady = false;
|
||||
client.isOpen = false;
|
||||
rejectCommand(new Error('socket closed'));
|
||||
}),
|
||||
connect: jest.fn(async () => { client.isOpen = true; client.isReady = true; }),
|
||||
};
|
||||
const timedOut = jest.fn();
|
||||
const execute = createRedisOperations(client, { timeoutMs: 20, onTimeout: timedOut });
|
||||
const result = await execute(() => new Promise((resolve, reject) => { rejectCommand = reject; }));
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(timedOut).toHaveBeenCalledTimes(1);
|
||||
expect(client.disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(client.connect).toHaveBeenCalledTimes(1);
|
||||
await expect(execute(async () => 'OK')).resolves.toBe('OK');
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const responseTime = require('response-time');
|
||||
const knex = require('../../infrastructure/database/knex');
|
||||
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/response-audit', () => ({ record: jest.fn() }));
|
||||
jest.mock('winston-daily-rotate-file', () => {
|
||||
const winston = require('winston');
|
||||
const Transport = require('winston-transport');
|
||||
class MemoryTransport extends Transport {
|
||||
log(info, callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
winston.transports.DailyRotateFile = MemoryTransport;
|
||||
return MemoryTransport;
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json(), responseTime(), logger.correlation, logger.request, logger.response);
|
||||
app.post('/api/topup1', (req, res) => {
|
||||
req._startTime = Date.now() - req.body.duration;
|
||||
res.json({ code: '00', data: { trxID: req.body.trxID } });
|
||||
});
|
||||
app.post('/api/topup2', (req, res) => {
|
||||
req.partner_id_token = 'fixture';
|
||||
res.json({ code: '5001', data: {} });
|
||||
});
|
||||
app.post('/api/topup3', (req, res) => {
|
||||
req.partner_id_token = '9917';
|
||||
res.json({ code: '00', data: {} });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
for (const histogram of histograms) histogram.reset();
|
||||
});
|
||||
|
||||
test('distinct transaction IDs and latencies share one histogram series per bucket', async () => {
|
||||
const transactionIds = ['0001', '0002', '0100', '01a0'];
|
||||
const responses = await Promise.all(transactionIds.map((trxID, index) =>
|
||||
request(app).post('/api/topup1?fixture=1').send({ trxID, duration: 200 + index * 100 })
|
||||
));
|
||||
|
||||
for (const histogram of histograms) {
|
||||
const metric = await histogram.get();
|
||||
const counts = metric.values.filter((value) => value.metricName.endsWith('_count'));
|
||||
expect(counts).toEqual([{
|
||||
metricName: `${metric.name}_count`,
|
||||
labels: { route: '/api/topup1', status_code: '00', issuer_name: 'UNDEFINED' },
|
||||
value: transactionIds.length,
|
||||
}]);
|
||||
expect(metric.values.some((entry) => entry.labels.le === 1000)).toBe(true);
|
||||
}
|
||||
|
||||
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',
|
||||
http_status: 200,
|
||||
trx_id: transactionIds[index],
|
||||
});
|
||||
expect(record.response_time_ms).toBeGreaterThanOrEqual(200 + index * 100);
|
||||
expect(record).not.toHaveProperty('labels');
|
||||
});
|
||||
});
|
||||
|
||||
test('logs the valid request transaction ID on HSM failure even if issuer lookup fails', async () => {
|
||||
knex.mockReturnValue({
|
||||
where: jest.fn().mockReturnValue({
|
||||
first: jest.fn().mockReturnValue({ timeout: jest.fn().mockRejectedValue(new Error('DB unavailable')) }),
|
||||
}),
|
||||
});
|
||||
const response = await request(app).post('/api/topup2').send({ trxID: 'ABCD', card_number: 'fixture-card' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const [info] = responseAudit.record.mock.calls[0];
|
||||
expect(info).toMatchObject({
|
||||
level: 'error',
|
||||
status_code: '5001',
|
||||
request_id: response.headers['x-request-id'],
|
||||
trx_id: 'abcd',
|
||||
issuer_name: 'UNDEFINED',
|
||||
});
|
||||
expect(info).not.toHaveProperty('card_number');
|
||||
});
|
||||
|
||||
test('a slow issuer lookup is shared and audit records are emitted while it is pending', async () => {
|
||||
let finishLookup;
|
||||
const pending = new Promise((resolve) => { finishLookup = resolve; });
|
||||
const timeout = jest.fn().mockReturnValue(pending);
|
||||
knex.mockReturnValue({
|
||||
where: jest.fn().mockReturnValue({ first: jest.fn().mockReturnValue({ timeout }) }),
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all(Array.from({ length: 12 }, () => request(app).post('/api/topup3')));
|
||||
expect(timeout).toHaveBeenCalledTimes(1);
|
||||
expect(responseAudit.record).toHaveBeenCalledTimes(12);
|
||||
expect(responseAudit.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
issuer_name: 'UNDEFINED',
|
||||
partner_id: '9917',
|
||||
}));
|
||||
} finally {
|
||||
finishLookup({ c_name: 'Fixture' });
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"__inputs": [
|
||||
{ "name": "DS_PROMETHEUS", "label": "Prometheus", "type": "datasource", "pluginId": "prometheus", "pluginName": "Prometheus" },
|
||||
{ "name": "DS_LOKI", "label": "Loki", "type": "datasource", "pluginId": "loki", "pluginName": "Loki" }
|
||||
],
|
||||
"uid": "topup-observability",
|
||||
"title": "Online TopUp - Latensi dan transaksi",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"time": { "from": "now-1h", "to": "now" },
|
||||
"templating": {
|
||||
"list": [
|
||||
{ "name": "prom_app", "label": "PROM_APP", "type": "textbox", "query": "topuponline", "current": { "text": "topuponline", "value": "topuponline" } },
|
||||
{ "name": "trx_id", "label": "ID transaksi HSM", "type": "textbox", "query": "", "current": { "text": "", "value": "" } },
|
||||
{ "name": "request_id", "label": "X-Request-Id", "type": "textbox", "query": "", "current": { "text": "", "value": "" } },
|
||||
{ "name": "min_ms", "label": "Durasi minimum (ms)", "type": "textbox", "query": "0", "current": { "text": "0", "value": "0" } }
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Latensi p95 per endpoint",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
|
||||
"gridPos": { "h": 9, "w": 12, "x": 0, "y": 0 },
|
||||
"fieldConfig": { "defaults": { "unit": "ms" }, "overrides": [] },
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le, route) (rate(topuponline_response_time_bucket{app=\"$prom_app\"}[$__rate_interval])))",
|
||||
"legendFormat": "{{route}}",
|
||||
"range": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Rata-rata durasi per endpoint",
|
||||
"type": "timeseries",
|
||||
"datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" },
|
||||
"gridPos": { "h": 9, "w": 12, "x": 12, "y": 0 },
|
||||
"fieldConfig": { "defaults": { "unit": "ms" }, "overrides": [] },
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (route) (rate(topuponline_response_time_sum{app=\"$prom_app\"}[$__rate_interval])) / sum by (route) (rate(topuponline_response_time_count{app=\"$prom_app\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{route}}",
|
||||
"range": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Durasi dan transaksi per request",
|
||||
"type": "logs",
|
||||
"datasource": { "type": "loki", "uid": "${DS_LOKI}" },
|
||||
"gridPos": { "h": 13, "w": 24, "x": 0, "y": 9 },
|
||||
"options": { "showTime": true, "showLogDetails": true, "sortOrder": "Descending", "wrapLogMessage": true },
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"queryType": "range",
|
||||
"maxLines": 500,
|
||||
"expr": "{app=\"topuponline\"} |= \"http_response\" | json | event=\"http_response\" | trx_id=~`(?i).*${trx_id:regex}.*` | request_id=~`(?i).*${request_id:regex}.*` | response_time_ms >= ${min_ms:raw} | __error__=\"\" | line_format `{{.route}} {{.status_code}} {{.response_time_ms}}ms trx_id={{.trx_id}} request_id={{.request_id}}`"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# Latensi dan transaksi Online TopUp
|
||||
|
||||
Impor [dashboard Grafana](topup-observability.json) dan pilih data source
|
||||
Prometheus serta Loki. Jika `PROM_APP` dikustomisasi, isi variabel dashboard
|
||||
`PROM_APP` dengan nilai environment itu. Dashboard menampilkan p95 dan rata-rata
|
||||
per endpoint, serta log respons yang dapat difilter berdasarkan ID transaksi,
|
||||
request ID, atau durasi minimum.
|
||||
|
||||
## Melihat detail satu request
|
||||
|
||||
- Di klien HTTP, baca `X-Response-Time` untuk durasi dan `X-Request-Id` untuk
|
||||
korelasi. Endpoint TopUp tetap mengirim ID HSM di `data.trxID` jika tersedia.
|
||||
- Di panel log atau Grafana Explore, pilih rentang waktu sempit dan cari
|
||||
`request_id` dari header. ID ini unik untuk satu request. ID HSM dapat dipakai
|
||||
oleh beberapa request, sehingga hasil `trx_id` bisa lebih dari satu baris.
|
||||
- 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"
|
||||
```
|
||||
|
||||
```logql
|
||||
{app="topuponline"} |= "http_response" | json | event="http_response" | request_id="UUID-DARI-HEADER"
|
||||
```
|
||||
|
||||
```logql
|
||||
{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
|
||||
`date`, `month`, `year`, `response_time`, serta `trxId` dari panel Prometheus.
|
||||
Nama metrik dipertahankan dan satuan durasinya milidetik. Label yang tersedia
|
||||
adalah `route`, `status_code`, `issuer_name`, dan `app` dari registry.
|
||||
Gunakan seri `_bucket` untuk persentil dan pindahkan pencarian transaksi ke
|
||||
panel Loki. Grafik dengan konfigurasi bucket baru lebih mudah dibandingkan
|
||||
setelah semua replika memakai konfigurasi yang sama.
|
||||
|
||||
```promql
|
||||
histogram_quantile(
|
||||
0.95,
|
||||
sum by (le, route) (rate(topuponline_response_time_bucket{app="topuponline"}[5m]))
|
||||
)
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
# Memori dan audit transaksi
|
||||
|
||||
## Arsip dan Loki
|
||||
|
||||
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.
|
||||
|
||||
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 tetap mencoba mencatat ke stdout.
|
||||
Ketersediaan audit saat disk gagal bergantung pada penampung stdout yang terpisah.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
## Redis dan pooling
|
||||
|
||||
Redis membatasi 256 command dan 500 ms per operasi. Saat socket tersendat,
|
||||
koneksi ditutup untuk melepaskan command yang sudah dikirim lalu dibuat ulang.
|
||||
Nomor transaksi tetap memakai klaim unik PostgreSQL. Fallback dapat menambah
|
||||
beban DB, jadi pantau latensi dan timeout pool saat uji beban.
|
||||
|
||||
Pooling memproses paling banyak 500 baris dalam satu transaksi sumber. Baris
|
||||
`raw` dan `valid` tetap ada dengan penanda waktu setelah diproses. Jika commit
|
||||
produk berhasil tetapi update `b_sync` terputus, retry mengenali pasangan kartu
|
||||
dan UID yang sudah tersimpan. Konflik yang tidak cocok meninggalkan data asal
|
||||
untuk pemeriksaan.
|
||||
|
||||
Saat rolling deploy, jeda job validasi dan sinkronisasi pooling sampai pemanggilan
|
||||
versi lama selesai. Versi lama tidak memakai mekanisme klaim batch yang sama.
|
||||
Generated
-513
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -21,6 +21,8 @@ require('dotenv').config();
|
||||
moment.locale('id');
|
||||
const responseTime = require('response-time');
|
||||
const { logger } = require('../application/helpers/getbodyrequest');
|
||||
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 {
|
||||
@@ -37,6 +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 [...auditMetrics, ...stdoutMetrics]) register.registerMetric(metric);
|
||||
|
||||
app.get('/metrics', (req, res) => {
|
||||
res.setHeader('Content-Type', register.contentType);
|
||||
@@ -48,6 +51,7 @@ var corsOptions = {
|
||||
'http://localhost:' + process.env.PORT || 3000,
|
||||
'http://localhost:3000',
|
||||
],
|
||||
exposedHeaders: ['X-Request-Id', 'X-Response-Time'],
|
||||
};
|
||||
|
||||
// app.use(cors(corsOptions));
|
||||
@@ -72,6 +76,7 @@ app.get('/', async (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.use(logger.correlation);
|
||||
app.use(logger.request);
|
||||
app.use(logger.response);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user