diff --git a/constants/index.ts b/constants/index.ts index 4565777b..8d153d72 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -306,6 +306,16 @@ export const TRIGGER_LOG_BATCH_SIZE = 200 export const PRICES_CONNECTION_BATCH_SIZE = 1_000 // interactive $transaction timeout in ms (for batched delete + createMany of prices) export const PRICES_CONNECTION_TIMEOUT = 30_000 +// Txs whose price links are replaced per DB transaction (2 links per tx). Small +// chunks keep each transaction well under PRICES_CONNECTION_TIMEOUT and mean a +// failure only loses that chunk, not the whole run. +export const PRICES_CONNECTION_TX_CHUNK_SIZE = 500 +// Unpriced txs loaded into memory per page by connectAllTransactionsToPrices. +export const UNPRICED_TXS_PAGE_SIZE = 5_000 +// How often the jobs process retries linking prices for txs that still have none. +export const PRICE_LINKING_REPEAT_DELAY = 60 * 60 * 1000 +// Wait before retrying a sync insert whose DB transaction timed out. +export const SYNC_INSERT_RETRY_DELAY = 2_000 export const CLIENT_PAYMENT_EXPIRATION_TIME = (7) * (24 * 60 * 60 * 1000) // (number of days) * (24 * 60 * 60 * 1000) diff --git a/jobs/initJobs.ts b/jobs/initJobs.ts index 3d7a0c1d..9997b511 100644 --- a/jobs/initJobs.ts +++ b/jobs/initJobs.ts @@ -1,8 +1,8 @@ -import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY } from 'constants/index' +import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY, PRICE_LINKING_REPEAT_DELAY } from 'constants/index' import { Queue } from 'bullmq' import { redisBullMQ } from 'redis/clientInstance' import EventEmitter from 'events' -import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker } from './workers' +import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker, linkUnpricedTransactionsWorker } from './workers' EventEmitter.defaultMaxListeners = 20 @@ -11,10 +11,12 @@ const main = async (): Promise => { const pricesQueue = new Queue('pricesSync', { connection: redisBullMQ }) const blockchainQueue = new Queue('blockchainSync', { connection: redisBullMQ }) const cleanupQueue = new Queue('clientPaymentCleanup', { connection: redisBullMQ }) + const priceLinkingQueue = new Queue('priceLinking', { connection: redisBullMQ }) await pricesQueue.obliterate({ force: true }) await blockchainQueue.obliterate({ force: true }) await cleanupQueue.obliterate({ force: true }) + await priceLinkingQueue.obliterate({ force: true }) // Start blockchain sync first; current prices job starts only after it completes await blockchainQueue.add('syncBlockchainAndPrices', @@ -54,6 +56,23 @@ const main = async (): Promise => { ) await cleanupClientPaymentsWorker(cleanupQueue.name) + + // Runs right away and then periodically, independent of the blockchain sync, + // so unpriced txs get linked even if that sync is interrupted before its end. + await priceLinkingQueue.add( + 'linkUnpricedTransactions', + {}, + { + jobId: 'linkUnpricedTransactions', + removeOnComplete: true, + removeOnFail: true, + repeat: { + every: PRICE_LINKING_REPEAT_DELAY, + immediately: true + } + } + ) + await linkUnpricedTransactionsWorker(priceLinkingQueue.name) } void main() diff --git a/jobs/workers.ts b/jobs/workers.ts index 25ec1a71..cb576304 100644 --- a/jobs/workers.ts +++ b/jobs/workers.ts @@ -143,6 +143,26 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet }) } +// Links txs that still have no prices (e.g. a failed per-batch link during sync, +// or a startup sync that was interrupted before finishing). +export const linkUnpricedTransactionsWorker = async (queueName: string): Promise => { + const worker = new Worker( + queueName, + async (job) => { + console.log(`[PRICES] job ${job.id as string}: linking txs without prices...`) + await connectAllTransactionsToPrices() + }, + { + connection: redisBullMQ, + lockDuration: DEFAULT_WORKER_LOCK_DURATION + } + ) + + worker.on('failed', (job, err) => { + console.error(`[PRICES] job ${job?.id as string}: linking txs without prices FAILED — ${err.message}`) + }) +} + export const cleanupClientPaymentsWorker = async (queueName: string): Promise => { const worker = new Worker( queueName, diff --git a/redis/clientInstance.ts b/redis/clientInstance.ts index 148f11e8..64a19bdc 100755 --- a/redis/clientInstance.ts +++ b/redis/clientInstance.ts @@ -3,10 +3,30 @@ import IORedis, { ScanStream } from 'ioredis' import { ScanStreamOptions } from 'ioredis/built/types' class RedisMocked { + private readonly sets = new Map>() + async get (_: string): Promise { return null } + async sadd (key: string, ...members: string[]): Promise { + const set = this.sets.get(key) ?? new Set() + const before = set.size + members.forEach(m => set.add(m)) + this.sets.set(key, set) + return set.size - before + } + + async smembers (key: string): Promise { + return [...(this.sets.get(key) ?? [])] + } + + async srem (key: string, ...members: string[]): Promise { + const set = this.sets.get(key) + if (set === undefined) return 0 + return members.filter(m => set.delete(m)).length + } + async del (key: string, data: any): Promise { } diff --git a/services/chronikService.ts b/services/chronikService.ts index 1f77f7a7..fa6223ef 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -16,7 +16,9 @@ import { upsertTransaction, getSimplifiedTransactions, getSimplifiedTrasaction, - connectTransactionsToPricesForAddresses + connectTransactionsToPricesForAddresses, + connectTransactionsListToPrices, + invalidateCachesForAddresses } from './transactionService' import { CacheSet } from 'redis/index' import { @@ -1107,6 +1109,31 @@ export class ChronikBlockchainClient { `${commitTuples.length}` ) + // Link prices batch by batch instead of only at the end of the sync job, so + // an interrupted sync (restart, deploy) doesn't leave everything unpriced. + // A failure here is not fatal: connectAllTransactionsToPrices retries later. + if (syncResult.inserted.length > 0) { + try { + const linkedIds = new Set(await connectTransactionsListToPrices( + syncResult.inserted.map(t => ({ ...t, address: { networkId: this.networkId } })), + { skipUnlink: true } + )) + // The bulk path doesn't add txs to cached payments, so drop the caches of + // addresses whose new txs are now priced instead of waiting for the end of + // the sync, which an interrupted sync never reaches. Txs left unpriced are + // invalidated by connectAllTransactionsToPrices once it links them. + const addressStringById = new Map(commitTuples.map(t => [t.row.addressId, t.addressString])) + const linkedAddresses = [...new Set( + syncResult.inserted.filter(t => linkedIds.has(t.id)).map(t => addressStringById.get(t.addressId)) + )].filter((a): a is string => a !== undefined) + if (linkedAddresses.length > 0) { + await invalidateCachesForAddresses(linkedAddresses) + } + } catch (err: any) { + console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to link prices for ${syncResult.inserted.length} synced txs: ${err.message as string}`) + } + } + const createdForProd = syncResult.inserted.filter(t => productionAddressesIds.includes(t.addressId) ) diff --git a/services/transactionService.ts b/services/transactionService.ts index 90d54865..5e5a56f3 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -1,15 +1,17 @@ import prisma from 'prisma-local/clientInstance' import { Prisma, Transaction } from '@prisma/client' -import { RESPONSE_MESSAGES, USD_QUOTE_ID, CAD_QUOTE_ID, N_OF_QUOTES, UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT, SupportedQuotesType, NETWORK_IDS, PRICES_CONNECTION_BATCH_SIZE, PRICES_CONNECTION_TIMEOUT, HUMAN_READABLE_DATE_FORMAT } from 'constants/index' +import { RESPONSE_MESSAGES, USD_QUOTE_ID, CAD_QUOTE_ID, N_OF_QUOTES, UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT, SupportedQuotesType, NETWORK_IDS, PRICES_CONNECTION_BATCH_SIZE, PRICES_CONNECTION_TIMEOUT, PRICES_CONNECTION_TX_CHUNK_SIZE, UNPRICED_TXS_PAGE_SIZE, SYNC_INSERT_RETRY_DELAY, HUMAN_READABLE_DATE_FORMAT } from 'constants/index' import { fetchAddressBySubstring, fetchAddressById, fetchAddressesByPaybuttonId } from 'services/addressService' import { AllPrices, QuoteValues, fetchAndStoreMissingPrices, fetchPricesForNetworkAndTimestamp, flattenTimestamp } from 'services/priceService' import _ from 'lodash' import { CacheSet } from 'redis/index' +import { redis } from 'redis/clientInstance' import { SimplifiedTransaction } from 'ws-service/types' import { OpReturnData, parseAddress } from 'utils/validators' import { generatePaymentFromTxWithInvoices } from 'redis/paymentCache' import { ButtonDisplayData, Payment } from 'redis/types' import moment from 'moment-timezone' +import { v4 as uuidv4 } from 'uuid' export function getTransactionValue (transaction: TransactionWithPrices | TransactionsWithPaybuttonsAndPrices | SimplifiedTransaction): QuoteValues { const ret: QuoteValues = { @@ -113,12 +115,6 @@ const includeNetwork = { } } -const transactionWithNetwork = Prisma.validator()( - { include: includeNetwork } -) - -type TransactionWithNetwork = Prisma.TransactionGetPayload - const transactionWithAddressAndPrices = Prisma.validator()( { include: includeAddressAndPrices } ) @@ -447,29 +443,30 @@ export async function upsertTransaction ( } } -function buildPriceTxConnectionInput (tx: Transaction, allPrices: AllPrices): Prisma.PricesOnTransactionsCreateManyInput[] { +function buildPriceTxConnectionInput (tx: Pick, allPrices: AllPrices): Prisma.PricesOnTransactionsCreateManyInput[] { return [ { transactionId: tx.id, priceId: allPrices.usd.id }, { transactionId: tx.id, priceId: allPrices.cad.id } ] } -async function deletePriceTxConnectionsInChunks ( - client: Prisma.TransactionClient, - transactionIds: string[] -): Promise { - let pricesUnlinkedCount = 0 - console.log( - `[PRICES] Disconnecting existing price links for ${transactionIds.length} txs...` - ) - for (let i = 0; i < transactionIds.length; i += PRICES_CONNECTION_BATCH_SIZE) { - const slice = transactionIds.slice(i, i + PRICES_CONNECTION_BATCH_SIZE) - const result = await client.pricesOnTransactions.deleteMany({ - where: { transactionId: { in: slice } } - }) - pricesUnlinkedCount += result.count +// Txs whose link replacement failed. Their old links stay (rolled back) and may +// be for the wrong day, so neither the no-prices nor the irregular-count pass of +// connectAllTransactionsToPrices would find them. Kept in Redis because the +// failure can happen in the app process while the retry runs in the jobs process. +const PRICE_RELINK_PENDING_KEY = 'prices:relinkPending' + +async function recordPendingRelinks (txIds: string[]): Promise { + try { + await redis.sadd(PRICE_RELINK_PENDING_KEY, ...txIds) + } catch (err: any) { + console.error(`[PRICES] Failed to record ${txIds.length} txs for relinking: ${err.message as string}`) } - console.log(`[PRICES] Disconnected ${pricesUnlinkedCount} price links.`) +} + +/** The fields connectTransactionsListToPrices needs from a tx. */ +export type PriceLinkableTransaction = Pick & { + address: { networkId: number } } async function createPriceTxConnectionInChunks ( @@ -532,12 +529,24 @@ async function fetchStoredPricesForNetworkAndTimestamps ( return complete } -export async function connectTransactionsListToPrices ( - txList: TransactionWithNetwork[] -): Promise { - if (txList.length === 0) return +export interface ConnectPricesOptions { + // Set when every tx is known to have no price links yet (e.g. just inserted, + // or selected by `prices: none`), so the per-chunk unlink can be skipped. + skipUnlink?: boolean +} - console.log(`[PRICES] Preparing to connect ${txList.length} txs to prices...`) +/** + * Link each tx to the USD and CAD prices of its day, replacing any existing links. + * Writes in chunks of PRICES_CONNECTION_TX_CHUNK_SIZE txs, each in its own short + * DB transaction: a chunk that fails is logged and skipped (its txs stay unpriced + * for the next run to retry) instead of rolling back the whole list. + * Returns the ids of the txs that were linked. + */ +export async function connectTransactionsListToPrices ( + txList: PriceLinkableTransaction[], + { skipUnlink = false }: ConnectPricesOptions = {} +): Promise { + if (txList.length === 0) return [] // collect UNIQUE (networkId, timestamp) pairs const networkIdToTimestamps = new Map>() @@ -551,11 +560,9 @@ export async function connectTransactionsListToPrices ( // ---- efficient fetch ---- const priceByNetworkTs = new Map() - let pairs = 0 for (const [networkId, timestamps] of networkIdToTimestamps.entries()) { const tsArray = [...timestamps] - pairs += tsArray.length let storedPrices = await fetchStoredPricesForNetworkAndTimestamps(networkId, tsArray) @@ -583,61 +590,186 @@ export async function connectTransactionsListToPrices ( } } - console.log(`[PRICES] Loaded prices for ${pairs} (network,timestamp) pairs.`) - - // Build all join rows (2 per tx: USD + CAD) - const rows: Prisma.PricesOnTransactionsCreateManyInput[] = [] - const txIdsToConnect: string[] = [] + const txsToConnect: Array<{ id: string, rows: Prisma.PricesOnTransactionsCreateManyInput[] }> = [] for (const t of txList) { - const ts = flattenTimestamp(t.timestamp) - const allPrices = priceByNetworkTs.get(`${t.address.networkId}:${ts}`) + const allPrices = priceByNetworkTs.get(`${t.address.networkId}:${flattenTimestamp(t.timestamp)}`) if (allPrices == null) { continue } - rows.push(...buildPriceTxConnectionInput(t, allPrices)) - txIdsToConnect.push(t.id) + txsToConnect.push({ id: t.id, rows: buildPriceTxConnectionInput(t, allPrices) }) } - - if (txIdsToConnect.length < txList.length) { - console.warn(`[PRICES] Skipped ${txList.length - txIdsToConnect.length} txs due to missing price data.`) + const skippedNoPrice = txList.length - txsToConnect.length + + const linkedIds: string[] = [] + let failedChunks = 0 + for (let i = 0; i < txsToConnect.length; i += PRICES_CONNECTION_TX_CHUNK_SIZE) { + const chunk = txsToConnect.slice(i, i + PRICES_CONNECTION_TX_CHUNK_SIZE) + const ids = chunk.map(c => c.id) + const rows = chunk.flatMap(c => c.rows) + try { + await prisma.$transaction( + async (tx) => { + if (!skipUnlink) { + await tx.pricesOnTransactions.deleteMany({ where: { transactionId: { in: ids } } }) + } + await createPriceTxConnectionInChunks(tx, rows) + }, + { timeout: PRICES_CONNECTION_TIMEOUT } + ) + linkedIds.push(...ids) + } catch (err: any) { + failedChunks++ + console.error(`[PRICES] Failed to link prices for a chunk of ${chunk.length} txs (first: ${ids[0]}): ${err.message as string}`) + // Txs selected as unlinked are found again by the no-prices pass; replaced + // links are not, so record them for connectAllTransactionsToPrices to retry. + if (!skipUnlink) { + await recordPendingRelinks(ids) + } + } } - if (txIdsToConnect.length === 0) { - console.warn('[PRICES] No txs to connect after filtering — all had missing prices.') - return + const failedTxs = txsToConnect.length - linkedIds.length + if (skippedNoPrice > 0 || failedChunks > 0 || txList.length >= PRICES_CONNECTION_TX_CHUNK_SIZE) { + console.log( + `[PRICES] Linked ${linkedIds.length}/${txList.length} txs to prices` + + (skippedNoPrice > 0 ? `, ${skippedNoPrice} skipped (no price data)` : '') + + (failedChunks > 0 ? `, ${failedTxs} failed in ${failedChunks} chunks` : '') + + '.' + ) } + return linkedIds +} - console.log(`[PRICES] Built ${rows.length} price links (2 per tx).`) +let connectAllTransactionsToPricesRun: Promise | undefined - await prisma.$transaction( - async (tx) => { - await deletePriceTxConnectionsInChunks(tx, txIdsToConnect) - await createPriceTxConnectionInChunks(tx, rows) - }, - { timeout: PRICES_CONNECTION_TIMEOUT } - ) +// Addresses with newly priced txs whose cache invalidation hasn't succeeded yet. +// Once linked, those txs aren't found by later runs, so the addresses must not be +// dropped: they're retried on the next run. Kept in memory because this only runs +// in the jobs process and a failed invalidation usually means Redis is unreachable. +const addressesPendingCacheInvalidation = new Set() + +/** + * Drop the payment, balance and dashboard caches of these addresses. Addresses + * whose invalidation fails stay queued and are retried by the next call (or the + * next connectAllTransactionsToPrices run in this process). + */ +export async function invalidateCachesForAddresses (addresses: string[]): Promise { + addresses.forEach(a => addressesPendingCacheInvalidation.add(a)) + await flushPendingCacheInvalidations() } +async function flushPendingCacheInvalidations (): Promise { + if (addressesPendingCacheInvalidation.size === 0) return + const addresses = [...addressesPendingCacheInvalidation] + try { + await CacheSet.addressesSynced(addresses) + addresses.forEach(a => addressesPendingCacheInvalidation.delete(a)) + console.log(`[CACHE] Invalidated caches for ${addresses.length} addresses with newly priced txs.`) + } catch (err: any) { + console.error(`[PRICES] Failed to invalidate caches after linking prices, will retry on the next run: ${err.message as string}`) + } +} + +/** + * Link every tx that has no prices, or an incomplete set, to its day's prices. + * Unpriced txs are paged (UNPRICED_TXS_PAGE_SIZE at a time) rather than loaded + * all at once. Runs from the startup sync job and from a repeating job; a call + * made while a run is in progress in this process waits for that run instead of + * starting another one. + */ export async function connectAllTransactionsToPrices (): Promise { + if (connectAllTransactionsToPricesRun !== undefined) { + console.log('[PRICES] Linking txs to prices is already running, waiting for it.') + return await connectAllTransactionsToPricesRun + } + connectAllTransactionsToPricesRun = runConnectAllTransactionsToPrices() + try { + await connectAllTransactionsToPricesRun + } finally { + connectAllTransactionsToPricesRun = undefined + } +} + +async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started connecting txs to prices.') - const noPricesTxs = await fetchAllTransactionsWithNoPrices() - console.log(`[PRICES] Found ${noPricesTxs.length} txs with no prices.`) - const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() - console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) - const txs = [ - ...noPricesTxs, - ...wrongNumberOfPricesTxs - ] - console.log('[PRICES] Connecting txs to prices...') - void await connectTransactionsListToPrices(txs) - console.log('[PRICES] Finished connecting txs to prices.') + // Addresses whose cached payments were built while these txs were unpriced + // (and so left them out); their caches are dropped once the txs are linked. + const trackLinked = (txs: Array<{ id: string, address: { address: string } }>, linkedIds: string[]): void => { + const linked = new Set(linkedIds) + for (const t of txs) { + if (linked.has(t.id)) addressesPendingCacheInvalidation.add(t.address.address) + } + } + const priceLinkableSelect = { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } as const + + try { + let found = 0 + let linked = 0 + let cursor: string | undefined + while (true) { + const page = await prisma.transaction.findMany({ + where: { + prices: { none: {} }, + ...(cursor !== undefined ? { id: { gt: cursor } } : {}) + }, + orderBy: { id: 'asc' }, + take: UNPRICED_TXS_PAGE_SIZE, + select: priceLinkableSelect + }) + if (page.length === 0) break + cursor = page[page.length - 1].id + found += page.length + const linkedIds = await connectTransactionsListToPrices(page, { skipUnlink: true }) + linked += linkedIds.length + trackLinked(page, linkedIds) + console.log(`[PRICES] Txs with no prices: ${linked}/${found} linked so far.`) + } + console.log(`[PRICES] Found ${found} txs with no prices, linked ${linked}.`) + + const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() + console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) + const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + trackLinked(wrongNumberOfPricesTxs, relinkedIds) + + // Txs whose link replacement failed earlier (possibly in another process). + let pendingRelinked = 0 + try { + const pendingIds = await redis.smembers(PRICE_RELINK_PENDING_KEY) + if (pendingIds.length > 0) { + const pendingTxs = await prisma.transaction.findMany({ + where: { id: { in: pendingIds } }, + select: priceLinkableSelect + }) + const pendingLinkedIds = await connectTransactionsListToPrices(pendingTxs) + trackLinked(pendingTxs, pendingLinkedIds) + pendingRelinked = pendingLinkedIds.length + // Done: relinked now, or deleted since. Failures stay recorded for the next run. + const existing = new Set(pendingTxs.map(t => t.id)) + const relinked = new Set(pendingLinkedIds) + const done = pendingIds.filter(id => relinked.has(id) || !existing.has(id)) + if (done.length > 0) { + await redis.srem(PRICE_RELINK_PENDING_KEY, ...done) + } + console.log(`[PRICES] Relinked ${pendingRelinked}/${pendingIds.length} txs whose earlier link replacement failed.`) + } + } catch (err: any) { + console.error(`[PRICES] Failed to relink txs recorded as pending: ${err.message as string}`) + } + + console.log( + `[PRICES] Finished connecting txs to prices (${linked} unpriced, ${relinkedIds.length} irregular ` + + `and ${pendingRelinked} pending txs linked).` + ) + } finally { + // Also on failure: txs linked before it must still get their caches dropped. + await flushPendingCacheInvalidations() + } } /** * Link prices for the given addresses' txs that have none (or an incomplete set). - * The bulk sync path (createManyTransactionsForSync) leaves txs unpriced; the - * sync job fixes that globally with connectAllTransactionsToPrices, but on-demand - * syncs (syncAndSubscribeAddresses) must do it for their own addresses. + * Catches txs from an on-demand sync (syncAndSubscribeAddresses) whose per-batch + * price linking failed, without waiting for the repeating linking job. */ export async function connectTransactionsToPricesForAddresses (addressIds: string[]): Promise { if (addressIds.length === 0) return @@ -663,6 +795,24 @@ export async function connectTransactionsToPricesForAddresses (addressIds: strin await connectTransactionsListToPrices([...noPricesTxs, ...irregularTxs]) } +// Prisma's error code for an interactive transaction that expired or was closed. +const PRISMA_TRANSACTION_API_ERROR = 'P2028' + +const isTransactionTimeoutError = (err: unknown): boolean => + err instanceof Prisma.PrismaClientKnownRequestError && err.code === PRISMA_TRANSACTION_API_ERROR + +/** Runs `fn`; if it fails with a transaction timeout, waits and runs it once more. */ +export async function retryOnTransactionTimeout (fn: () => Promise): Promise { + try { + return await fn() + } catch (err) { + if (!isTransactionTimeoutError(err)) throw err + console.warn(`[TRANSACTIONS] DB transaction timed out, retrying once in ${SYNC_INSERT_RETRY_DELAY}ms...`) + await new Promise(resolve => setTimeout(resolve, SYNC_INSERT_RETRY_DELAY)) + return await fn() + } +} + interface ExistingTxSnapshot { confirmed: boolean timestamp: number @@ -845,20 +995,24 @@ async function persistManyTransactionRows ( let updatedCount = 0 if (newTxs.length > 0) { - await prisma.$transaction( + // Ids are generated here so only rows this call created are reported as + // inserted: if a concurrent sync inserted the same (hash, addressId) first, + // skipDuplicates keeps that row (with its own id) and it is left out, so its + // price linking, seed-file append and triggers aren't run twice. + const newTxsWithIds = newTxs.map(row => ({ ...row, id: uuidv4() })) + const newIds = newTxsWithIds.map(row => row.id) + // Retried once if the DB transaction times out (e.g. MySQL briefly stalled + // under load), instead of dropping the whole batch. Safe to repeat: the + // timed-out attempt was rolled back and the inserts skip duplicates. + const createdTxs = await retryOnTransactionTimeout(async () => await prisma.$transaction( async (tx) => { await tx.transaction.createMany({ - data: newTxs, + data: newTxsWithIds, skipDuplicates: true }) const createdTxs = await tx.transaction.findMany({ - where: { - OR: newTxs.map(row => ({ - hash: row.hash, - addressId: row.addressId - })) - }, + where: { id: { in: newIds } }, select: syncPersistedTxSelect }) @@ -902,14 +1056,13 @@ async function persistManyTransactionRows ( }) } - for (const createdTx of createdTxs) { - inserted.push(createdTx) - } + return createdTxs }, { timeout: UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT } - ) + )) + inserted.push(...createdTxs) } if (toUpdate.length > 0) { @@ -957,8 +1110,9 @@ async function persistManyTransactionRows ( } /** - * Bulk sync path: persist txs + inputs only. Prices, Redis cache, and paybutton - * graphs are deferred to connectAllTransactionsToPrices after the sync job. + * Bulk sync path: persist txs + inputs only. The caller (commitTransactionsBatch) + * links prices per batch; the Redis cache is invalidated after the sync, and + * connectAllTransactionsToPrices retries any txs left unpriced. */ export async function createManyTransactionsForSync ( transactionsData: Prisma.TransactionUncheckedCreateInput[] @@ -1039,19 +1193,7 @@ export async function markTransactionsOrphaned (hash: string): Promise { }) } -async function fetchAllTransactionsWithNoPrices (): Promise { - const x = await prisma.transaction.findMany({ - where: { - prices: { - none: {} - } - }, - include: includeNetwork - }) - return x -} - -export async function fetchAllTransactionsWithIrregularPrices (): Promise { +export async function fetchAllTransactionsWithIrregularPrices (): Promise> { const grouped = await prisma.pricesOnTransactions.groupBy({ by: ['transactionId'], _count: { transactionId: true }, @@ -1062,7 +1204,7 @@ export async function fetchAllTransactionsWithIrregularPrices (): Promise ({ getSimplifiedTransactions: jest.fn(), getSimplifiedTrasaction: jest.fn(), connectAllTransactionsToPrices: jest.fn(), - connectTransactionsToPricesForAddresses: jest.fn() + connectTransactionsToPricesForAddresses: jest.fn(), + connectTransactionsListToPrices: jest.fn(), + invalidateCachesForAddresses: jest.fn() })) jest.mock('../../redis/index', () => ({ @@ -1708,3 +1711,71 @@ describe('chronik WebSocket reconnection', () => { expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16) }) }) + +describe('commitTransactionsBatch price linking', () => { + const inserted = [{ + id: 'tx-1', + hash: 'hash-1', + addressId: 'addr-1', + amount: new Prisma.Decimal(1), + timestamp: 1700000000, + confirmed: true + }] + const commitTuples = [{ + row: { hash: 'hash-1', addressId: 'addr-1', timestamp: 1700000000, amount: 1 }, + raw: {}, + addressString: 'ecash:addr-1' + }] + + beforeEach(() => { + process.env.WS_AUTH_KEY = 'test-auth-key' + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted }) + jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('links prices for the txs it just inserted, with the client network', async () => { + const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(['tx-1']) + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(link).toHaveBeenCalledWith( + [{ ...inserted[0], address: { networkId: 1 } }], + { skipUnlink: true } + ) + }) + + it('invalidates the caches of addresses whose new txs got linked', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(['tx-1']) + const invalidate = (invalidateCachesForAddresses as jest.Mock).mockReset() + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-1']) + }) + + it('does not invalidate caches when no new tx could be linked', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue([]) + const invalidate = (invalidateCachesForAddresses as jest.Mock).mockReset() + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(invalidate).not.toHaveBeenCalled() + }) + + it('still commits the batch when price linking fails', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockRejectedValue(new Error('price API down')) + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + const client = new ChronikBlockchainClient('ecash') + + await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toBeUndefined() + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down')) + }) +}) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index df320dac..fd765d55 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -9,6 +9,13 @@ import * as addressService from 'services/addressService' import { RESPONSE_MESSAGES } from 'constants/index' import moment from 'moment-timezone' import * as priceService from 'services/priceService' +import { redis } from 'redis/clientInstance' + +const PRICE_RELINK_PENDING_KEY = 'prices:relinkPending' +const clearPendingRelinks = async (): Promise => { + const pending = await redis.smembers(PRICE_RELINK_PENDING_KEY) + if (pending.length > 0) await redis.srem(PRICE_RELINK_PENDING_KEY, ...pending) +} const includePrices = { prices: { @@ -595,3 +602,282 @@ describe('connectTransactionsListToPrices', () => { expect(prismaMock.pricesOnTransactions.createMany).not.toHaveBeenCalled() }) }) + +describe('connectTransactionsListToPrices chunking', () => { + const dayTs = moment.utc('2026-08-02').unix() + const usd = { ...mockedUSDPriceOnTransaction.price, id: 11, timestamp: dayTs, networkId: 1 } + const cad = { ...mockedCADPriceOnTransaction.price, id: 12, timestamp: dayTs, networkId: 1 } + const makeTxs = (n: number): any[] => Array.from({ length: n }, (_, i) => ({ + id: `tx-${i}`, timestamp: dayTs + 60, address: { networkId: 1 } + })) + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.price.findMany = prismaMock.price.findMany + prisma.pricesOnTransactions.deleteMany = prismaMock.pricesOnTransactions.deleteMany + prisma.pricesOnTransactions.createMany = prismaMock.pricesOnTransactions.createMany + prisma.pricesOnTransactions.groupBy = prismaMock.pricesOnTransactions.groupBy + prisma.transaction.findMany = prismaMock.transaction.findMany + prismaMock.price.findMany.mockResolvedValue([usd, cad]) + prismaMock.pricesOnTransactions.deleteMany.mockResolvedValue({ count: 0 }) + prismaMock.pricesOnTransactions.createMany.mockResolvedValue({ count: 0 }) + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + }) + + it('writes each chunk of txs in its own DB transaction', async () => { + const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) + + expect(linked).toHaveLength(501) + expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) + const createManyCalls = prismaMock.pricesOnTransactions.createMany.mock.calls as any[] + expect(createManyCalls[0][0].data).toHaveLength(1000) + expect(createManyCalls[1][0].data).toHaveLength(2) + }) + + it('keeps linking the remaining chunks when one chunk fails', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction + .mockRejectedValueOnce(new Error('Transaction already closed')) + .mockImplementation(async (fn: any) => fn(prismaMock)) + + const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) + + expect(linked).toEqual(['tx-500']) + expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Transaction already closed')) + errorSpy.mockRestore() + }) + + it('only unlinks existing prices when skipUnlink is not set', async () => { + await transactionService.connectTransactionsListToPrices(makeTxs(2), { skipUnlink: true }) + expect(prismaMock.pricesOnTransactions.deleteMany).not.toHaveBeenCalled() + + await transactionService.connectTransactionsListToPrices(makeTxs(2)) + expect(prismaMock.pricesOnTransactions.deleteMany).toHaveBeenCalledWith({ + where: { transactionId: { in: ['tx-0', 'tx-1'] } } + }) + }) + + it('records txs whose link replacement failed so a later run relinks them', async () => { + await clearPendingRelinks() + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction.mockRejectedValue(new Error('Transaction already closed')) + + await transactionService.connectTransactionsListToPrices(makeTxs(2)) + + expect((await redis.smembers(PRICE_RELINK_PENDING_KEY)).sort((a, b) => a.localeCompare(b))).toEqual(['tx-0', 'tx-1']) + await clearPendingRelinks() + errorSpy.mockRestore() + }) + + it('does not record failed txs that had no links (the no-prices pass finds them)', async () => { + await clearPendingRelinks() + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction.mockRejectedValue(new Error('Transaction already closed')) + + await transactionService.connectTransactionsListToPrices(makeTxs(2), { skipUnlink: true }) + + expect(await redis.smembers(PRICE_RELINK_PENDING_KEY)).toEqual([]) + errorSpy.mockRestore() + }) +}) + +describe('connectAllTransactionsToPrices', () => { + const dayTs = moment.utc('2026-08-02').unix() + const usd = { ...mockedUSDPriceOnTransaction.price, id: 11, timestamp: dayTs, networkId: 1 } + const cad = { ...mockedCADPriceOnTransaction.price, id: 12, timestamp: dayTs, networkId: 1 } + const page = [ + { id: 'a', timestamp: dayTs + 60, address: { networkId: 1, address: 'ecash:addr-a' } }, + { id: 'b', timestamp: dayTs + 120, address: { networkId: 1, address: 'ecash:addr-b' } } + ] + let invalidate: jest.SpyInstance + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.price.findMany = prismaMock.price.findMany + prisma.pricesOnTransactions.deleteMany = prismaMock.pricesOnTransactions.deleteMany + prisma.pricesOnTransactions.createMany = prismaMock.pricesOnTransactions.createMany + prisma.pricesOnTransactions.groupBy = prismaMock.pricesOnTransactions.groupBy + prisma.transaction.findMany = prismaMock.transaction.findMany + prismaMock.price.findMany.mockResolvedValue([usd, cad]) + prismaMock.pricesOnTransactions.createMany.mockResolvedValue({ count: 0 }) + ;(prismaMock.pricesOnTransactions.groupBy as unknown as jest.Mock).mockResolvedValue([]) + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + prismaMock.transaction.findMany + .mockResolvedValueOnce(page as any) + .mockResolvedValue([]) + invalidate = jest.spyOn(CacheSet, 'addressesSynced').mockResolvedValue() + }) + + afterEach(() => { + invalidate.mockRestore() + }) + + it('pages through unpriced txs by id and links them without unlinking', async () => { + await transactionService.connectAllTransactionsToPrices() + + const firstQuery = prismaMock.transaction.findMany.mock.calls[0][0] as any + const secondQuery = prismaMock.transaction.findMany.mock.calls[1][0] as any + expect(firstQuery.where).toEqual({ prices: { none: {} } }) + expect(firstQuery.orderBy).toEqual({ id: 'asc' }) + expect(secondQuery.where).toEqual({ prices: { none: {} }, id: { gt: 'b' } }) + expect(prismaMock.pricesOnTransactions.createMany).toHaveBeenCalledWith({ + data: [ + { transactionId: 'a', priceId: 11 }, { transactionId: 'a', priceId: 12 }, + { transactionId: 'b', priceId: 11 }, { transactionId: 'b', priceId: 12 } + ], + skipDuplicates: true + }) + expect(prismaMock.pricesOnTransactions.deleteMany).not.toHaveBeenCalled() + }) + + it('invalidates the caches of addresses whose txs got linked', async () => { + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-a', 'ecash:addr-b']) + }) + + it('does not invalidate caches when no tx could be linked', async () => { + prismaMock.price.findMany.mockResolvedValue([]) + const fetchMissing = jest.spyOn(priceService, 'fetchAndStoreMissingPrices').mockResolvedValue([]) + + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).not.toHaveBeenCalled() + fetchMissing.mockRestore() + }) + + it('still invalidates addresses linked before a later page query fails', async () => { + prismaMock.transaction.findMany.mockReset() + prismaMock.transaction.findMany + .mockResolvedValueOnce(page as any) + .mockRejectedValueOnce(new Error('db down')) + + await expect(transactionService.connectAllTransactionsToPrices()).rejects.toThrow('db down') + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-a', 'ecash:addr-b']) + }) + + it('retries a failed cache invalidation on the next run', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + invalidate.mockRejectedValueOnce(new Error('redis down')) + + await transactionService.connectAllTransactionsToPrices() + // Nothing left to link on the second run; the pending addresses are retried. + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).toHaveBeenCalledTimes(2) + expect(invalidate.mock.calls[1][0]).toEqual(['ecash:addr-a', 'ecash:addr-b']) + errorSpy.mockRestore() + }) + + it('relinks txs recorded as pending and clears them from the pending set', async () => { + await clearPendingRelinks() + await redis.sadd(PRICE_RELINK_PENDING_KEY, 'r1', 'deleted-tx') + const pendingTx = { id: 'r1', timestamp: dayTs + 60, address: { networkId: 1, address: 'ecash:addr-r' } } + prismaMock.pricesOnTransactions.deleteMany.mockResolvedValue({ count: 2 }) + prismaMock.transaction.findMany.mockReset() + prismaMock.transaction.findMany + .mockResolvedValueOnce([]) // no unpriced txs + .mockResolvedValueOnce([]) // no irregular txs + .mockResolvedValueOnce([pendingTx] as any) // pending relinks (deleted-tx no longer exists) + + await transactionService.connectAllTransactionsToPrices() + + expect(prismaMock.pricesOnTransactions.deleteMany).toHaveBeenCalledWith({ where: { transactionId: { in: ['r1'] } } }) + expect(prismaMock.pricesOnTransactions.createMany).toHaveBeenCalledWith({ + data: [{ transactionId: 'r1', priceId: 11 }, { transactionId: 'r1', priceId: 12 }], + skipDuplicates: true + }) + expect(await redis.smembers(PRICE_RELINK_PENDING_KEY)).toEqual([]) + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-r']) + }) + + it('makes a concurrent call wait for the run in progress instead of starting another', async () => { + await Promise.all([ + transactionService.connectAllTransactionsToPrices(), + transactionService.connectAllTransactionsToPrices() + ]) + + expect(prismaMock.pricesOnTransactions.groupBy).toHaveBeenCalledTimes(1) + }) +}) + +describe('retryOnTransactionTimeout', () => { + let timeoutSpy: jest.SpyInstance + let warnSpy: jest.SpyInstance + + beforeEach(() => { + timeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation(((fn: () => void) => { fn(); return 0 }) as any) + warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}) + }) + + afterEach(() => { + timeoutSpy.mockRestore() + warnSpy.mockRestore() + }) + + it('retries once when the DB transaction timed out', async () => { + const timeout = new Prisma.PrismaClientKnownRequestError('Transaction already closed', { code: 'P2028', clientVersion: 'test' }) + const fn = jest.fn().mockRejectedValueOnce(timeout).mockResolvedValueOnce('ok') + + await expect(transactionService.retryOnTransactionTimeout(fn)).resolves.toBe('ok') + expect(fn).toHaveBeenCalledTimes(2) + }) + + it('does not retry other errors', async () => { + const fn = jest.fn().mockRejectedValue(new Error('unique constraint')) + + await expect(transactionService.retryOnTransactionTimeout(fn)).rejects.toThrow('unique constraint') + expect(fn).toHaveBeenCalledTimes(1) + }) +}) + +describe('createManyTransactionsForSync with an overlapping sync', () => { + const row = (hash: string): any => ({ hash, addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }) + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.transaction.findMany = prismaMock.transaction.findMany + prisma.transaction.createMany = prismaMock.transaction.createMany + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + prismaMock.transaction.createMany.mockResolvedValue({ count: 1 }) + }) + + it('only reports the rows this call created, identified by the ids it generated', async () => { + prismaMock.transaction.findMany + .mockResolvedValueOnce([]) // neither tx existed when checked + .mockImplementationOnce((async (args: any) => { + // A concurrent sync inserted h2 first, so only our h1 row exists with one of our ids. + const ourIds: string[] = args.where.id.in + return [{ id: ourIds[0], hash: 'h1', addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }] + }) as any) + + const result = await transactionService.createManyTransactionsForSync([row('h1'), row('h2')]) + + const createManyData = (prismaMock.transaction.createMany.mock.calls[0][0] as any).data + expect(createManyData).toHaveLength(2) + expect(createManyData.every((r: any) => typeof r.id === 'string' && r.id.length > 0)).toBe(true) + const lookup = prismaMock.transaction.findMany.mock.calls[1][0] as any + expect(lookup.where).toEqual({ id: { in: createManyData.map((r: any) => r.id) } }) + expect(result.inserted.map(t => t.hash)).toEqual(['h1']) + expect(result.insertedCount).toBe(1) + }) +}) + +describe('invalidateCachesForAddresses', () => { + it('keeps addresses whose invalidation failed and retries them on the next call', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + const invalidate = jest.spyOn(CacheSet, 'addressesSynced') + .mockRejectedValueOnce(new Error('redis down')) + .mockResolvedValue() + + await transactionService.invalidateCachesForAddresses(['ecash:a']) + await transactionService.invalidateCachesForAddresses(['ecash:b']) + + expect(invalidate).toHaveBeenCalledTimes(2) + expect(invalidate.mock.calls[1][0]).toEqual(['ecash:a', 'ecash:b']) + invalidate.mockRestore() + errorSpy.mockRestore() + }) +})