mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 11:06:28 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dd7b081550 | |||
| 85fa8843d8 | |||
| 005746e29f | |||
| 34610e9515 | |||
| 297c3d7323 | |||
| ebd97d4408 | |||
| d5d8ea1ce6 | |||
| d8267cc263 | |||
| 58ffbb6920 | |||
| 3d392d1e6f |
@@ -0,0 +1,49 @@
|
||||
# Dependencies & caches (installed cleanly inside Docker build)
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.npm
|
||||
.eslintcache
|
||||
|
||||
# Environment & secret files (inject at runtime via --env-file or orchestrator)
|
||||
.env
|
||||
.env.*
|
||||
env
|
||||
env.copy
|
||||
|
||||
# Version control, CI, editor, and agent metadata
|
||||
.git
|
||||
.gitignore
|
||||
.github
|
||||
.editorconfig
|
||||
.vscode
|
||||
.idea
|
||||
.agents
|
||||
.gemini
|
||||
skills
|
||||
eslint.config.cjs
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
docker-compose*.yml
|
||||
docker-compose*.yaml
|
||||
|
||||
# Logs, audit archives, coverage, and runtime artifacts
|
||||
logs
|
||||
*.log
|
||||
lokiLog
|
||||
expresswinstonlog
|
||||
coverage
|
||||
.nyc_output
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
report.*.json
|
||||
|
||||
# Documentation & tests (not needed in production image)
|
||||
README.md
|
||||
*.md
|
||||
docs
|
||||
application/tests
|
||||
**/*.test.js
|
||||
**/*.spec.js
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '26.13.1'
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ==============================================================================
|
||||
# Stage 1: Production dependencies
|
||||
# ==============================================================================
|
||||
FROM node:26.13.1-alpine3.24 AS deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Native addon build dependencies
|
||||
RUN apk add --no-cache python3 make g++
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci --omit=dev --no-audit --no-fund
|
||||
|
||||
# ==============================================================================
|
||||
# Stage 2: Production runtime
|
||||
# ==============================================================================
|
||||
FROM node:26.13.1-alpine3.24 AS runtime
|
||||
|
||||
# OS security updates and runtime dependencies
|
||||
RUN apk upgrade --no-cache \
|
||||
&& apk add --no-cache tini tzdata
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
TZ=Asia/Jakarta \
|
||||
NO_COLOR=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Runtime writable directories
|
||||
RUN mkdir -p /app/logs /app/lokiLog/audit \
|
||||
&& chown -R node:node /app
|
||||
|
||||
# Production dependencies
|
||||
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
|
||||
|
||||
# Application files
|
||||
COPY --chown=node:node package.json knexfile.js index.js ./
|
||||
COPY --chown=node:node server ./server
|
||||
COPY --chown=node:node infrastructure ./infrastructure
|
||||
COPY --chown=node:node application ./application
|
||||
COPY --chown=node:node public ./public
|
||||
|
||||
# Non-root execution
|
||||
USER node
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# Healthcheck
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD ["node", "-e", "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
|
||||
|
||||
ENTRYPOINT ["/sbin/tini", "--"]
|
||||
CMD ["node", "index.js"]
|
||||
@@ -71,12 +71,22 @@ setelah dibuat dan event hasil menyertakannya, termasuk saat HSM timeout.
|
||||
Permintaan load balance ikut terhubung jika klien mengirim kode sesi yang sama.
|
||||
Setiap panggilan HTTP tetap punya `request_id` sendiri.
|
||||
|
||||
Untuk mengikuti reservasi hingga hasil Top Up, cari event
|
||||
`reservation_topup_link` berdasarkan `reservation_number`. Top Up Step 6
|
||||
mencatat satu event per reservasi dari detail yang berhasil disimpan bersama
|
||||
load balance. Gunakan `unique_code` dari event itu untuk melihat langkah 1–8.
|
||||
Sesi yang berhenti sebelum detail tersimpan belum memiliki hubungan ini.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | request_id="e6aa798c-c8c2-440e-a39b-66bcfbde2f58"
|
||||
{app="topuponline"} | json | route="/api/login" | message="Password is wrong."
|
||||
{app="topuponline"} | json | unique_code="1234567890121"
|
||||
{app="topuponline"} | json | event="reservation_topup_link" | reservation_number="RBLTEST261124000023"
|
||||
{app="topuponline"} | json | event=~"http_request|http_response|http_request_aborted|reservation_topup_link" | (reservation_number="RBLTEST261124000023" or unique_code="1234567890121")
|
||||
```
|
||||
|
||||
Lihat [panduan investigasi Grafana](docs/grafana/topup-observability.md)
|
||||
untuk menelusuri detail `application_log` saat ada error.
|
||||
|
||||
## Kapasitas koneksi PostgreSQL
|
||||
|
||||
Pengaturan pool utama dan pool tambahan ada di `knexfile.js`.
|
||||
|
||||
@@ -14,6 +14,14 @@ function getHsmUniqueCode(value) {
|
||||
return /^\d{1,14}$/.test(code) ? code : undefined;
|
||||
}
|
||||
|
||||
function getReservationNumber(value) {
|
||||
return typeof value === 'string' && /^RBL[a-z0-9-]{1,61}$/i.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function getLoadBalanceNumber(value) {
|
||||
return typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function logStatusCode(value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return 'UNKNOWN';
|
||||
const code = String(value);
|
||||
@@ -27,4 +35,4 @@ function logErrorCode(error) {
|
||||
return typeof name === 'string' && /^[A-Za-z]{1,30}Error$/.test(name) ? name : 'Error';
|
||||
}
|
||||
|
||||
module.exports = { getHsmUniqueCode, logCorrelation, logStatusCode, logErrorCode };
|
||||
module.exports = { getHsmUniqueCode, getReservationNumber, getLoadBalanceNumber, logCorrelation, logStatusCode, logErrorCode };
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
const { getReservationNumber } = require('./log-fields');
|
||||
|
||||
const validationFields = ['amount', 'mid', 'tid', 'card_number'];
|
||||
const customerFields = ['customer_name', 'phone_number'];
|
||||
const cancellationFields = ['reservation_number', 'mid', 'tid'];
|
||||
@@ -13,10 +15,6 @@ const fieldsByRoute = new Map([
|
||||
['/api/reservation/cancel/v2', ['cancel_reservation_data']],
|
||||
]);
|
||||
|
||||
function getReservationNumber(value) {
|
||||
return typeof value === 'string' && /^RBL[a-z0-9-]{1,61}$/i.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function getAmount(value) {
|
||||
if (typeof value !== 'number' && typeof value !== 'string') return undefined;
|
||||
return /^-?\d{1,12}(?:\.\d{1,2})?$/.test(value) ? value : undefined;
|
||||
@@ -52,4 +50,4 @@ function summarizeReservationRequest(route, body) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
module.exports = { fieldsByRoute, getReservationNumber, summarizeReservationRequest };
|
||||
module.exports = { fieldsByRoute, summarizeReservationRequest };
|
||||
|
||||
@@ -48,4 +48,8 @@ function record(event) {
|
||||
writeStdoutLine(line);
|
||||
}
|
||||
|
||||
module.exports = { record, auditMetrics: [auditErrors, retentionErrors] };
|
||||
function close() {
|
||||
archive.close();
|
||||
}
|
||||
|
||||
module.exports = { record, close, auditMetrics: [auditErrors, retentionErrors] };
|
||||
|
||||
@@ -27,6 +27,8 @@ const searchableMessages = new Set([
|
||||
'partner is not match',
|
||||
'card number is not registered',
|
||||
"reservation doesn't exist",
|
||||
'bad request. reservation data is invalid.',
|
||||
'bad request. reservation data is empty.',
|
||||
'reservation exists',
|
||||
'amount must be greater than 0',
|
||||
'your card number has reached the maximum balance',
|
||||
|
||||
@@ -33,4 +33,13 @@ async function redisMiddleware(req, res, next) {
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { redisMiddleware };
|
||||
async function closeRedis() {
|
||||
if (!redisClient.isOpen) return;
|
||||
try {
|
||||
await redisClient.quit();
|
||||
} catch {
|
||||
if (redisClient.isOpen) await redisClient.disconnect().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { redisMiddleware, closeRedis };
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
const { correlation } = require('./request-context.middleware');
|
||||
const { getHsmUniqueCode } = require('../helpers/log-fields');
|
||||
const { getHsmUniqueCode, getLoadBalanceNumber, getReservationNumber } = require('../helpers/log-fields');
|
||||
const { getSearchableResponseMessage, getResponseSummary } = require('../helpers/response-log-message');
|
||||
const {
|
||||
fieldsByRoute: reservationRequestRoutes,
|
||||
getReservationNumber,
|
||||
summarizeReservationRequest,
|
||||
} = require('../helpers/reservation-request-log');
|
||||
const responseAudit = require("../helpers/response-audit");
|
||||
@@ -68,12 +67,6 @@ const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
const usesHsmRequestCode = (route) => /^\/api\/topup[2-8]$/.test(route) || route === '/api/loadbalance/request';
|
||||
|
||||
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();
|
||||
|
||||
@@ -221,7 +214,8 @@ function response(req, res, next) {
|
||||
statusCode,
|
||||
message: getSearchableResponseMessage(body?.message),
|
||||
trxId: getTransactionId(data?.trxID, req.body?.trxID),
|
||||
loadBalanceNumber: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
|
||||
loadBalanceNumber: getLoadBalanceNumber(data?.load_balance_number)
|
||||
?? getLoadBalanceNumber(req.body?.load_balance_number),
|
||||
reservationNumber: getReservationNumber(data?.reservation_number),
|
||||
};
|
||||
return sendJson.call(this, body);
|
||||
@@ -255,6 +249,13 @@ function response(req, res, next) {
|
||||
}
|
||||
|
||||
event.message = summary.message ?? getResponseSummary(event);
|
||||
const failure = matchedRoute === '/api/reservation/v2' && statusCode === '500'
|
||||
? res.locals.reservationFailure
|
||||
: undefined;
|
||||
if (failure) {
|
||||
event.error_code = failure.code;
|
||||
event.error_stage = failure.stage;
|
||||
}
|
||||
if (!auditedRoutes.has(matchedRoute)) {
|
||||
writeStdoutLine(formatLog(event));
|
||||
return;
|
||||
|
||||
@@ -1,8 +1,31 @@
|
||||
const { logCorrelation, logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const {
|
||||
getHsmUniqueCode, getLoadBalanceNumber, getReservationNumber, logCorrelation, logErrorCode, logStatusCode,
|
||||
} = require('../../helpers/log-fields');
|
||||
const { formatLog, writeStdoutLine } = require('../../helpers/stdout-log');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./loadbalance.model');
|
||||
const moment = require('moment');
|
||||
|
||||
// Detail yang disimpan menjadi sumber hubungan reservasi, bukan daftar dari klien.
|
||||
function logReservationTopupLinks(requestId, uniqueCode, loadBalanceNumber, details) {
|
||||
const sessionCode = getHsmUniqueCode(uniqueCode);
|
||||
const balanceNumber = getLoadBalanceNumber(loadBalanceNumber);
|
||||
if (!sessionCode || !balanceNumber) return;
|
||||
|
||||
const reservations = new Set(details.map(detail => getReservationNumber(detail.c_reservation_no)));
|
||||
for (const reservationNumber of reservations) {
|
||||
if (!reservationNumber) continue;
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'reservation_topup_link',
|
||||
level: 'info',
|
||||
request_id: requestId,
|
||||
reservation_number: reservationNumber,
|
||||
unique_code: sessionCode,
|
||||
load_balance_number: balanceNumber,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Alur tulis saldo dipakai oleh HSM dan proses permintaan saldo.
|
||||
const updateAllTransaction = async (
|
||||
reservationNumber,
|
||||
@@ -555,6 +578,7 @@ const loadingBalanceInsert = async (req, param) => {
|
||||
// )} [FLAG] : ${JSON.stringify(flag)}`
|
||||
// );
|
||||
if (insertLoadingBalance > 0) {
|
||||
logReservationTopupLinks(req.id, unique_code, loadBalanceNumber, detail);
|
||||
result = {
|
||||
code: '00',
|
||||
message: write_status
|
||||
|
||||
@@ -82,4 +82,8 @@ const syncBatch = () => processBatch("valid", "b_sync", syncLock, async (trx, ca
|
||||
await knex.transaction((main) => ensureCards(main, "t_m_card_product", cards));
|
||||
});
|
||||
|
||||
module.exports = { insertRawCards, validateBatch, syncBatch };
|
||||
function closePool() {
|
||||
return dbPooling.destroy();
|
||||
}
|
||||
|
||||
module.exports = { insertRawCards, validateBatch, syncBatch, closePool };
|
||||
|
||||
@@ -295,8 +295,20 @@ const validateReplacement = async (req, res) => {
|
||||
|
||||
// if (is_warranty == true) {
|
||||
let result = {};
|
||||
const ctsUrl = process.env.CTS_URL?.trim();
|
||||
if (!ctsUrl) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message: 'CTS connection has not been configured.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
|
||||
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
|
||||
const baseUrl = `${ctsUrl}/v2/api/info/last-balance`;
|
||||
const payload = {
|
||||
card_number: card_number,
|
||||
};
|
||||
@@ -306,7 +318,22 @@ const validateReplacement = async (req, res) => {
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
let response;
|
||||
try {
|
||||
response = await postWithDeadline(url, payload, config);
|
||||
} catch (error) {
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ CTS REQUEST FAILED ] error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '415',
|
||||
message: 'Failed to retrieve last balance from CTS.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
@@ -324,7 +351,7 @@ const validateReplacement = async (req, res) => {
|
||||
}
|
||||
result = {
|
||||
code: '415',
|
||||
message: 'Last Balance not updated.',
|
||||
message: 'Failed to retrieve last balance from CTS.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
@@ -391,7 +418,6 @@ const validateReplacement = async (req, res) => {
|
||||
unique_code: uniqueCode,
|
||||
card_category: {
|
||||
id: dataCardReplacement.card_category_id,
|
||||
code: dataCardReplacement.card_category_code,
|
||||
name: dataCardReplacement.card_category_name
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1474,6 +1474,7 @@ const reservation = async (req, res) => {
|
||||
};
|
||||
|
||||
const reservationV2 = async (req, res) => {
|
||||
let stage = 'validate_request';
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
@@ -1521,13 +1522,16 @@ const reservationV2 = async (req, res) => {
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation data...`
|
||||
// );
|
||||
|
||||
stage = 'decode_reservation_data';
|
||||
let reservationData;
|
||||
|
||||
try {
|
||||
reservationData = helper.decryptText(reservation_data);
|
||||
} catch (error) { }
|
||||
const plaintext = helper.decryptText(reservation_data);
|
||||
if (typeof plaintext === 'string' && plaintext) reservationData = JSON.parse(plaintext);
|
||||
} catch {
|
||||
// Muatan yang gagal didekripsi atau diurai ditolak sebagai input yang tidak valid.
|
||||
}
|
||||
|
||||
if (!reservationData) {
|
||||
if (!reservationData || typeof reservationData !== 'object' || Array.isArray(reservationData)) {
|
||||
result = {
|
||||
code: '435',
|
||||
message: 'bad request. reservation data is invalid.',
|
||||
@@ -1542,9 +1546,6 @@ const reservationV2 = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// parsing data to json format
|
||||
reservationData = JSON.parse(reservationData);
|
||||
|
||||
if (
|
||||
!reservationData.mid ||
|
||||
!reservationData.tid ||
|
||||
@@ -1584,6 +1585,7 @@ const reservationV2 = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
stage = 'check_card_blacklist';
|
||||
let cardBlacklist = await model.getCardBlacklist(
|
||||
reservationData.card_number
|
||||
);
|
||||
@@ -1624,6 +1626,7 @@ const reservationV2 = async (req, res) => {
|
||||
let transactionDate = reservationData.transaction_date;
|
||||
let securityCode = reservationData.security_code;
|
||||
|
||||
stage = 'verify_reservation_data';
|
||||
if (securityCode) {
|
||||
// log debug
|
||||
// process enkripsi data reservasi dengan HMAC sebagai pembanding bahwa data yang di decrypt valid
|
||||
@@ -1724,6 +1727,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
stage = 'lookup_partner';
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
@@ -1757,6 +1761,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// get parameter to check with card product cms or not
|
||||
stage = 'check_reservation_limits';
|
||||
let getCheckByCardProductStatusValue =
|
||||
await model.getCheckByCardProductStatusValue();
|
||||
let checkByCardProductStatusValue =
|
||||
@@ -2010,6 +2015,7 @@ const reservationV2 = async (req, res) => {
|
||||
let channelFee = 0;
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
stage = 'lookup_issuer_fee';
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
@@ -2046,6 +2052,7 @@ const reservationV2 = async (req, res) => {
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting reservation expiration date on parameter...`
|
||||
// );
|
||||
|
||||
stage = 'lookup_reservation_expiration';
|
||||
const { time, measure } = await model.getReservationExpiration();
|
||||
let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
@@ -2062,6 +2069,7 @@ const reservationV2 = async (req, res) => {
|
||||
phoneNumber = mid + '_' + tid;
|
||||
}
|
||||
|
||||
stage = 'allocate_reservation_number';
|
||||
const { number: reservationNumber, sequence: reservationNoSequence } =
|
||||
await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD'));
|
||||
|
||||
@@ -2123,6 +2131,7 @@ const reservationV2 = async (req, res) => {
|
||||
// (belum) ada issue disini, jadi ada case reservation number nya sama, terus error query harusnya ada handle response message nya, yg sekarang malah masuk ke blok reservation saved successfully.
|
||||
|
||||
// insert transaction
|
||||
stage = 'insert_reservation';
|
||||
let insert = await model.insertReservation(data);
|
||||
|
||||
// jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback
|
||||
@@ -2134,6 +2143,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// log card history
|
||||
stage = 'write_reservation_history';
|
||||
await model.createReserveBalanceLog({
|
||||
i_log_name: 90,
|
||||
d_log: now,
|
||||
@@ -2192,9 +2202,11 @@ const reservationV2 = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
} catch (error) {
|
||||
// create log
|
||||
// Simpan tahap dan kode aman tersedia di audit tanpa menyalin exception mentah.
|
||||
const errorCode = logErrorCode(error);
|
||||
res.locals.reservationFailure = { stage, code: errorCode };
|
||||
winston.logger.error(
|
||||
`[ RESPONSE RESERVATION-V2 ] code=500 error_code=${logErrorCode(error)}`
|
||||
`[ RESPONSE RESERVATION-V2 ] code=500 error_code=${errorCode} error_stage=${stage}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
const http = require('node:http');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const {
|
||||
createGracefulShutdown,
|
||||
createClusterShutdown,
|
||||
} = require('../../infrastructure/graceful-shutdown');
|
||||
|
||||
function createLoggerSpy() {
|
||||
return {
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
test('menunggu request HTTP aktif selesai sebelum menutup resource dan keluar dengan kode 0', async () => {
|
||||
const order = [];
|
||||
let releaseInFlight;
|
||||
const inFlightStarted = new Promise((resolve) => {
|
||||
releaseInFlight = resolve;
|
||||
});
|
||||
|
||||
let respondNow;
|
||||
const holdResponse = new Promise((resolve) => {
|
||||
respondNow = resolve;
|
||||
});
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
order.push('http:start');
|
||||
releaseInFlight();
|
||||
await holdResponse;
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
order.push('http:end');
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const { port } = server.address();
|
||||
|
||||
const exit = jest.fn();
|
||||
const logger = createLoggerSpy();
|
||||
const onBeforeClose = jest.fn(() => order.push('before-close'));
|
||||
const cleanupTasks = [
|
||||
{ name: 'postgres', close: jest.fn(async () => order.push('cleanup:postgres')) },
|
||||
{ name: 'redis', close: jest.fn(async () => order.push('cleanup:redis')) },
|
||||
];
|
||||
|
||||
const manager = createGracefulShutdown({
|
||||
servers: [server],
|
||||
cleanupTasks,
|
||||
onBeforeClose,
|
||||
timeoutMs: 2000,
|
||||
logger,
|
||||
exit,
|
||||
});
|
||||
|
||||
const responsePromise = fetch(`http://127.0.0.1:${port}/test`);
|
||||
await inFlightStarted;
|
||||
|
||||
const shutdownPromise = manager.shutdown('SIGTERM');
|
||||
expect(manager.isShuttingDown()).toBe(true);
|
||||
expect(onBeforeClose).toHaveBeenCalledWith('SIGTERM');
|
||||
// Cleanup belum boleh jalan selama request HTTP aktif belum selesai.
|
||||
expect(cleanupTasks[0].close).not.toHaveBeenCalled();
|
||||
|
||||
respondNow();
|
||||
const response = await responsePromise;
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({ ok: true });
|
||||
|
||||
await shutdownPromise;
|
||||
|
||||
expect(order).toEqual([
|
||||
'http:start',
|
||||
'before-close',
|
||||
'http:end',
|
||||
'cleanup:postgres',
|
||||
'cleanup:redis',
|
||||
]);
|
||||
expect(exit).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
test('panggilan shutdown berulang bersifat idempoten dan hanya menjalankan cleanup sekali', async () => {
|
||||
const server = {
|
||||
listening: true,
|
||||
close: jest.fn((cb) => cb()),
|
||||
closeIdleConnections: jest.fn(),
|
||||
};
|
||||
const cleanup = jest.fn(async () => {});
|
||||
const onBeforeClose = jest.fn();
|
||||
const exit = jest.fn();
|
||||
|
||||
const manager = createGracefulShutdown({
|
||||
servers: [server],
|
||||
cleanupTasks: [{ name: 'db', close: cleanup }],
|
||||
onBeforeClose,
|
||||
timeoutMs: 1000,
|
||||
exit,
|
||||
});
|
||||
|
||||
const p1 = manager.shutdown('SIGTERM');
|
||||
const p2 = manager.shutdown('SIGINT');
|
||||
expect(p1).toBe(p2);
|
||||
|
||||
await Promise.all([p1, p2]);
|
||||
|
||||
expect(onBeforeClose).toHaveBeenCalledTimes(1);
|
||||
expect(server.close).toHaveBeenCalledTimes(1);
|
||||
expect(server.closeIdleConnections).toHaveBeenCalledTimes(1);
|
||||
expect(cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
test('kegagalan salah satu cleanup tidak menghentikan cleanup lain dan keluar dengan kode 1', async () => {
|
||||
const logger = createLoggerSpy();
|
||||
const exit = jest.fn();
|
||||
const failingCleanup = jest.fn(async () => {
|
||||
throw new Error('redis quit error');
|
||||
});
|
||||
const healthyCleanup = jest.fn(async () => {});
|
||||
|
||||
const manager = createGracefulShutdown({
|
||||
servers: [],
|
||||
cleanupTasks: [
|
||||
{ name: 'redis', close: failingCleanup },
|
||||
{ name: 'postgres', close: healthyCleanup },
|
||||
],
|
||||
timeoutMs: 1000,
|
||||
logger,
|
||||
exit,
|
||||
});
|
||||
|
||||
await manager.shutdown('SIGTERM');
|
||||
|
||||
expect(failingCleanup).toHaveBeenCalledTimes(1);
|
||||
expect(healthyCleanup).toHaveBeenCalledTimes(1);
|
||||
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('redis: redis quit error'));
|
||||
expect(exit).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
test('memaksa tutup koneksi dan keluar dengan kode 1 jika shutdown melewati batas waktu', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const server = {
|
||||
listening: true,
|
||||
close: jest.fn(() => {
|
||||
// Simulasikan server menggantung dan tidak pernah memanggil callback close.
|
||||
}),
|
||||
closeIdleConnections: jest.fn(),
|
||||
closeAllConnections: jest.fn(),
|
||||
};
|
||||
const logger = createLoggerSpy();
|
||||
const exit = jest.fn();
|
||||
|
||||
const manager = createGracefulShutdown({
|
||||
servers: [server],
|
||||
timeoutMs: 500,
|
||||
logger,
|
||||
exit,
|
||||
});
|
||||
|
||||
void manager.shutdown('SIGTERM');
|
||||
await jest.advanceTimersByTimeAsync(500);
|
||||
|
||||
expect(server.closeAllConnections).toHaveBeenCalledTimes(1);
|
||||
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('timed out'));
|
||||
expect(exit).toHaveBeenCalledWith(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('installSignalHandlers mendaftarkan SIGTERM/SIGINT dan uninstall melepas listener', async () => {
|
||||
const targetProcess = new EventEmitter();
|
||||
const exit = jest.fn();
|
||||
const manager = createGracefulShutdown({
|
||||
servers: [],
|
||||
cleanupTasks: [],
|
||||
timeoutMs: 1000,
|
||||
exit,
|
||||
});
|
||||
|
||||
const uninstall = manager.installSignalHandlers(targetProcess);
|
||||
expect(targetProcess.listenerCount('SIGTERM')).toBe(1);
|
||||
expect(targetProcess.listenerCount('SIGINT')).toBe(1);
|
||||
|
||||
targetProcess.emit('SIGINT');
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(manager.isShuttingDown()).toBe(true);
|
||||
expect(exit).toHaveBeenCalledWith(0);
|
||||
|
||||
uninstall();
|
||||
expect(targetProcess.listenerCount('SIGTERM')).toBe(0);
|
||||
expect(targetProcess.listenerCount('SIGINT')).toBe(0);
|
||||
});
|
||||
|
||||
test('cluster primary mematikan worker tanpa respawn dan keluar dengan kode 0 saat semua worker berhenti', async () => {
|
||||
const clusterModule = new EventEmitter();
|
||||
const worker1 = Object.assign(new EventEmitter(), {
|
||||
id: 1,
|
||||
isDead: () => false,
|
||||
kill: jest.fn(),
|
||||
});
|
||||
const worker2 = Object.assign(new EventEmitter(), {
|
||||
id: 2,
|
||||
isDead: () => false,
|
||||
kill: jest.fn(),
|
||||
});
|
||||
clusterModule.workers = { 1: worker1, 2: worker2 };
|
||||
|
||||
const exit = jest.fn();
|
||||
const clusterShutdown = createClusterShutdown({
|
||||
clusterModule,
|
||||
timeoutMs: 2000,
|
||||
logger: createLoggerSpy(),
|
||||
exit,
|
||||
});
|
||||
|
||||
const promise = clusterShutdown.shutdown('SIGTERM');
|
||||
expect(clusterShutdown.isShuttingDown()).toBe(true);
|
||||
expect(worker1.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
expect(worker2.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
|
||||
clusterModule.emit('exit', worker1);
|
||||
expect(exit).not.toHaveBeenCalled();
|
||||
|
||||
clusterModule.emit('exit', worker2);
|
||||
await promise;
|
||||
|
||||
expect(exit).toHaveBeenCalledTimes(1);
|
||||
expect(exit).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
test('cluster primary mengirim SIGKILL dan keluar kode 1 jika worker melewati timeout', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const clusterModule = new EventEmitter();
|
||||
const stuckWorker = Object.assign(new EventEmitter(), {
|
||||
id: 1,
|
||||
isDead: () => false,
|
||||
kill: jest.fn(),
|
||||
process: { kill: jest.fn() },
|
||||
});
|
||||
clusterModule.workers = { 1: stuckWorker };
|
||||
|
||||
const exit = jest.fn();
|
||||
const clusterShutdown = createClusterShutdown({
|
||||
clusterModule,
|
||||
timeoutMs: 300,
|
||||
logger: createLoggerSpy(),
|
||||
exit,
|
||||
});
|
||||
|
||||
void clusterShutdown.shutdown('SIGTERM');
|
||||
await jest.advanceTimersByTimeAsync(300);
|
||||
|
||||
expect(stuckWorker.kill).toHaveBeenCalledWith('SIGTERM');
|
||||
expect(stuckWorker.process.kill).toHaveBeenCalledWith('SIGKILL');
|
||||
expect(exit).toHaveBeenCalledWith(1);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('closeRedis menutup koneksi terbuka dengan quit dan fallback disconnect saat quit gagal', async () => {
|
||||
const mockClient = {
|
||||
isOpen: false,
|
||||
isReady: false,
|
||||
on: jest.fn(),
|
||||
connect: jest.fn(async () => {}),
|
||||
quit: jest.fn(async () => {}),
|
||||
disconnect: jest.fn(async () => {}),
|
||||
};
|
||||
|
||||
let closeRedis;
|
||||
try {
|
||||
jest.isolateModules(() => {
|
||||
jest.doMock('redis', () => ({ createClient: () => mockClient }));
|
||||
({ closeRedis } = require('../middlewares/redis.middleware'));
|
||||
});
|
||||
|
||||
await closeRedis();
|
||||
expect(mockClient.quit).not.toHaveBeenCalled();
|
||||
|
||||
mockClient.isOpen = true;
|
||||
await closeRedis();
|
||||
expect(mockClient.quit).toHaveBeenCalledTimes(1);
|
||||
|
||||
mockClient.quit.mockRejectedValueOnce(new Error('quit failed'));
|
||||
await closeRedis();
|
||||
expect(mockClient.disconnect).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
jest.dontMock('redis');
|
||||
}
|
||||
});
|
||||
|
||||
test('melempar error jika SHUTDOWN_TIMEOUT_MS tidak valid', () => {
|
||||
const previous = process.env.SHUTDOWN_TIMEOUT_MS;
|
||||
process.env.SHUTDOWN_TIMEOUT_MS = '0';
|
||||
try {
|
||||
expect(() => createGracefulShutdown()).toThrow('SHUTDOWN_TIMEOUT_MS must be a positive integer');
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.SHUTDOWN_TIMEOUT_MS;
|
||||
else process.env.SHUTDOWN_TIMEOUT_MS = previous;
|
||||
}
|
||||
});
|
||||
@@ -1,9 +1,14 @@
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
const { writeStdoutLine } = require('../helpers/stdout-log');
|
||||
const { loadingBalanceInsert, loadingBalanceUpdate } = 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('../helpers/stdout-log', () => ({
|
||||
...jest.requireActual('../helpers/stdout-log'),
|
||||
writeStdoutLine: jest.fn(),
|
||||
}));
|
||||
jest.mock('../modules/loadbalance/loadbalance.model', () => ({
|
||||
getPartner: jest.fn(),
|
||||
findReservationsWithLoadedBalance: jest.fn(),
|
||||
@@ -40,6 +45,7 @@ test('menolak terminal milik partner lain sebelum membaca atau menulis reservasi
|
||||
});
|
||||
expect(model.findReservationsWithLoadedBalance).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
expect(writeStdoutLine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('log layanan tidak menyimpan kode klien mentah atau data kartu', async () => {
|
||||
@@ -84,7 +90,7 @@ function setupPending() {
|
||||
model.allocateLoadBalanceNumber.mockResolvedValue({ number: 'LBLTEST261124000023', sequence: 23 });
|
||||
}
|
||||
|
||||
test('fetches pending details once and preserves the pending order and amounts', async () => {
|
||||
test('fetches pending details once and logs links from the committed details', async () => {
|
||||
setupPending();
|
||||
model.findReservationDetails.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL1', i_reservation_balance: 1, i_reservation_amount: 10 },
|
||||
@@ -92,7 +98,12 @@ test('fetches pending details once and preserves the pending order and amounts',
|
||||
]);
|
||||
model.insertLoadingBalance.mockResolvedValue(1);
|
||||
|
||||
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({
|
||||
await expect(loadingBalanceInsert({ ...req, id: 'fixture-request-id' }, {
|
||||
...input,
|
||||
unique_code: '1234567890121',
|
||||
reservation_number: ['RBL1'],
|
||||
card_number: 'fixture-card',
|
||||
})).resolves.toMatchObject({
|
||||
code: '00',
|
||||
data: { load_balance_number: 'LBLTEST261124000023' },
|
||||
});
|
||||
@@ -106,6 +117,33 @@ test('fetches pending details once and preserves the pending order and amounts',
|
||||
{ c_reservation_no: 'RBL2', i_amount: 20 },
|
||||
{ c_reservation_no: 'RBL1', i_amount: 10 },
|
||||
]);
|
||||
const events = writeStdoutLine.mock.calls.map(([line]) => JSON.parse(line));
|
||||
expect(events).toEqual(['RBL2', 'RBL1'].map(reservationNumber => ({
|
||||
timestamp: expect.any(String),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
level: 'info',
|
||||
event: 'reservation_topup_link',
|
||||
request_id: 'fixture-request-id',
|
||||
reservation_number: reservationNumber,
|
||||
unique_code: '1234567890121',
|
||||
load_balance_number: 'LBLTEST261124000023',
|
||||
})));
|
||||
});
|
||||
|
||||
test('does not log a link when the load balance write fails or the session code is invalid', 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.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
|
||||
|
||||
await expect(loadingBalanceInsert(req, { ...input, unique_code: '1234567890121' }))
|
||||
.resolves.toMatchObject({ code: '433' });
|
||||
await expect(loadingBalanceInsert(req, { ...input, unique_code: 'invalid-session' }))
|
||||
.resolves.toMatchObject({ code: '00' });
|
||||
expect(writeStdoutLine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('preserves code 414 if a pending reservation is absent at the new read', async () => {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const helper = require('../helpers/helper');
|
||||
const model = require('../modules/reservebalance/reservebalance.model');
|
||||
const audit = require('../helpers/response-audit');
|
||||
const validate = require('../modules/reservebalance/reservebalance.validation');
|
||||
const { reservationV2 } = require('../modules/reservebalance/reservation-create.handlers');
|
||||
const { correlation, response } = require('../middlewares/response-telemetry.middleware');
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => jest.fn());
|
||||
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
getUniqueCode: jest.fn(() => '123'),
|
||||
decryptText: jest.fn(),
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../modules/reservebalance/reservebalance.model', () => ({
|
||||
getCardBlacklist: jest.fn(),
|
||||
getPartner: jest.fn(),
|
||||
getCheckByCardProductStatusValue: jest.fn(),
|
||||
getLastBalanceFromCardHistory: jest.fn(),
|
||||
getBIRegulationStatus: jest.fn(),
|
||||
getMaxReservation: jest.fn(),
|
||||
getReservationPendingV2: jest.fn(),
|
||||
getIssuer: jest.fn(),
|
||||
getReservationExpiration: jest.fn(),
|
||||
allocateReservationNumber: jest.fn(),
|
||||
insertReservation: jest.fn(),
|
||||
createReserveBalanceLog: jest.fn(),
|
||||
}));
|
||||
|
||||
const app = express();
|
||||
app.use(correlation, response, express.json());
|
||||
app.post('/api/reservation/v2', (req, res, next) => {
|
||||
req.partner_id_token = 'fixture-partner';
|
||||
next();
|
||||
}, validate('reservationV2'), reservationV2);
|
||||
|
||||
function createReservation() {
|
||||
return request(app).post('/api/reservation/v2')
|
||||
.send({ reservation_data: 'fixture-ciphertext', ref_no: 'fixture-ref' });
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
test.each(['invalid JSON', 'null', '[]'])('payload reservasi %s ditolak tanpa akses database', async (plaintext) => {
|
||||
helper.decryptText.mockReturnValue(plaintext);
|
||||
const result = await createReservation().expect(200);
|
||||
expect(result.body).toEqual({ code: '435', message: 'bad request. reservation data is invalid.', data: {} });
|
||||
expect(model.getCardBlacklist).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('kegagalan alokasi mempertahankan respons dan mencatat tahap serta kode aman di audit', async () => {
|
||||
helper.decryptText.mockReturnValue(JSON.stringify({
|
||||
mid: 'A001', tid: 'B001', card_number: '0000000000000001', amount: 10000, transaction_date: '2026-11-25',
|
||||
}));
|
||||
model.getPartner.mockResolvedValue({ i_partner: 'fixture-partner', partner_code: 'P01' });
|
||||
model.getBIRegulationStatus.mockResolvedValue({ c_value: 'N' });
|
||||
model.getMaxReservation.mockResolvedValue({ c_value: '100000' });
|
||||
model.getReservationPendingV2.mockResolvedValue([]);
|
||||
model.getReservationExpiration.mockResolvedValue({ time: 1, measure: 'hours' });
|
||||
model.allocateReservationNumber.mockRejectedValue(Object.assign(new Error('private database detail'), { code: '42P01' }));
|
||||
|
||||
const result = await createReservation().expect(200);
|
||||
expect(result.body.code).toBe('500');
|
||||
expect(model.insertReservation).not.toHaveBeenCalled();
|
||||
const [event] = audit.record.mock.lastCall;
|
||||
expect(event).toMatchObject({
|
||||
request_id: result.headers['x-request-id'],
|
||||
status_code: '500',
|
||||
error_code: '42P01',
|
||||
error_stage: 'allocate_reservation_number',
|
||||
});
|
||||
expect(JSON.stringify(event)).not.toContain('private database detail');
|
||||
});
|
||||
@@ -12,12 +12,26 @@ jest.mock('../middlewares/response-telemetry.middleware', () => ({
|
||||
|
||||
const app = require('../../server');
|
||||
|
||||
test('entry point menyajikan halaman utama, file publik, dan metrik', async () => {
|
||||
test('entry point menyajikan halaman utama, file publik, metrik, dan health', async () => {
|
||||
await request(app).get('/').expect(200, { message: 'Welcome to Topup Online Service.', data: {} });
|
||||
await request(app).get('/health').expect(200, { status: 'ok' });
|
||||
await request(app).get('/images/logo_portal_kmt.png').expect(200).expect('Content-Type', /image\/png/);
|
||||
await request(app).get('/metrics').expect(200).expect('Content-Type', /text\/plain/);
|
||||
});
|
||||
|
||||
test('health mengembalikan 503 dan header Connection close saat proses shutting down', async () => {
|
||||
try {
|
||||
app.setShuttingDown(true);
|
||||
expect(app.isShuttingDown()).toBe(true);
|
||||
|
||||
const response = await request(app).get('/health').expect(503, { status: 'shutting_down' });
|
||||
expect(response.headers.connection).toBe('close');
|
||||
} finally {
|
||||
app.setShuttingDown(false);
|
||||
expect(app.isShuttingDown()).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('entry point mempertahankan parse JSON, form, dan header CORS', async () => {
|
||||
await request(app).post('/api/fixture')
|
||||
.set('Origin', 'http://localhost:3000')
|
||||
|
||||
@@ -16,8 +16,16 @@ headers {
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "partner@example.test",
|
||||
"password": "SamplePassword-OnlyForLocal"
|
||||
"email": "{{process.env.BRUNO_PARTNER_EMAIL}}",
|
||||
"password": "{{process.env.BRUNO_PARTNER_PASSWORD}}"
|
||||
}
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
const body = res.getBody();
|
||||
if (body?.code === '00' && body.data?.access_token && body.data?.refresh_token) {
|
||||
bru.setVar('accessToken', body.data.access_token);
|
||||
bru.setVar('refreshToken', body.data.refresh_token);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,25 +20,25 @@ auth:bearer {
|
||||
|
||||
body:json {
|
||||
{
|
||||
"card_number": "0000000000000001",
|
||||
"station_code": "TEST01"
|
||||
"card_number": "1003012302000000",
|
||||
"station_code": "BOO"
|
||||
}
|
||||
}
|
||||
|
||||
docs {
|
||||
### Deskripsi
|
||||
Memeriksa kelayakan kartu untuk penggantian dan menyiapkan data konfirmasi.
|
||||
|
||||
|
||||
### Request
|
||||
- Endpoint POST /api/pos/cardreplacement/validate
|
||||
- Kirim Authorization: Bearer dengan accessToken dari login.
|
||||
- Contoh JSON tersedia di tab Body.
|
||||
- Route tidak membaca query atau path parameter tambahan.
|
||||
|
||||
|
||||
### Respons
|
||||
|
||||
|
||||
Handler umumnya mengembalikan HTTP 200. Untuk hasil aplikasi, periksa field code, message, dan data. Gunakan header X-Request-Id untuk pencarian log.
|
||||
|
||||
|
||||
| Code | Message |
|
||||
| --- | --- |
|
||||
| 00 | Successfully. |
|
||||
@@ -60,10 +60,10 @@ docs {
|
||||
| 494 | No data found in CTS for the given card number |
|
||||
| 500 | *Pesan kegagalan dapat berasal dari exception atau dependensi.* |
|
||||
| 500 | 500 internal server error - backend server. |
|
||||
|
||||
|
||||
**Pesan validasi yang dapat dikembalikan**
|
||||
- Card number is required
|
||||
- Station Code is required
|
||||
|
||||
|
||||
Pesan yang dicetak miring bersifat dinamis. Nilai aktual dapat mengikuti input atau hasil dari service lain.
|
||||
}
|
||||
|
||||
@@ -18,7 +18,11 @@ Koleksi Bruno ini mengikuti route yang terpasang melalui `server/routes.js` dan
|
||||
|
||||
1. Buka Bruno, pilih **Open Collection**, lalu pilih folder `docs/api/bruno`.
|
||||
2. Pilih environment **Local**. Sesuaikan `baseUrl` dengan alamat dan port lokal service. Path `/api` sudah termasuk.
|
||||
3. Isi secret `accessToken` dengan `data.access_token` dan `refreshToken` dengan `data.refresh_token` dari respons login di lingkungan uji.
|
||||
3. Untuk **Log In as Partner User**, isi `BRUNO_PARTNER_EMAIL` dan
|
||||
`BRUNO_PARTNER_PASSWORD` pada file lokal `docs/api/bruno/.env`. Bruno
|
||||
membaca file tersebut dari folder koleksi. Setelah login berhasil, skrip
|
||||
menyimpan token sebagai variabel runtime. Untuk alur login lain, isi secret
|
||||
`accessToken` dan `refreshToken` dari respons login di lingkungan uji.
|
||||
4. Periksa tab **Body**, **Headers**, **Params**, dan **Auth** sesuai konfigurasi tiap request. Ganti nilai sintetis dengan data uji yang terdaftar bila diperlukan.
|
||||
5. Isi placeholder yang berasal dari respons sebelumnya atau perangkat uji sesuai petunjuk pada tab **Docs**. Jalankan request pada lingkungan lokal atau nonproduksi.
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
vars {
|
||||
baseUrl: https://dev-topup.kci.id/api
|
||||
reservationData: ISI_DARI_LINGKUNGAN_UJI
|
||||
cancelReservationData: ISI_DARI_LINGKUNGAN_UJI
|
||||
replacementUniqueCode: SAMPLE-HSM-01
|
||||
replacementSecurityCode: ISI_DARI_LINGKUNGAN_UJI
|
||||
redeemSecurityCode: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep1Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep2Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupUniqueCode: SAMPLE-HSM-01
|
||||
topupTrxId: 0001
|
||||
topupStep3Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep4Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep5Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep6Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep7Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupLoadBalanceNumber: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep1Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep2Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearUniqueCode: SAMPLE-HSM-01
|
||||
clearTrxId: 0001
|
||||
clearStep3Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep4Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep5Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep6Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep7Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
}
|
||||
vars:secret [
|
||||
accessToken,
|
||||
refreshToken
|
||||
]
|
||||
@@ -14,8 +14,9 @@ request ID, atau durasi minimum.
|
||||
`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`.
|
||||
ID HSM dicatat dalam huruf kecil. Respons sukses pada route transaksi
|
||||
dicatat di level `info`. Penolakan aplikasi dicatat di `warn` dan kegagalan
|
||||
backend di `error`.
|
||||
- `http_status` memuat status HTTP, sedangkan `status_code` memuat kode aplikasi.
|
||||
|
||||
```logql
|
||||
@@ -30,14 +31,40 @@ request ID, atau durasi minimum.
|
||||
{app="topuponline"} |= "http_response" | json | event="http_response" | response_time_ms >= 1000 | __error__=""
|
||||
```
|
||||
|
||||
## Menelusuri reservasi sampai Top Up Step 8
|
||||
|
||||
1. Ambil `unique_code` dari event penghubung Step 6.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | event="reservation_topup_link" | reservation_number="<RBL>"
|
||||
```
|
||||
|
||||
2. Tampilkan timeline HTTP dan event penghubung dengan RBL serta kode sesi.
|
||||
|
||||
```logql
|
||||
{app="topuponline"}
|
||||
| json
|
||||
| event=~"http_request|http_response|http_request_aborted|reservation_topup_link"
|
||||
| (reservation_number="<RBL>" or unique_code="<KODE_SESI>")
|
||||
```
|
||||
|
||||
Respons Step 1 bisa ditemukan lewat kode sesi. Event request awal Step 1
|
||||
ditulis sebelum kode sesi dibuat. Cari langsung berdasarkan `request_id`
|
||||
untuk melihat baris awal tersebut. Tambahkan filter `event="application_log"`
|
||||
untuk melihat detail handler saat ada error.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | event="application_log" | request_id="<X-Request-Id>"
|
||||
```
|
||||
|
||||
## 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.
|
||||
Respons terpantau menggunakan `event=http_response`; log Winston menggunakan
|
||||
`event=application_log`. Request tidak dicatat sebagai event terpisah karena
|
||||
ID request dan statusnya tersedia pada event respons. Field `timestamp`
|
||||
Respons terpantau menggunakan `event=http_response`. Awal request pada route
|
||||
tertentu menggunakan `event=http_request`. Log internal Winston menggunakan
|
||||
`event=application_log`. Field `timestamp`
|
||||
menggunakan WIB dengan offset `+07:00`, misalnya
|
||||
`2026-11-25T00:30:00.000+07:00`.
|
||||
|
||||
|
||||
@@ -14,6 +14,24 @@ Pada alokasi pertama untuk suatu awalan, aplikasi membaca nomor terakhir dari da
|
||||
|
||||
Format enam digit menyediakan 999.999 nomor per jenis, kode partner, dan tanggal. Jika kapasitas satu awalan habis, alokasi gagal dengan pesan diagnostik dan tetap mempertahankan format nomor.
|
||||
|
||||
## Diagnosis kode PostgreSQL 42P01
|
||||
|
||||
Jalankan pemeriksaan katalog berikut dengan koneksi PostgreSQL yang dipakai
|
||||
instance API. Nilai kosong berarti relasi tersebut tidak tersedia.
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
to_regclass('trx.t_transaction_number_counter') AS counter_table,
|
||||
to_regclass('trx.t_d_reservation_no_validate') AS reservation_claims,
|
||||
to_regclass('trx.t_d_reservation_balance') AS reservations;
|
||||
```
|
||||
|
||||
Jika hanya `counter_table` yang kosong, jalankan migrasi
|
||||
`20261124000100_create_transaction_number_counter.js` melalui
|
||||
`knex migrate:up` pada environment Knex yang sama dengan proses API. Ulangi
|
||||
pemeriksaan katalog setelah migrasi. Jika tabel lain yang kosong, cocokkan
|
||||
target database dan skema aplikasi sebelum menjalankan migrasi tambahan.
|
||||
|
||||
## Pengujian lokal
|
||||
|
||||
Suite `application/tests/transaction-number.integration.test.js` memakai PostgreSQL lokal yang dapat dibuang dengan nama database `topup_test` dan skema `trx` yang belum ada. Isi `TOPUP_TEST_NUMBER_DB_URL` dengan URL database uji itu, lalu jalankan `npm test -- --runInBand application/tests/transaction-number.integration.test.js`.
|
||||
|
||||
@@ -3,6 +3,7 @@ require('./infrastructure/transaction-time').configureTransactionClock();
|
||||
const cluster = require('node:cluster');
|
||||
const { createServer } = require('node:http');
|
||||
const { clusterWorkerCount } = require('./infrastructure/runtime-config');
|
||||
const { createGracefulShutdown, createClusterShutdown } = require('./infrastructure/graceful-shutdown');
|
||||
require('./knexfile'); // Validate pool limits before starting any workers.
|
||||
const winston = require('./application/helpers/winston.logger');
|
||||
|
||||
@@ -33,23 +34,60 @@ if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
|
||||
}
|
||||
}
|
||||
|
||||
function createAppCleanupTasks() {
|
||||
const knex = require('./infrastructure/database/knex');
|
||||
const { closePool: closePoolingPool } = require('./application/modules/pooling/pooling.model');
|
||||
const { closeRedis } = require('./application/middlewares/redis.middleware');
|
||||
const { close: closeAuditArchive } = require('./application/helpers/response-audit');
|
||||
|
||||
return [
|
||||
{ name: 'postgres-primary', close: () => knex.destroy() },
|
||||
{ name: 'postgres-pooling', close: () => closePoolingPool() },
|
||||
{ name: 'redis', close: () => closeRedis() },
|
||||
{ name: 'audit-archive', close: () => closeAuditArchive() },
|
||||
];
|
||||
}
|
||||
|
||||
function attachWorkerShutdown(app, servers) {
|
||||
const gracefulShutdown = createGracefulShutdown({
|
||||
servers,
|
||||
cleanupTasks: createAppCleanupTasks(),
|
||||
onBeforeClose: () => app?.setShuttingDown(true),
|
||||
logger: winston.logger,
|
||||
});
|
||||
gracefulShutdown.installSignalHandlers();
|
||||
return gracefulShutdown;
|
||||
}
|
||||
|
||||
if (clustered) {
|
||||
if (cluster.isPrimary) {
|
||||
const workerCount = clusterWorkerCount();
|
||||
if (stickySession || multiplePorts) {
|
||||
winston.logger.warn('CLUSTER_NODE=YES takes precedence over sticky session and multiple ports');
|
||||
}
|
||||
const clusterShutdown = createClusterShutdown({
|
||||
clusterModule: cluster,
|
||||
logger: winston.logger,
|
||||
});
|
||||
clusterShutdown.installSignalHandlers();
|
||||
|
||||
winston.logger.info(`Starting Node.js cluster with ${workerCount} workers`);
|
||||
for (let i = 0; i < workerCount; i++) {
|
||||
cluster.fork();
|
||||
}
|
||||
|
||||
cluster.on('exit', (worker, code) => {
|
||||
if (clusterShutdown.isShuttingDown()) {
|
||||
winston.logger.info(`Worker ${worker.process.pid} exited with code ${code} during shutdown`);
|
||||
return;
|
||||
}
|
||||
winston.logger.warn(`Worker ${worker.process.pid} exited with code ${code}. Starting replacement`);
|
||||
cluster.fork();
|
||||
});
|
||||
} else {
|
||||
require('./server').listen(port, () => logListening(port, ' with cluster node'));
|
||||
const app = require('./server');
|
||||
const server = app.listen(port, () => logListening(port, ' with cluster node'));
|
||||
attachWorkerShutdown(app, [server]);
|
||||
}
|
||||
} else if (stickySession) {
|
||||
const workerCount = clusterWorkerCount();
|
||||
@@ -60,8 +98,10 @@ if (clustered) {
|
||||
}
|
||||
winston.logger.info(`Starting sticky session cluster with ${workerCount} workers`);
|
||||
}
|
||||
let workerApp;
|
||||
const server = sticky(workerCount, () => {
|
||||
const workerServer = createServer(require('./server'));
|
||||
workerApp = require('./server');
|
||||
const workerServer = createServer(workerApp);
|
||||
workerServer.on('connection', (socket) => socket.resume());
|
||||
return workerServer;
|
||||
});
|
||||
@@ -69,6 +109,14 @@ if (clustered) {
|
||||
// Keep the first HTTP bytes on the socket until the worker takes ownership.
|
||||
server.pauseOnConnect = true;
|
||||
server.listen(port, () => logListening(port, ' with sticky session'));
|
||||
const clusterShutdown = createClusterShutdown({
|
||||
clusterModule: cluster,
|
||||
servers: [server],
|
||||
logger: winston.logger,
|
||||
});
|
||||
clusterShutdown.installSignalHandlers();
|
||||
} else {
|
||||
attachWorkerShutdown(workerApp, [server]);
|
||||
}
|
||||
} else {
|
||||
const app = require('./server');
|
||||
@@ -80,9 +128,11 @@ if (clustered) {
|
||||
} else if (multiplePorts) {
|
||||
winston.logger.warn('Running on multiple ports is active but PORTS is unset');
|
||||
}
|
||||
const servers = [];
|
||||
for (const listenPort of ports) {
|
||||
app.listen(listenPort, () => logListening(listenPort));
|
||||
servers.push(app.listen(listenPort, () => logListening(listenPort)));
|
||||
}
|
||||
attachWorkerShutdown(app, servers);
|
||||
}
|
||||
|
||||
function logListening(listenPort, mode = '') {
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
const { positiveIntegerFromEnv } = require('./runtime-config');
|
||||
|
||||
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10000;
|
||||
const IDLE_SWEEP_INTERVAL_MS = 100;
|
||||
const noopLogger = { info() {}, warn() {}, error() {} };
|
||||
|
||||
function closeHttpServer(server) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!server || typeof server.close !== 'function') {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
if (server.listening === false) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
let settled = false;
|
||||
let idleSweepTimer;
|
||||
const finish = (error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (idleSweepTimer) clearInterval(idleSweepTimer);
|
||||
if (error && error.code !== 'ERR_SERVER_NOT_RUNNING') reject(error);
|
||||
else resolve();
|
||||
};
|
||||
|
||||
try {
|
||||
server.close(finish);
|
||||
if (typeof server.closeIdleConnections === 'function') {
|
||||
server.closeIdleConnections();
|
||||
// Close keep-alive sockets as soon as their in-flight requests finish.
|
||||
idleSweepTimer = setInterval(() => {
|
||||
if (!settled) server.closeIdleConnections();
|
||||
}, IDLE_SWEEP_INTERVAL_MS);
|
||||
if (typeof idleSweepTimer.unref === 'function') {
|
||||
idleSweepTimer.unref();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
finish(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function forceCloseHttpServer(server) {
|
||||
if (server && typeof server.closeAllConnections === 'function') {
|
||||
server.closeAllConnections();
|
||||
}
|
||||
}
|
||||
|
||||
function createGracefulShutdown({
|
||||
servers = [],
|
||||
cleanupTasks = [],
|
||||
onBeforeClose,
|
||||
timeoutMs = positiveIntegerFromEnv('SHUTDOWN_TIMEOUT_MS', DEFAULT_SHUTDOWN_TIMEOUT_MS),
|
||||
logger = noopLogger,
|
||||
exit = (code) => process.exit(code),
|
||||
} = {}) {
|
||||
let shutdownPromise = null;
|
||||
let shuttingDown = false;
|
||||
|
||||
function isShuttingDown() {
|
||||
return shuttingDown;
|
||||
}
|
||||
|
||||
function shutdown(signal = 'SIGTERM') {
|
||||
if (shutdownPromise) {
|
||||
return shutdownPromise;
|
||||
}
|
||||
|
||||
shuttingDown = true;
|
||||
logger.info(`Received ${signal}; starting graceful shutdown (timeout ${timeoutMs}ms)`);
|
||||
|
||||
try {
|
||||
if (typeof onBeforeClose === 'function') {
|
||||
onBeforeClose(signal);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Pre-shutdown hook failed: ${error?.message || error}`);
|
||||
}
|
||||
|
||||
let timedOut = false;
|
||||
let timer;
|
||||
|
||||
shutdownPromise = (async () => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
logger.error(`Graceful shutdown timed out after ${timeoutMs}ms; forcing connections closed`);
|
||||
for (const server of servers) {
|
||||
try {
|
||||
forceCloseHttpServer(server);
|
||||
} catch {
|
||||
// Best-effort force close when shutdown deadline expires.
|
||||
}
|
||||
}
|
||||
exit(1);
|
||||
}, timeoutMs);
|
||||
|
||||
if (typeof timer.unref === 'function') {
|
||||
timer.unref();
|
||||
}
|
||||
|
||||
let hasErrors = false;
|
||||
|
||||
const serverResults = await Promise.allSettled(
|
||||
servers.map((server) => closeHttpServer(server))
|
||||
);
|
||||
for (const result of serverResults) {
|
||||
if (result.status === 'rejected') {
|
||||
hasErrors = true;
|
||||
logger.error(`HTTP server close failed: ${result.reason?.message || result.reason}`);
|
||||
}
|
||||
}
|
||||
|
||||
const taskResults = await Promise.allSettled(
|
||||
cleanupTasks.map(async (task) => {
|
||||
const name = task?.name || 'resource';
|
||||
const close = typeof task === 'function' ? task : task?.close;
|
||||
if (typeof close !== 'function') return;
|
||||
try {
|
||||
await close();
|
||||
} catch (error) {
|
||||
throw new Error(`${name}: ${error?.message || error}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (const result of taskResults) {
|
||||
if (result.status === 'rejected') {
|
||||
hasErrors = true;
|
||||
logger.error(`Resource cleanup failed during shutdown (${result.reason?.message || result.reason})`);
|
||||
}
|
||||
}
|
||||
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!timedOut) {
|
||||
if (hasErrors) {
|
||||
logger.warn('Graceful shutdown completed with errors');
|
||||
exit(1);
|
||||
} else {
|
||||
logger.info('Graceful shutdown completed cleanly');
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return shutdownPromise;
|
||||
}
|
||||
|
||||
function installSignalHandlers(targetProcess = process, signals = ['SIGTERM', 'SIGINT']) {
|
||||
const handlers = new Map();
|
||||
for (const signal of signals) {
|
||||
const handler = () => {
|
||||
void shutdown(signal);
|
||||
};
|
||||
handlers.set(signal, handler);
|
||||
targetProcess.on(signal, handler);
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const [signal, handler] of handlers.entries()) {
|
||||
if (typeof targetProcess.off === 'function') {
|
||||
targetProcess.off(signal, handler);
|
||||
} else if (typeof targetProcess.removeListener === 'function') {
|
||||
targetProcess.removeListener(signal, handler);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
shutdown,
|
||||
isShuttingDown,
|
||||
installSignalHandlers,
|
||||
};
|
||||
}
|
||||
|
||||
function createClusterShutdown({
|
||||
clusterModule,
|
||||
servers = [],
|
||||
onBeforeClose,
|
||||
timeoutMs = positiveIntegerFromEnv('SHUTDOWN_TIMEOUT_MS', DEFAULT_SHUTDOWN_TIMEOUT_MS),
|
||||
logger = noopLogger,
|
||||
exit = (code) => process.exit(code),
|
||||
} = {}) {
|
||||
let shutdownPromise = null;
|
||||
let shuttingDown = false;
|
||||
|
||||
function isShuttingDown() {
|
||||
return shuttingDown;
|
||||
}
|
||||
|
||||
function shutdown(signal = 'SIGTERM') {
|
||||
if (shutdownPromise) {
|
||||
return shutdownPromise;
|
||||
}
|
||||
|
||||
shuttingDown = true;
|
||||
logger.info(`Cluster primary received ${signal}; shutting down workers (timeout ${timeoutMs}ms)`);
|
||||
|
||||
try {
|
||||
if (typeof onBeforeClose === 'function') {
|
||||
onBeforeClose(signal);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Cluster pre-shutdown hook failed: ${error?.message || error}`);
|
||||
}
|
||||
|
||||
shutdownPromise = (async () => {
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
logger.error(`Cluster shutdown timed out after ${timeoutMs}ms; sending SIGKILL to remaining workers`);
|
||||
const activeWorkers = Object.values(clusterModule?.workers || {}).filter(Boolean);
|
||||
for (const worker of activeWorkers) {
|
||||
try {
|
||||
if (worker.process && typeof worker.process.kill === 'function') {
|
||||
worker.process.kill('SIGKILL');
|
||||
} else if (typeof worker.kill === 'function') {
|
||||
worker.kill('SIGKILL');
|
||||
}
|
||||
} catch {
|
||||
// Worker may already have exited.
|
||||
}
|
||||
}
|
||||
exit(1);
|
||||
}, timeoutMs);
|
||||
|
||||
if (typeof timer.unref === 'function') {
|
||||
timer.unref();
|
||||
}
|
||||
|
||||
if (servers.length > 0) {
|
||||
await Promise.allSettled(servers.map((server) => closeHttpServer(server)));
|
||||
}
|
||||
|
||||
const workers = Object.values(clusterModule?.workers || {}).filter(
|
||||
(worker) => worker && !(typeof worker.isDead === 'function' && worker.isDead())
|
||||
);
|
||||
|
||||
if (workers.length > 0 && clusterModule && typeof clusterModule.on === 'function') {
|
||||
await new Promise((resolve) => {
|
||||
const remaining = new Set(workers.map((worker) => worker.id));
|
||||
|
||||
const onExit = (exitedWorker) => {
|
||||
if (exitedWorker) {
|
||||
remaining.delete(exitedWorker.id);
|
||||
}
|
||||
if (remaining.size === 0) {
|
||||
cleanupListener();
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
const cleanupListener = () => {
|
||||
if (typeof clusterModule.off === 'function') {
|
||||
clusterModule.off('exit', onExit);
|
||||
} else if (typeof clusterModule.removeListener === 'function') {
|
||||
clusterModule.removeListener('exit', onExit);
|
||||
}
|
||||
};
|
||||
|
||||
clusterModule.on('exit', onExit);
|
||||
|
||||
for (const worker of workers) {
|
||||
try {
|
||||
if (typeof worker.removeAllListeners === 'function') {
|
||||
worker.removeAllListeners('exit');
|
||||
}
|
||||
if (typeof worker.kill === 'function') {
|
||||
worker.kill(signal);
|
||||
}
|
||||
} catch {
|
||||
remaining.delete(worker.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (remaining.size === 0) {
|
||||
cleanupListener();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!timedOut) {
|
||||
logger.info('Cluster primary shutdown completed cleanly');
|
||||
exit(0);
|
||||
}
|
||||
})();
|
||||
|
||||
return shutdownPromise;
|
||||
}
|
||||
|
||||
function installSignalHandlers(targetProcess = process, signals = ['SIGTERM', 'SIGINT']) {
|
||||
const handlers = new Map();
|
||||
for (const signal of signals) {
|
||||
const handler = () => {
|
||||
void shutdown(signal);
|
||||
};
|
||||
handlers.set(signal, handler);
|
||||
targetProcess.on(signal, handler);
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const [signal, handler] of handlers.entries()) {
|
||||
if (typeof targetProcess.off === 'function') {
|
||||
targetProcess.off(signal, handler);
|
||||
} else if (typeof targetProcess.removeListener === 'function') {
|
||||
targetProcess.removeListener(signal, handler);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
shutdown,
|
||||
isShuttingDown,
|
||||
installSignalHandlers,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_SHUTDOWN_TIMEOUT_MS,
|
||||
closeHttpServer,
|
||||
createGracefulShutdown,
|
||||
createClusterShutdown,
|
||||
};
|
||||
Generated
+1024
-2447
File diff suppressed because it is too large
Load Diff
+6
-3
@@ -1,8 +1,11 @@
|
||||
{
|
||||
"name": "onlinetopup-v1",
|
||||
"version": "1.6.6",
|
||||
"version": "1.6.7",
|
||||
"description": "optimize query and coding enhancement",
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"node": ">=26.13.1 <27"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "nodemon index",
|
||||
"migrate": "knex migrate:latest",
|
||||
@@ -24,7 +27,7 @@
|
||||
"homepage": "https://github.com/mohamadihsan/topuponline#readme",
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bcrypt": "^6.0.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.1.1",
|
||||
"dotenv": "^8.2.0",
|
||||
@@ -35,7 +38,7 @@
|
||||
"knex": "^3.1.0",
|
||||
"moment": "^2.29.3",
|
||||
"pg": "^8.6.0",
|
||||
"pm2": "^6.0.13",
|
||||
"pm2": "^7.1.2",
|
||||
"prom-client": "^14.2.0",
|
||||
"redis": "^4.6.5",
|
||||
"response-time": "^2.3.2",
|
||||
|
||||
@@ -15,9 +15,28 @@ moment.locale('id');
|
||||
|
||||
const app = express();
|
||||
const port = process.env.PORT || '3000';
|
||||
let shuttingDown = false;
|
||||
|
||||
app.setShuttingDown = (value = true) => {
|
||||
shuttingDown = Boolean(value);
|
||||
};
|
||||
app.isShuttingDown = () => shuttingDown;
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (shuttingDown) {
|
||||
res.setHeader('Connection', 'close');
|
||||
}
|
||||
next();
|
||||
});
|
||||
app.use(correlation);
|
||||
mountMetrics(app);
|
||||
app.get('/health', (req, res) => {
|
||||
if (shuttingDown) {
|
||||
res.status(503).json({ status: 'shutting_down' });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ status: 'ok' });
|
||||
});
|
||||
app.use(cors({
|
||||
origin: ['http://localhost:' + port, 'http://localhost:3000'],
|
||||
exposedHeaders: ['X-Request-Id', 'X-Response-Time'],
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
name: run-workflow
|
||||
description: 'How to write and run a dynamic workflow script with the `run_workflow` tool: a Python script that orchestrates many agents with `agent`, `parallel`, `pipeline`, and `phase`. Use when a task splits into many independent or staged pieces of agent work (fan out over files, modules, bugs, or review angles, then aggregate), or when the user asks for a workflow. Don''t use for a single delegated task (use a subagent) or for legacy workflow files (see migrate-workflows).'
|
||||
metadata:
|
||||
namespace: system
|
||||
---
|
||||
# Dynamic workflows with `run_workflow`
|
||||
|
||||
A workflow is a short Python script that the `run_workflow` tool executes. The
|
||||
script decides which agents to start, in what order, and what to do with their
|
||||
results. Use it instead of many manual subagent calls when the orchestration
|
||||
itself is code: loops over a list, fan-out then aggregate, or staged pipelines.
|
||||
|
||||
## Steps
|
||||
|
||||
1. Pass the script inline as `Script`, or write it to a file (for example in
|
||||
the conversation scratch directory) and pass its absolute path as
|
||||
`ScriptPath`. Set exactly one of them; a file is easier to fix and rerun.
|
||||
2. Call `run_workflow(Script="...", Description="...")` or
|
||||
`run_workflow(ScriptPath="/abs/path/workflow.py", Description="...")`.
|
||||
`Description` is a one-line goal shown in the UI.
|
||||
The workflow runs in the background, and you are notified when it ends.
|
||||
For a quick script, such as a `call_tool` fan-out, set
|
||||
`WaitMsBeforeAsync` (up to 10000) to get the result in the same turn if it
|
||||
finishes in time.
|
||||
To pass inputs, set `Args` to a JSON object; the script reads it as the
|
||||
`args` dict. When `ScriptPath` is a saved workflow's entry script, `Args`
|
||||
is validated against the args schema in its `workflow.json`.
|
||||
3. Read the tool result: it contains the `log()` output (`Logs:`) and what the
|
||||
script printed (`Output:`). Each agent is also linked from the workflow
|
||||
step, so the user can open its conversation.
|
||||
4. If the tool returns an error, fix the script at the reported line and run
|
||||
it again.
|
||||
|
||||
## Script rules
|
||||
|
||||
The script runs in its own `python3` process, which needs Python 3.8 or later
|
||||
on `PATH`:
|
||||
|
||||
- `await` works at the top level, and you can define `async def` helpers.
|
||||
- Installed library workflows are importable by name (`import <library>` or
|
||||
`from <library> import <name>`); library modules see the same primitives as
|
||||
the script.
|
||||
- What the script prints (`print()`, `stderr`, child-process output, and the
|
||||
`repr` of a trailing expression) is returned in the tool result's `Output:`
|
||||
section (and appended to the error when the workflow fails).
|
||||
- An uncaught exception stops the workflow and reports the script line.
|
||||
- `CONVERSATION_ID` and `STEP_INDEX` identify the `run_workflow` step.
|
||||
`WORKSPACES` is a tuple of the workspace directories, primary first (empty
|
||||
if there are none).
|
||||
- The working directory is `Cwd` if given, else `WORKSPACES[0]`, so relative
|
||||
paths resolve against it. Local modules are not importable.
|
||||
|
||||
## Primitives
|
||||
|
||||
| Primitive | Behavior |
|
||||
| --- | --- |
|
||||
| `log(*args)` | Adds a line to the workflow output and the UI. |
|
||||
| `phase(name)` | Starts a named phase; later logs and agents group under it. |
|
||||
| `agent(prompt=None, schema=None, role=None, type_name="self", workspace="inherit", model=None)` | Defines an agent; nothing runs yet. `await agent(prompt, schema)` runs it once and returns its result. `a = agent(...)` then `await a(prompt, schema)` runs one turn in a conversation kept across calls. |
|
||||
| `parallel(items, fn)` | Promise that calls `fn(item)` for each item and awaits all results concurrently; results are in item order. If one fails, the rest are cancelled. |
|
||||
| `pipeline(items, fn)` | Promise that calls and awaits `fn(item)` one item at a time; results are in item order. |
|
||||
| `trajectory(last=None, types=None, tools=None, min_index=None, max_index=None)` | `await trajectory()` returns steps before this `run_workflow` call started, oldest first. `min_index` and `max_index` bound `step.index` (inclusive); `types` and `tools` filter by step type or tool name; `last` keeps the last N matching steps. |
|
||||
|
||||
Arguments:
|
||||
|
||||
- `type_name`: the agent type to run. `"self"` uses the current agent's
|
||||
configuration; any available custom agent name also works.
|
||||
- `workspace`: `"inherit"` (the current workspace), `"branch"` (a new isolated
|
||||
clone, for agents that edit code in parallel), or `"share"` (a new workspace
|
||||
that shares the underlying repository). Other values are errors.
|
||||
- `schema` (required): a JSON schema (dict or string) for the agent's result.
|
||||
The agent returns the result by calling its `finish` tool, which checks it
|
||||
against the schema, and `await agent(...)` returns the parsed value. An
|
||||
agent that ends without calling `finish` fails the workflow. Use
|
||||
`{"type": "string"}` for a free-form answer.
|
||||
- `role`: an optional short title for the agent's card, such as
|
||||
`"Security reviewer"`.
|
||||
- `model`: the agent's model tier: `"inherit"` (default, your model),
|
||||
`"flash_lite"`, `"flash"`, or `"pro"`. Use a lighter tier for simple,
|
||||
high-fan-out work.
|
||||
- `fn`: usually a `lambda` that returns `agent(...)`, or an `async def`
|
||||
helper that awaits several agents. It must return something awaitable:
|
||||
an `agent()` or a call on one, a nested `parallel()` / `pipeline()`, or
|
||||
an `async def` call. Build per-item prompts and roles with f-strings.
|
||||
|
||||
Awaiting the same agent twice runs it once and returns the same result. An
|
||||
`agent()` that is never awaited or called never runs, so always `await` it, or
|
||||
pass it to `parallel` / `pipeline` and await that.
|
||||
|
||||
The workflow step shows one card per agent, in the order agents start, titled
|
||||
with its `role`, or else the first line of its prompt, so set a role or start
|
||||
each prompt with a short line that names the job.
|
||||
|
||||
## Agents that keep their context
|
||||
|
||||
When one agent should do several related turns, such as a reviewer that checks
|
||||
the fixes for the bugs it found, call it instead of awaiting it. Each
|
||||
`a(prompt, schema)` is lazy like an awaited `agent()` and returns that turn's
|
||||
`finish` result; the agent's own `prompt`, if any, is its standing instructions
|
||||
and leads the first turn. `schema` on a call defaults to the agent's. Turns on
|
||||
one agent run one at a time, in the order they were started. A failed turn
|
||||
raises, but the agent stays usable. An agent is either awaited or called, not
|
||||
both. `del a` ends the agent, unless something else, such as a lambda, still
|
||||
references it; every agent ends when the workflow ends.
|
||||
|
||||
```python
|
||||
reviewer = agent("You review Go code for correctness.", role="Reviewer")
|
||||
bugs = await reviewer("List the bugs in foo.go.", {"type": "array", "items": {"type": "string"}})
|
||||
fixes = await parallel(bugs, lambda b: agent(f"Fix: {b}", {"type": "string"}))
|
||||
ok = await reviewer(f"Fixes made: {fixes}. Are all your bugs fixed?", {"type": "boolean"})
|
||||
del reviewer
|
||||
```
|
||||
|
||||
## Calling tools from the script
|
||||
|
||||
Where the `run_workflow` tool description lists tools for `call_tool`, the
|
||||
script can call them directly:
|
||||
|
||||
- `call_tool(name, **args)` returns a promise like `agent()` does. Awaiting it
|
||||
runs the tool with the arguments you would pass to it directly and returns
|
||||
the tool's output as a `str`.
|
||||
- It raises `ToolError` (with `.tool` and `.message`) if the tool fails or
|
||||
the call is denied. `.denied` is `True` when a pre-tool hook or the
|
||||
permission check rejected the call before the tool ran, so a script can
|
||||
skip denied calls and still fail on real errors.
|
||||
- The user cannot be asked anything from a workflow: a call that needs user
|
||||
approval that has not already been granted is denied.
|
||||
- Tool outputs are not shown to you unless the script logs or prints them.
|
||||
|
||||
## Reading earlier conversation steps
|
||||
|
||||
Pass inputs you already have in `Args` (or inline in the script). Use
|
||||
`await trajectory(...)` when the script needs to inspect steps from earlier in
|
||||
this conversation—such as mining a failed `run_command` output without
|
||||
rerunning it—and pass only the relevant slice into child `agent()` prompts.
|
||||
|
||||
Each returned `Step` is a `dict` that also supports attribute access (missing
|
||||
fields return `None` as attributes):
|
||||
|
||||
- `index` (`int`): 0-based step index.
|
||||
- `type` (`str`): step type, e.g. `"USER_INPUT"`, `"PLANNER_RESPONSE"`,
|
||||
`"SYSTEM_MESSAGE"`, or `"GENERIC"` (tool calls).
|
||||
- `status` (`str`): e.g. `"DONE"`, `"ERROR"`, or `"CLEARED"`.
|
||||
- Message steps set `text` (`str`); tool steps set `tool` (`str`), `args`
|
||||
(parsed `dict`), and `output` (`str`, truncated at 200k characters).
|
||||
|
||||
```python
|
||||
steps = await trajectory(tools=["run_command"], last=20)
|
||||
errors = [s.output for s in steps if s.status == "ERROR" and s.output]
|
||||
log(f"Found {len(errors)} failed command(s)")
|
||||
```
|
||||
|
||||
`trajectory()` only returns steps before the `run_workflow` call started (steps
|
||||
added while the workflow runs in the background are not included). Older tool
|
||||
steps evicted from memory have `status == "CLEARED"` and `output == None`; read
|
||||
the conversation's `transcript.jsonl` / `transcript_full.jsonl` when you need
|
||||
cleared tool outputs or steps added after the workflow started.
|
||||
|
||||
## Behavior to know
|
||||
|
||||
- Workflow agents are main agents, not subagents. They are hidden from the
|
||||
conversation list and reachable from the workflow step. An awaited agent
|
||||
is single-use; a called agent lasts until deleted or the workflow ends.
|
||||
- `await agent(...)` returns when the agent's run ends, with the result it
|
||||
passed to `finish`.
|
||||
- If one agent in `parallel` fails, the whole call fails and the other agents
|
||||
in it are cancelled. Stopping the parent conversation stops all running
|
||||
workflow agents.
|
||||
- Agents do not see the script or each other. Put all the context an agent
|
||||
needs in its prompt, and ask for a short, well-defined output.
|
||||
|
||||
## Example
|
||||
|
||||
Fan out over a list that an agent produces:
|
||||
|
||||
```python
|
||||
phase("Discover")
|
||||
files = await agent(
|
||||
"List the Go files under pkg/foo that call Bar(). Paths only.",
|
||||
schema={"type": "array", "items": {"type": "string"}},
|
||||
)
|
||||
|
||||
phase("Review")
|
||||
reviews = await parallel(files, lambda f: agent(
|
||||
f"Review {f} for misuse of Bar(). Reply in 3 bullets or 'OK'.",
|
||||
schema={"type": "string"},
|
||||
role=f"Review {f}",
|
||||
))
|
||||
for r in reviews:
|
||||
log(r)
|
||||
```
|
||||
Reference in New Issue
Block a user