mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:56:27 +00:00
90 lines
3.9 KiB
JavaScript
90 lines
3.9 KiB
JavaScript
const { pooling: poolingConfig } = require("../../../knexfile");
|
|
const { withTransactionTimeZone } = require("../../../infrastructure/transaction-time");
|
|
const dbPooling = require("knex")(withTransactionTimeZone(poolingConfig));
|
|
const { observePool } = require("../../../infrastructure/database/pool-metrics");
|
|
observePool("pooling", dbPooling.client.pool);
|
|
const knex = require("../../../infrastructure/database/knex");
|
|
const moment = require("moment");
|
|
|
|
const BATCH_SIZE = 500;
|
|
const validateLock = 3824001;
|
|
const syncLock = 3824002;
|
|
|
|
const cardColumns = ["c_card_number", "c_idm"];
|
|
const cardKey = (row) => JSON.stringify(cardColumns.map((column) => row[column]));
|
|
|
|
async function insertRawCards(cards) {
|
|
// Satu request insert tetap atomik meski SQL dikirim dalam potongan kecil.
|
|
await dbPooling.transaction(async (trx) => {
|
|
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);
|
|
}
|
|
});
|
|
}
|
|
|
|
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));
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
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 };
|
|
});
|
|
}
|
|
|
|
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));
|
|
});
|
|
|
|
function closePool() {
|
|
return dbPooling.destroy();
|
|
}
|
|
|
|
module.exports = { insertRawCards, validateBatch, syncBatch, closePool };
|