From e5456864457cee0b42b541145e688a8e0df0e107 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 20:55:59 -0700 Subject: [PATCH 1/7] fix: link prices per sync batch and in chunks so txs don't stay unpriced Production had ~168k txs with no price links. The startup sync job only linked prices after syncing every address, and on prod that sync ran 45+ minutes and was restarted (deploys) before finishing, so every run's txs were left unpriced and the next run started over. Linking itself would also have failed at that size: all links were written in one interactive DB transaction with a 30s timeout, so it rolled back entirely. Meanwhile batch inserts were hitting the 15s transaction timeout when MySQL stalled, dropping those batches. - Bulk sync: link prices for each committed batch right after inserting it (before triggers), so an interrupted sync leaves nothing unpriced. Failures are logged and retried later. - connectTransactionsListToPrices: write links in chunks of 500 txs, each in its own DB transaction; a failed chunk is logged and skipped instead of rolling back the whole list. Skip the unlink step for txs known to have no links. Log one summary line instead of several per call. Returns the number of txs linked. - connectAllTransactionsToPrices: page unpriced txs by id (5k at a time) instead of loading them all; a concurrent call waits for the run in progress. - New repeating job (immediately at boot, then hourly) that links txs still without prices, independent of the startup sync, so the existing backlog clears after deploy. - persistManyTransactionRows: retry once when the insert transaction times out (Prisma P2028) instead of dropping the batch. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 10 + jobs/initJobs.ts | 23 ++- jobs/workers.ts | 20 ++ services/chronikService.ts | 17 +- services/transactionService.ts | 211 +++++++++++++-------- tests/unittests/chronikService.test.ts | 54 +++++- tests/unittests/transactionService.test.ts | 139 ++++++++++++++ 7 files changed, 389 insertions(+), 85 deletions(-) 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/services/chronikService.ts b/services/chronikService.ts index 1f77f7a7..35133118 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -16,7 +16,8 @@ import { upsertTransaction, getSimplifiedTransactions, getSimplifiedTrasaction, - connectTransactionsToPricesForAddresses + connectTransactionsToPricesForAddresses, + connectTransactionsListToPrices } from './transactionService' import { CacheSet } from 'redis/index' import { @@ -1107,6 +1108,20 @@ 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 { + await connectTransactionsListToPrices( + syncResult.inserted.map(t => ({ ...t, address: { networkId: this.networkId } })), + { skipUnlink: true } + ) + } 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..e6ec3e09 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -1,6 +1,6 @@ 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' @@ -447,29 +447,16 @@ 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 - } - 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 +519,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 how many txs were linked. + */ +export async function connectTransactionsListToPrices ( + txList: PriceLinkableTransaction[], + { skipUnlink = false }: ConnectPricesOptions = {} +): Promise { + if (txList.length === 0) return 0 // collect UNIQUE (networkId, timestamp) pairs const networkIdToTimestamps = new Map>() @@ -551,11 +550,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 +580,106 @@ 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 + + let linked = 0 + 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 } + ) + linked += chunk.length + } 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}`) + } } - if (txIdsToConnect.length === 0) { - console.warn('[PRICES] No txs to connect after filtering — all had missing prices.') - return + const failedTxs = txsToConnect.length - linked + if (skippedNoPrice > 0 || failedChunks > 0 || txList.length >= PRICES_CONNECTION_TX_CHUNK_SIZE) { + console.log( + `[PRICES] Linked ${linked}/${txList.length} txs to prices` + + (skippedNoPrice > 0 ? `, ${skippedNoPrice} skipped (no price data)` : '') + + (failedChunks > 0 ? `, ${failedTxs} failed in ${failedChunks} chunks` : '') + + '.' + ) } + return linked +} - 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 } - ) +/** + * 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 + } } -export async function connectAllTransactionsToPrices (): Promise { +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.`) + 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: { id: true, timestamp: true, address: { select: { networkId: true } } } + }) + if (page.length === 0) break + cursor = page[page.length - 1].id + found += page.length + linked += await connectTransactionsListToPrices(page, { skipUnlink: true }) + 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 txs = [ - ...noPricesTxs, - ...wrongNumberOfPricesTxs - ] - console.log('[PRICES] Connecting txs to prices...') - void await connectTransactionsListToPrices(txs) - console.log('[PRICES] Finished connecting txs to prices.') + const relinked = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinked} irregular txs linked).`) } /** * 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 +705,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,7 +905,10 @@ async function persistManyTransactionRows ( let updatedCount = 0 if (newTxs.length > 0) { - await prisma.$transaction( + // 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, @@ -902,14 +965,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 +1019,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,18 +1102,6 @@ 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 { const grouped = await prisma.pricesOnTransactions.groupBy({ by: ['transactionId'], diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 9f43d70e..e6c4aed7 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -10,7 +10,8 @@ import { } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' import { fetchAddressesArray } from '../../services/addressService' -import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses } from '../../services/transactionService' +import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync } from '../../services/transactionService' +import prisma from '../../prisma-local/clientInstance' import { executeAddressTriggers } from '../../services/triggerService' import { CacheSet } from '../../redis/index' @@ -73,7 +74,8 @@ jest.mock('../../services/transactionService', () => ({ getSimplifiedTransactions: jest.fn(), getSimplifiedTrasaction: jest.fn(), connectAllTransactionsToPrices: jest.fn(), - connectTransactionsToPricesForAddresses: jest.fn() + connectTransactionsToPricesForAddresses: jest.fn(), + connectTransactionsListToPrices: jest.fn() })) jest.mock('../../redis/index', () => ({ @@ -1708,3 +1710,51 @@ 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(1) + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(link).toHaveBeenCalledWith( + [{ ...inserted[0], address: { networkId: 1 } }], + { skipUnlink: true } + ) + }) + + 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..c493b2c9 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -595,3 +595,142 @@ 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).toBe(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).toBe(1) + 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'] } } + }) + }) +}) + +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 } }, + { id: 'b', timestamp: dayTs + 120, 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.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([]) + }) + + 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('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) + }) +}) From e07107aa7cdea685396611e1c25ac85e67c611b9 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:01:44 -0700 Subject: [PATCH 2/7] fix: invalidate caches of addresses whose txs get linked to prices Cached payments are built while txs are unpriced and leave them out. When connectAllTransactionsToPrices (startup job or the new repeating job) links those txs, drop the caches of the affected addresses and their users' dashboards so they rebuild with the newly priced payments. Previously only the end of a completed startup sync cleared caches, which on prod never happened. connectTransactionsListToPrices now returns the ids of the txs it linked, so only addresses with actually linked txs are invalidated (not ones whose txs still have no price data, which would otherwise be rebuilt every hour). Co-Authored-By: Claude Opus 5.5 --- services/transactionService.ts | 56 ++++++++++++++-------- tests/unittests/chronikService.test.ts | 2 +- tests/unittests/transactionService.test.ts | 30 ++++++++++-- 3 files changed, 63 insertions(+), 25 deletions(-) diff --git a/services/transactionService.ts b/services/transactionService.ts index e6ec3e09..483c7b3d 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -113,12 +113,6 @@ const includeNetwork = { } } -const transactionWithNetwork = Prisma.validator()( - { include: includeNetwork } -) - -type TransactionWithNetwork = Prisma.TransactionGetPayload - const transactionWithAddressAndPrices = Prisma.validator()( { include: includeAddressAndPrices } ) @@ -530,13 +524,13 @@ export interface ConnectPricesOptions { * 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 how many txs were linked. + * Returns the ids of the txs that were linked. */ export async function connectTransactionsListToPrices ( txList: PriceLinkableTransaction[], { skipUnlink = false }: ConnectPricesOptions = {} -): Promise { - if (txList.length === 0) return 0 +): Promise { + if (txList.length === 0) return [] // collect UNIQUE (networkId, timestamp) pairs const networkIdToTimestamps = new Map>() @@ -590,7 +584,7 @@ export async function connectTransactionsListToPrices ( } const skippedNoPrice = txList.length - txsToConnect.length - let linked = 0 + 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) @@ -606,23 +600,23 @@ export async function connectTransactionsListToPrices ( }, { timeout: PRICES_CONNECTION_TIMEOUT } ) - linked += chunk.length + 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}`) } } - const failedTxs = txsToConnect.length - linked + const failedTxs = txsToConnect.length - linkedIds.length if (skippedNoPrice > 0 || failedChunks > 0 || txList.length >= PRICES_CONNECTION_TX_CHUNK_SIZE) { console.log( - `[PRICES] Linked ${linked}/${txList.length} txs to prices` + + `[PRICES] Linked ${linkedIds.length}/${txList.length} txs to prices` + (skippedNoPrice > 0 ? `, ${skippedNoPrice} skipped (no price data)` : '') + (failedChunks > 0 ? `, ${failedTxs} failed in ${failedChunks} chunks` : '') + '.' ) } - return linked + return linkedIds } let connectAllTransactionsToPricesRun: Promise | undefined @@ -649,6 +643,16 @@ export async function connectAllTransactionsToPrices (): Promise { async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started 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 addressesToInvalidate = new Set() + 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)) addressesToInvalidate.add(t.address.address) + } + } + let found = 0 let linked = 0 let cursor: string | undefined @@ -660,20 +664,32 @@ async function runConnectAllTransactionsToPrices (): Promise { }, orderBy: { id: 'asc' }, take: UNPRICED_TXS_PAGE_SIZE, - select: { id: true, timestamp: true, address: { select: { networkId: true } } } + select: { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } }) if (page.length === 0) break cursor = page[page.length - 1].id found += page.length - linked += await connectTransactionsListToPrices(page, { skipUnlink: true }) + 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 relinked = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) - console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinked} irregular txs linked).`) + const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + trackLinked(wrongNumberOfPricesTxs, relinkedIds) + console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinkedIds.length} irregular txs linked).`) + + if (addressesToInvalidate.size > 0) { + try { + await CacheSet.addressesSynced([...addressesToInvalidate]) + console.log(`[PRICES] Invalidated caches for ${addressesToInvalidate.size} addresses with newly priced txs.`) + } catch (err: any) { + console.error(`[PRICES] Failed to invalidate caches after linking prices: ${err.message as string}`) + } + } } /** @@ -1102,7 +1118,7 @@ export async function markTransactionsOrphaned (hash: string): Promise { }) } -export async function fetchAllTransactionsWithIrregularPrices (): Promise { +export async function fetchAllTransactionsWithIrregularPrices (): Promise> { const grouped = await prisma.pricesOnTransactions.groupBy({ by: ['transactionId'], _count: { transactionId: true }, @@ -1113,7 +1129,7 @@ export async function fetchAllTransactionsWithIrregularPrices (): Promise { }) it('links prices for the txs it just inserted, with the client network', async () => { - const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(1) + const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(['tx-1']) const client = new ChronikBlockchainClient('ecash') await (client as any).commitTransactionsBatch(commitTuples, [], false) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index c493b2c9..f34ea6a1 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -620,7 +620,7 @@ describe('connectTransactionsListToPrices chunking', () => { it('writes each chunk of txs in its own DB transaction', async () => { const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) - expect(linked).toBe(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) @@ -635,7 +635,7 @@ describe('connectTransactionsListToPrices chunking', () => { const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) - expect(linked).toBe(1) + expect(linked).toEqual(['tx-500']) expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Transaction already closed')) errorSpy.mockRestore() @@ -657,9 +657,10 @@ describe('connectAllTransactionsToPrices', () => { 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 } }, - { id: 'b', timestamp: dayTs + 120, address: { networkId: 1 } } + { 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 @@ -675,6 +676,11 @@ describe('connectAllTransactionsToPrices', () => { 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 () => { @@ -695,6 +701,22 @@ describe('connectAllTransactionsToPrices', () => { 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('makes a concurrent call wait for the run in progress instead of starting another', async () => { await Promise.all([ transactionService.connectAllTransactionsToPrices(), From e46ae0726c1579d915f1ab61d7ac7833fcff2890 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:12:57 -0700 Subject: [PATCH 3/7] perf: invalidate only changed addresses after sync; log sync timings Every completed startup sync wiped the payment, balance and dashboard caches of every address and user, so each user's next page load rebuilt their whole payment history from the DB. That, plus the startup sync competing for MySQL, is a large part of the slow page loads (long-running loading spinners). - Startup sync now reports which addresses got new txs or had existing txs updated (commitTransactionsBatch -> syncAddresses -> syncMissedTransactions), and invalidateCachesAfterBlockchainSync only clears those addresses and the dashboards of the users who own them (one query via fetchUsersForAddresses). If the changed set is unknown because a network's sync failed part-way, it falls back to clearing everything as before. Addresses whose txs get newly priced are already invalidated by connectAllTransactionsToPrices. - Cache rebuilds log one line per address with how many payments were left out for missing price links, instead of one warning per tx (thousands of lines per rebuild on prod). - Startup sync logs per-address timings (pages, chronik time, time waiting on DB commits) for addresses with new txs or that take over 30s, flags addresses that were never synced and fetch their full history, and ends with a summary plus the 10 slowest addresses, to find why it takes 45+ min. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 4 + jobs/workers.ts | 32 +++++--- redis/paymentCache.ts | 8 +- services/chronikService.ts | 108 ++++++++++++++++++++----- services/transactionService.ts | 9 ++- services/userService.ts | 15 ++++ tests/unittests/chronikService.test.ts | 60 +++++++++++++- tests/unittests/userService.test.ts | 21 +++++ tests/unittests/workers.test.ts | 66 +++++++++++++++ types/chronikTypes.ts | 2 + 10 files changed, 289 insertions(+), 36 deletions(-) create mode 100644 tests/unittests/workers.test.ts diff --git a/constants/index.ts b/constants/index.ts index 8d153d72..290ec3c0 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -296,6 +296,10 @@ export const CHRONIK_FETCH_N_TXS_PER_PAGE = 200 export const INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY = 16 export const TX_EMIT_BATCH_SIZE = 200 // for our generator, not chronik export const DB_COMMIT_BATCH_SIZE = 200 // tamanho dos lotes para commit no DB +// Addresses whose startup sync takes longer than this are logged with timings. +export const SLOW_ADDRESS_SYNC_LOG_THRESHOLD = 30_000 +// How many of the slowest addresses to list at the end of a startup sync. +export const SLOWEST_ADDRESSES_TO_LOG = 10 export const TX_BATCH_POLLING_DELAY = 500 // delay (ms) between polling for new batches of txs to commit to the DB export const TRIGGER_POST_CONCURRENCY = 100 diff --git a/jobs/workers.ts b/jobs/workers.ts index cb576304..2d815b5b 100644 --- a/jobs/workers.ts +++ b/jobs/workers.ts @@ -8,7 +8,7 @@ import { fetchAllAddresses } from 'services/addressService' import { cleanupExpiredClientPayments } from 'services/clientPaymentService' import { multiBlockchainClient } from 'services/chronikService' import { connectAllTransactionsToPrices } from 'services/transactionService' -import { fetchAllUsers } from 'services/userService' +import { fetchAllUsers, fetchUsersForAddresses } from 'services/userService' import * as priceService from 'services/priceService' @@ -38,25 +38,37 @@ const invalidateAddressCaches = async ( } /** - * Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync. - * Rebuild is lazy on the next API request. + * Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync, + * for the addresses whose txs changed and the users who own them. Rebuild is lazy + * on the next API request. Every other cache stays warm: wiping all of them made + * each user's next page load rebuild their whole history from the DB. + * Addresses whose txs were newly linked to prices are invalidated separately by + * connectAllTransactionsToPrices. If the changed set is unknown (the sync failed + * part-way), falls back to invalidating everything. */ -async function invalidateCachesAfterBlockchainSync (): Promise { - console.log('[CACHE]: Invalidating caches after blockchain sync...') - const addresses = await fetchAllAddresses() +export async function invalidateCachesAfterBlockchainSync (changedAddresses: string[] | undefined): Promise { + const invalidateAll = changedAddresses === undefined + const addresses = invalidateAll + ? (await fetchAllAddresses()).map(a => a.address) + : [...new Set(changedAddresses)] + console.log( + invalidateAll + ? `[CACHE]: Invalidating caches for all ${addresses.length} addresses after blockchain sync (changed addresses unknown)...` + : `[CACHE]: Invalidating caches for ${addresses.length} addresses changed by blockchain sync...` + ) let paymentCacheFailures = 0 let balanceCacheFailures = 0 for (let i = 0; i < addresses.length; i += ADDRESS_INVALIDATION_BATCH_SIZE) { const batch = addresses.slice(i, i + ADDRESS_INVALIDATION_BATCH_SIZE) const results = await Promise.all( - batch.map(async (a) => await invalidateAddressCaches(a.address)) + batch.map(async (a) => await invalidateAddressCaches(a)) ) for (const r of results) { paymentCacheFailures += r.paymentFailures balanceCacheFailures += r.balanceFailures } } - const users = await fetchAllUsers() + const users = invalidateAll ? await fetchAllUsers() : await fetchUsersForAddresses(addresses) let dashboardCacheFailures = 0 await Promise.all( users.map(async (u) => { @@ -112,9 +124,9 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet async (job) => { console.log(`job ${job.id as string}: syncing missed prices, transactions and connecting them...`) await priceService.syncPastDaysNewerPrices() - await multiBlockchainClient.syncMissedTransactions() + const changedAddresses = await multiBlockchainClient.syncMissedTransactions() await connectAllTransactionsToPrices() - await invalidateCachesAfterBlockchainSync() + await invalidateCachesAfterBlockchainSync(changedAddresses) }, { connection: redisBullMQ, diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index 3b5d241e..2a226752 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -172,14 +172,17 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: let balance = new Prisma.Decimal(0) let paymentCount = 0 let txCount = 0 + let skippedUnpriced = 0 const txsWithPaybuttonsGenerator = generateTransactionsWithPaybuttonsAndPricesForAddress(address.id) for await (const batch of txsWithPaybuttonsGenerator) { for (const tx of batch) { txCount++ balance = balance.plus(tx.amount) if (tx.amount.gt(0)) { + // Left out until its prices are linked; connectAllTransactionsToPrices + // then invalidates this address so it is rebuilt with the tx. if (tx.prices.length !== N_OF_QUOTES) { - console.warn(`[CACHE] Skipping tx ${tx.hash} — missing price links (${tx.prices.length}/${N_OF_QUOTES})`) + skippedUnpriced++ continue } const payment = generatePaymentFromTx(tx) @@ -192,6 +195,9 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: } const elapsed = ((Date.now() - startTime) / 1000).toFixed(1) console.log(`[CACHE] Cached address ${address.address.slice(0, 20)}...: ${paymentCount} payments, ${txCount} txs in ${elapsed}s`) + if (skippedUnpriced > 0) { + console.warn(`[CACHE] Address ${address.address}: left out ${skippedUnpriced} payments with missing price links.`) + } const info: AddressPaymentInfo = { balance, paymentCount diff --git a/services/chronikService.ts b/services/chronikService.ts index 35133118..64971f3e 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -409,6 +409,27 @@ export class ChronikBlockchainClient { return txsPage.txs } + private logSyncTimings ( + logPrefix: string, + startedAt: number, + timings: Array<{ address: string, ms: number, chronikMs: number, pages: number, newTxs: number }> + ): void { + const totalPages = timings.reduce((sum, t) => sum + t.pages, 0) + const totalChronikMs = timings.reduce((sum, t) => sum + t.chronikMs, 0) + const withNewTxs = timings.filter(t => t.newTxs > 0).length + console.log( + `${logPrefix} <<< Fetched ${timings.length} addresses in ${((Date.now() - startedAt) / 1000).toFixed(1)}s: ` + + `${withNewTxs} with new txs, ${totalPages} chronik pages, ${(totalChronikMs / 1000).toFixed(1)}s total chronik time.` + ) + const slowest = [...timings].sort((a, b) => b.ms - a.ms).slice(0, SLOWEST_ADDRESSES_TO_LOG) + for (const t of slowest) { + console.log( + `${logPrefix} slowest: ${t.address} ${(t.ms / 1000).toFixed(1)}s, ${t.pages} pages, ${t.newTxs} new txs ` + + `(chronik ${(t.chronikMs / 1000).toFixed(1)}s).` + ) + } + } + /* * For each address, fetch pages in parallel (“burst”), * then use the burst’s newest/oldest timestamps to decide whether to continue. @@ -427,6 +448,11 @@ export class ChronikBlockchainClient { const chronikTxs: ChronikTxWithAddress[] = [] const completedAddresses: string[] = [] + // Per-address timings, to find what makes a startup sync slow. "waited" is + // time not spent fetching from chronik: mostly paused while batches are + // committed to the DB. + const fetchStartedAt = Date.now() + const addressTimings: Array<{ address: string, ms: number, chronikMs: number, pages: number, newTxs: number }> = [] let producersPaused = false const producerPauseWaiters: Array<() => void> = [] @@ -494,6 +520,9 @@ export class ChronikBlockchainClient { let nextBurstBasePageIndex = 0 let hasReachedStoppingCondition = false let newTxs = 0 + const addressStartedAt = Date.now() + let chronikMs = 0 + let pagesFetched = 0 try { while (!hasReachedStoppingCondition) { @@ -502,11 +531,19 @@ export class ChronikBlockchainClient { const pageIndex = nextBurstBasePageIndex let pageTxs: Tx[] = [] + const pageStartedAt = Date.now() try { pageTxs = await this.getPaginatedTxs(address.address, pageIndex, CHRONIK_FETCH_N_TXS_PER_PAGE) + pagesFetched++ } catch (err: any) { console.warn(`${addrLogPrefix} page=${pageIndex} failed: ${err.message as string}`) pageTxs = [] + } finally { + chronikMs += Date.now() - pageStartedAt + } + + if (pageIndex === 0 && pageTxs.length > 0 && lastSyncedTimestampSeconds === 0) { + console.log(`${addrLogPrefix} never synced (no lastSynced), fetching its full history.`) } if (pageIndex === 0 && pageTxs.length === 0) { @@ -547,12 +584,17 @@ export class ChronikBlockchainClient { } newTxs += newTxsInThisPage } - if (newTxs > 0) { - console.log(`${addrLogPrefix} ${newTxs} new txs.`) - } } catch (err: any) { console.error(`${logPrefix}: address job failed: ${err.message as string}`) } finally { + const ms = Date.now() - addressStartedAt + addressTimings.push({ address: address.address, ms, chronikMs, pages: pagesFetched, newTxs }) + if (newTxs > 0 || ms > SLOW_ADDRESS_SYNC_LOG_THRESHOLD) { + console.log( + `${addrLogPrefix} ${newTxs} new txs, ${pagesFetched} pages in ${(ms / 1000).toFixed(1)}s ` + + `(chronik ${(chronikMs / 1000).toFixed(1)}s, waited ${((ms - chronikMs) / 1000).toFixed(1)}s).` + ) + } completedAddresses.push(address.address) } } @@ -625,6 +667,8 @@ export class ChronikBlockchainClient { await Promise.all(Array.from(activeWorkers)) } + this.logSyncTimings(logPrefix, fetchStartedAt, addressTimings) + // Final TX flush after all addresses processed if (chronikTxs.length >= TX_EMIT_BATCH_SIZE) { yield * runDrainCycle() @@ -1099,7 +1143,7 @@ export class ChronikBlockchainClient { commitTuples: Array<{ row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string }>, productionAddressesIds: string[], runTriggers: boolean - ): Promise { + ): Promise { const rows = commitTuples.map(p => p.row) const rowsToUpsert = await filterRowsNeedingCreateMany(rows) const syncResult = await createManyTransactionsForSync(rowsToUpsert) @@ -1108,6 +1152,15 @@ export class ChronikBlockchainClient { `${commitTuples.length}` ) + // Addresses whose cached payments/balance are now stale. + const addressStringById = new Map(commitTuples.map(t => [t.row.addressId, t.addressString])) + const changedAddresses = [...new Set([ + ...syncResult.inserted.map(t => t.addressId), + ...syncResult.updatedAddressIds + ])] + .map(id => addressStringById.get(id)) + .filter((a): a is string => a !== undefined) + // 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. @@ -1190,6 +1243,7 @@ export class ChronikBlockchainClient { } } } + return changedAddresses } public async syncAddresses (addresses: Address[], runTriggers = false): Promise { @@ -1210,6 +1264,11 @@ export class ChronikBlockchainClient { interface RowWithRaw { row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string } let toCommit: RowWithRaw[] = [] + const changedAddresses = new Set() + const commit = async (tuples: RowWithRaw[]): Promise => { + const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) + changed.forEach(a => changedAddresses.add(a)) + } try { const pfx = `${this.CHRONIK_MSG_PREFIX}[PARALLEL FETCHING]` @@ -1225,11 +1284,7 @@ export class ChronikBlockchainClient { if (batch.phase === 'drain-complete') { if (toCommit.length > 0) { const remainder = toCommit.splice(0) - await this.commitTransactionsBatch( - remainder, - productionAddressesIds, - runTriggers - ) + await commit(remainder) remainder.length = 0 } continue @@ -1257,7 +1312,7 @@ export class ChronikBlockchainClient { if (toCommit.length >= DB_COMMIT_BATCH_SIZE) { const commitPairs = toCommit.splice(0, DB_COMMIT_BATCH_SIZE) - await this.commitTransactionsBatch(commitPairs, productionAddressesIds, runTriggers) + await commit(commitPairs) // Clear commitPairs commitPairs.length = 0 } @@ -1275,7 +1330,7 @@ export class ChronikBlockchainClient { // final DB flush (se sobrou menos que DB_COMMIT_BATCH_SIZE) if (toCommit.length > 0) { - await this.commitTransactionsBatch(toCommit, productionAddressesIds, runTriggers) + await commit(toCommit) toCommit = [] } @@ -1297,13 +1352,17 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX} Finished syncing ${total} txs for ${addresses.length} addresses with ${failed.length} errors.`) console.timeEnd(`${this.CHRONIK_MSG_PREFIX} syncAddresses`) - return { failedAddressesWithErrors, successfulAddressesWithCount } + return { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses: [...changedAddresses] } } - public async syncMissedTransactions (): Promise { + /** + * Returns the addresses whose txs changed (new or updated), or undefined if + * the sync failed in a way that leaves that unknown. + */ + public async syncMissedTransactions (): Promise { const addresses = await fetchAllAddressesForNetworkId(this.networkId) try { - const { failedAddressesWithErrors, successfulAddressesWithCount } = await this.syncAddresses(addresses, true) + const { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses } = await this.syncAddresses(addresses, true) Object.keys(failedAddressesWithErrors).forEach((addr) => { console.error(`${this.CHRONIK_MSG_PREFIX}: When syncing missing addresses for address ${addr} encountered error: ${failedAddressesWithErrors[addr]}`) }) @@ -1313,8 +1372,10 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX}:> ${addr} — ${successfulAddressesWithCount[addr]}.`) } }) + return changedAddresses ?? [] } catch (err: any) { console.error(`${this.CHRONIK_MSG_PREFIX}: ERROR: (skipping anyway) initial missing transactions sync failed: ${err.message as string} ${err.stack as string}`) + return undefined } } @@ -1494,16 +1555,19 @@ class MultiBlockchainClient { public async syncAddresses (addresses: Address[], runTriggers = false): Promise { let failedAddressesWithErrors: KeyValueT = {} let successfulAddressesWithCount: KeyValueT = {} + const changedAddresses: string[] = [] for (const networkSlug of Object.keys(this.clients)) { const thisNetworkAddresses = addresses.filter(a => a.networkId === NETWORK_IDS_FROM_SLUGS[networkSlug]) const ret = await this.clients[networkSlug as MainNetworkSlugsType].syncAddresses(thisNetworkAddresses, runTriggers) failedAddressesWithErrors = { ...failedAddressesWithErrors, ...ret.failedAddressesWithErrors } successfulAddressesWithCount = { ...successfulAddressesWithCount, ...ret.successfulAddressesWithCount } + changedAddresses.push(...(ret.changedAddresses ?? [])) } return { failedAddressesWithErrors, - successfulAddressesWithCount + successfulAddressesWithCount, + changedAddresses } } @@ -1520,10 +1584,16 @@ class MultiBlockchainClient { return await this.clients[networkSlug as MainNetworkSlugsType].getBalance(address) } - public async syncMissedTransactions (): Promise { + /** + * Returns the addresses whose txs changed during the sync, or undefined if + * that is unknown for any network (callers should then assume all changed). + */ + public async syncMissedTransactions (): Promise { await this.waitForStart() - await this.clients.bitcoincash.syncMissedTransactions() - await this.clients.ecash.syncMissedTransactions() + const bch = await this.clients.bitcoincash.syncMissedTransactions() + const xec = await this.clients.ecash.syncMissedTransactions() + if (bch === undefined || xec === undefined) return undefined + return [...bch, ...xec] } public async syncAndSubscribeAddresses (addresses: Address[]): Promise { diff --git a/services/transactionService.ts b/services/transactionService.ts index 483c7b3d..759bdc9e 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -775,6 +775,8 @@ export interface SyncPersistedTransaction { export interface CreateManyTransactionsSyncResult { insertedCount: number inserted: SyncPersistedTransaction[] + // Addresses of pre-existing txs whose confirmed/timestamp/orphaned changed. + updatedAddressIds: string[] } interface PersistManyTransactionRowsResult { @@ -1043,13 +1045,14 @@ export async function createManyTransactionsForSync ( transactionsData: Prisma.TransactionUncheckedCreateInput[] ): Promise { if (transactionsData.length === 0) { - return { insertedCount: 0, inserted: [] } + return { insertedCount: 0, inserted: [], updatedAddressIds: [] } } - const { inserted } = await persistManyTransactionRows(transactionsData) + const { inserted, updated } = await persistManyTransactionRows(transactionsData) return { insertedCount: inserted.length, - inserted + inserted, + updatedAddressIds: [...new Set(updated.map(t => t.addressId))] } } diff --git a/services/userService.ts b/services/userService.ts index cf8b6fa5..a68b9cdc 100644 --- a/services/userService.ts +++ b/services/userService.ts @@ -124,6 +124,21 @@ export async function fetchUsersForAddress (addressString: string): Promise { + if (addressStrings.length === 0) return [] + return await prisma.userProfile.findMany({ + where: { + addresses: { + some: { + address: { + address: { in: addressStrings } + } + } + } + } + }) +} + export async function isUserAdmin (id: string): Promise { const user = await prisma.userProfile.findFirst({ where: { diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 1b6bf12d..6fc4ed3e 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -65,7 +65,8 @@ jest.mock('../../services/transactionService', () => ({ createManyTransactions: jest.fn(), createManyTransactionsForSync: jest.fn(async () => ({ insertedCount: 0, - inserted: [] + inserted: [], + updatedAddressIds: [] })), filterRowsNeedingCreateMany: jest.fn(async (rows: unknown[]) => rows), deleteTransactions: jest.fn(), @@ -1728,7 +1729,7 @@ describe('commitTransactionsBatch price linking', () => { beforeEach(() => { process.env.WS_AUTH_KEY = 'test-auth-key' - ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted }) + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted, updatedAddressIds: [] }) jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) jest.spyOn(console, 'log').mockImplementation(() => {}) }) @@ -1754,7 +1755,60 @@ describe('commitTransactionsBatch price linking', () => { const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) const client = new ChronikBlockchainClient('ecash') - await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toBeUndefined() + await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toEqual(['ecash:addr-1']) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down')) }) }) + +describe('changed addresses reported by the sync', () => { + beforeEach(() => { + process.env.WS_AUTH_KEY = 'test-auth-key' + jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) + jest.spyOn(console, 'log').mockImplementation(() => {}) + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue([]) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('commitTransactionsBatch returns the addresses with inserted or updated txs', async () => { + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ + insertedCount: 1, + inserted: [{ id: 'tx-1', hash: 'h1', addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }], + updatedAddressIds: ['addr-2'] + }) + const client = new ChronikBlockchainClient('ecash') + const tuple = (addressId: string, hash: string): any => ({ + row: { hash, addressId, timestamp: 1700000000, amount: 1 }, + raw: {}, + addressString: `ecash:${addressId}` + }) + + const changed = await (client as any).commitTransactionsBatch( + [tuple('addr-1', 'h1'), tuple('addr-2', 'h2'), tuple('addr-3', 'h3')], + [], + false + ) + + expect(changed.sort()).toEqual(['ecash:addr-1', 'ecash:addr-2']) + }) + + it('MultiBlockchainClient.syncMissedTransactions merges both networks', async () => { + const clients = (multiBlockchainClient as any).clients + jest.spyOn(multiBlockchainClient, 'waitForStart').mockResolvedValue() + jest.spyOn(clients.bitcoincash, 'syncMissedTransactions').mockResolvedValue(['bitcoincash:a']) + jest.spyOn(clients.ecash, 'syncMissedTransactions').mockResolvedValue(['ecash:b']) + + await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toEqual(['bitcoincash:a', 'ecash:b']) + }) + + it('MultiBlockchainClient.syncMissedTransactions is undefined when a network sync failed', async () => { + const clients = (multiBlockchainClient as any).clients + jest.spyOn(multiBlockchainClient, 'waitForStart').mockResolvedValue() + jest.spyOn(clients.bitcoincash, 'syncMissedTransactions').mockResolvedValue(undefined) + jest.spyOn(clients.ecash, 'syncMissedTransactions').mockResolvedValue(['ecash:b']) + + await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toBeUndefined() + }) +}) diff --git a/tests/unittests/userService.test.ts b/tests/unittests/userService.test.ts index bf74df29..14126162 100644 --- a/tests/unittests/userService.test.ts +++ b/tests/unittests/userService.test.ts @@ -126,3 +126,24 @@ describe('user trigger limits and pro logic', () => { expect(userService.getUserRemainingTriggerCreditsLimit(user, 'PostData')).toBe(8) }) }) + +describe('fetchUsersForAddresses', () => { + it('fetches the owners of any of the given addresses in one query', async () => { + prisma.userProfile.findMany = prismaMock.userProfile.findMany + prismaMock.userProfile.findMany.mockResolvedValue([mockedUserProfile]) + + const users = await userService.fetchUsersForAddresses(['ecash:a', 'ecash:b']) + + expect(users).toEqual([mockedUserProfile]) + expect(prismaMock.userProfile.findMany).toHaveBeenCalledWith({ + where: { addresses: { some: { address: { address: { in: ['ecash:a', 'ecash:b'] } } } } } + }) + }) + + it('does not query when no address is given', async () => { + prisma.userProfile.findMany = prismaMock.userProfile.findMany + + await expect(userService.fetchUsersForAddresses([])).resolves.toEqual([]) + expect(prismaMock.userProfile.findMany).not.toHaveBeenCalled() + }) +}) diff --git a/tests/unittests/workers.test.ts b/tests/unittests/workers.test.ts new file mode 100644 index 00000000..84829a5b --- /dev/null +++ b/tests/unittests/workers.test.ts @@ -0,0 +1,66 @@ +import { invalidateCachesAfterBlockchainSync } from '../../jobs/workers' +import { clearPaymentCacheForAddress } from '../../redis/paymentCache' +import { clearBalanceCache } from '../../redis/balanceCache' +import { clearDashboardCache } from '../../redis/dashboardCache' +import { fetchAllAddresses } from '../../services/addressService' +import { fetchAllUsers, fetchUsersForAddresses } from '../../services/userService' + +jest.mock('bullmq', () => ({ Worker: jest.fn() })) +jest.mock('../../redis/clientInstance', () => ({ redisBullMQ: {} })) +jest.mock('../../redis/paymentCache', () => ({ clearPaymentCacheForAddress: jest.fn() })) +jest.mock('../../redis/balanceCache', () => ({ clearBalanceCache: jest.fn() })) +jest.mock('../../redis/dashboardCache', () => ({ clearDashboardCache: jest.fn() })) +jest.mock('../../services/addressService', () => ({ fetchAllAddresses: jest.fn() })) +jest.mock('../../services/userService', () => ({ + fetchAllUsers: jest.fn(), + fetchUsersForAddresses: jest.fn() +})) +jest.mock('../../services/clientPaymentService', () => ({ cleanupExpiredClientPayments: jest.fn() })) +jest.mock('../../services/chronikService', () => ({ multiBlockchainClient: {} })) +jest.mock('../../services/transactionService', () => ({ connectAllTransactionsToPrices: jest.fn() })) +jest.mock('../../services/priceService', () => ({})) + +describe('invalidateCachesAfterBlockchainSync', () => { + beforeEach(() => { + jest.clearAllMocks() + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('only clears the changed addresses and the dashboards of their users', async () => { + ;(fetchUsersForAddresses as jest.Mock).mockResolvedValue([{ id: 'user-1' }]) + + await invalidateCachesAfterBlockchainSync(['ecash:a', 'ecash:b', 'ecash:a']) + + expect(fetchAllAddresses).not.toHaveBeenCalled() + expect(fetchAllUsers).not.toHaveBeenCalled() + expect((clearPaymentCacheForAddress as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:b']) + expect((clearBalanceCache as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:b']) + expect(fetchUsersForAddresses).toHaveBeenCalledWith(['ecash:a', 'ecash:b']) + expect(clearDashboardCache).toHaveBeenCalledTimes(1) + expect(clearDashboardCache).toHaveBeenCalledWith('user-1') + }) + + it('clears nothing when no address changed', async () => { + ;(fetchUsersForAddresses as jest.Mock).mockResolvedValue([]) + + await invalidateCachesAfterBlockchainSync([]) + + expect(clearPaymentCacheForAddress).not.toHaveBeenCalled() + expect(clearDashboardCache).not.toHaveBeenCalled() + }) + + it('falls back to clearing every cache when the changed addresses are unknown', async () => { + ;(fetchAllAddresses as jest.Mock).mockResolvedValue([{ address: 'ecash:a' }, { address: 'ecash:c' }]) + ;(fetchAllUsers as jest.Mock).mockResolvedValue([{ id: 'user-1' }, { id: 'user-2' }]) + + await invalidateCachesAfterBlockchainSync(undefined) + + expect((clearPaymentCacheForAddress as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:c']) + expect(fetchUsersForAddresses).not.toHaveBeenCalled() + expect(clearDashboardCache).toHaveBeenCalledTimes(2) + }) +}) diff --git a/types/chronikTypes.ts b/types/chronikTypes.ts index 82e47b86..fbfb8046 100644 --- a/types/chronikTypes.ts +++ b/types/chronikTypes.ts @@ -50,4 +50,6 @@ export interface SubscriptionReturn { export interface SyncAndSubscriptionReturn { failedAddressesWithErrors: KeyValueT successfulAddressesWithCount: KeyValueT + // Addresses that got new txs, or existing txs updated, during the sync. + changedAddresses?: string[] } From faa89a042893865bf84f6c57c7cd16e5fd834b38 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:37:16 -0700 Subject: [PATCH 4/7] fix: don't lose cache invalidations or failed relinks in price linking Review follow-ups for connectAllTransactionsToPrices / connectTransactionsListToPrices: - Invalidate caches in a finally block, so addresses whose txs were linked before a later page query or price fetch failed still get their caches dropped (later runs no longer see those txs as unpriced). - When cache invalidation fails, keep the addresses and retry them on the next run instead of dropping them. Kept in memory: linking only runs in the jobs process, and a failed invalidation usually means Redis is unreachable. - When replacing existing links fails, the rollback keeps the old links, which may be for the wrong day; neither the no-prices nor the irregular-count pass would find those txs again. Record their ids in a Redis set (the failure can happen in the app process) and relink them on the next run, removing them once relinked or deleted. Co-Authored-By: Claude Opus 5.5 --- redis/clientInstance.ts | 20 ++++ services/transactionService.ts | 129 +++++++++++++++------ tests/unittests/transactionService.test.ts | 76 ++++++++++++ 3 files changed, 192 insertions(+), 33 deletions(-) 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/transactionService.ts b/services/transactionService.ts index 483c7b3d..83f055f5 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -5,6 +5,7 @@ import { fetchAddressBySubstring, fetchAddressById, fetchAddressesByPaybuttonId 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' @@ -448,6 +449,20 @@ function buildPriceTxConnectionInput (tx: Pick, allPrices: Al ] } +// 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}`) + } +} + /** The fields connectTransactionsListToPrices needs from a tx. */ export type PriceLinkableTransaction = Pick & { address: { networkId: number } @@ -604,6 +619,11 @@ export async function connectTransactionsListToPrices ( } 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) + } } } @@ -621,6 +641,24 @@ export async function connectTransactionsListToPrices ( let connectAllTransactionsToPricesRun: Promise | undefined +// 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() + +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(`[PRICES] 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 @@ -645,50 +683,75 @@ async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started 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 addressesToInvalidate = new Set() 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)) addressesToInvalidate.add(t.address.address) + if (linked.has(t.id)) addressesPendingCacheInvalidation.add(t.address.address) } } + const priceLinkableSelect = { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } as const - 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: { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } - }) - 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}.`) + 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) - console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinkedIds.length} irregular txs linked).`) + const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() + console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) + const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + trackLinked(wrongNumberOfPricesTxs, relinkedIds) - if (addressesToInvalidate.size > 0) { + // Txs whose link replacement failed earlier (possibly in another process). + let pendingRelinked = 0 try { - await CacheSet.addressesSynced([...addressesToInvalidate]) - console.log(`[PRICES] Invalidated caches for ${addressesToInvalidate.size} addresses with newly priced txs.`) + 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 invalidate caches after linking prices: ${err.message as string}`) + 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() } } diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index f34ea6a1..ab5e136c 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: { @@ -650,6 +657,29 @@ describe('connectTransactionsListToPrices chunking', () => { 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', () => { @@ -717,6 +747,52 @@ describe('connectAllTransactionsToPrices', () => { 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(), From 00f9405015556aa207ebfc9af0a44090f76ae4c6 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:12:57 -0700 Subject: [PATCH 5/7] perf: invalidate only changed addresses after sync; log sync timings Every completed startup sync wiped the payment, balance and dashboard caches of every address and user, so each user's next page load rebuilt their whole payment history from the DB. That, plus the startup sync competing for MySQL, is a large part of the slow page loads (long-running loading spinners). - Startup sync now reports which addresses got new txs or had existing txs updated (commitTransactionsBatch -> syncAddresses -> syncMissedTransactions), and invalidateCachesAfterBlockchainSync only clears those addresses and the dashboards of the users who own them (one query via fetchUsersForAddresses). If the changed set is unknown because a network's sync failed part-way, it falls back to clearing everything as before. Addresses whose txs get newly priced are already invalidated by connectAllTransactionsToPrices. - Cache rebuilds log one line per address with how many payments were left out for missing price links, instead of one warning per tx (thousands of lines per rebuild on prod). - Startup sync logs per-address timings (pages, chronik time, time waiting on DB commits) for addresses with new txs or that take over 30s, flags addresses that were never synced and fetch their full history, and ends with a summary plus the 10 slowest addresses, to find why it takes 45+ min. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 4 + jobs/workers.ts | 32 +++++--- redis/paymentCache.ts | 8 +- services/chronikService.ts | 108 ++++++++++++++++++++----- services/transactionService.ts | 9 ++- services/userService.ts | 15 ++++ tests/unittests/chronikService.test.ts | 60 +++++++++++++- tests/unittests/userService.test.ts | 21 +++++ tests/unittests/workers.test.ts | 66 +++++++++++++++ types/chronikTypes.ts | 2 + 10 files changed, 289 insertions(+), 36 deletions(-) create mode 100644 tests/unittests/workers.test.ts diff --git a/constants/index.ts b/constants/index.ts index 8d153d72..290ec3c0 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -296,6 +296,10 @@ export const CHRONIK_FETCH_N_TXS_PER_PAGE = 200 export const INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY = 16 export const TX_EMIT_BATCH_SIZE = 200 // for our generator, not chronik export const DB_COMMIT_BATCH_SIZE = 200 // tamanho dos lotes para commit no DB +// Addresses whose startup sync takes longer than this are logged with timings. +export const SLOW_ADDRESS_SYNC_LOG_THRESHOLD = 30_000 +// How many of the slowest addresses to list at the end of a startup sync. +export const SLOWEST_ADDRESSES_TO_LOG = 10 export const TX_BATCH_POLLING_DELAY = 500 // delay (ms) between polling for new batches of txs to commit to the DB export const TRIGGER_POST_CONCURRENCY = 100 diff --git a/jobs/workers.ts b/jobs/workers.ts index cb576304..2d815b5b 100644 --- a/jobs/workers.ts +++ b/jobs/workers.ts @@ -8,7 +8,7 @@ import { fetchAllAddresses } from 'services/addressService' import { cleanupExpiredClientPayments } from 'services/clientPaymentService' import { multiBlockchainClient } from 'services/chronikService' import { connectAllTransactionsToPrices } from 'services/transactionService' -import { fetchAllUsers } from 'services/userService' +import { fetchAllUsers, fetchUsersForAddresses } from 'services/userService' import * as priceService from 'services/priceService' @@ -38,25 +38,37 @@ const invalidateAddressCaches = async ( } /** - * Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync. - * Rebuild is lazy on the next API request. + * Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync, + * for the addresses whose txs changed and the users who own them. Rebuild is lazy + * on the next API request. Every other cache stays warm: wiping all of them made + * each user's next page load rebuild their whole history from the DB. + * Addresses whose txs were newly linked to prices are invalidated separately by + * connectAllTransactionsToPrices. If the changed set is unknown (the sync failed + * part-way), falls back to invalidating everything. */ -async function invalidateCachesAfterBlockchainSync (): Promise { - console.log('[CACHE]: Invalidating caches after blockchain sync...') - const addresses = await fetchAllAddresses() +export async function invalidateCachesAfterBlockchainSync (changedAddresses: string[] | undefined): Promise { + const invalidateAll = changedAddresses === undefined + const addresses = invalidateAll + ? (await fetchAllAddresses()).map(a => a.address) + : [...new Set(changedAddresses)] + console.log( + invalidateAll + ? `[CACHE]: Invalidating caches for all ${addresses.length} addresses after blockchain sync (changed addresses unknown)...` + : `[CACHE]: Invalidating caches for ${addresses.length} addresses changed by blockchain sync...` + ) let paymentCacheFailures = 0 let balanceCacheFailures = 0 for (let i = 0; i < addresses.length; i += ADDRESS_INVALIDATION_BATCH_SIZE) { const batch = addresses.slice(i, i + ADDRESS_INVALIDATION_BATCH_SIZE) const results = await Promise.all( - batch.map(async (a) => await invalidateAddressCaches(a.address)) + batch.map(async (a) => await invalidateAddressCaches(a)) ) for (const r of results) { paymentCacheFailures += r.paymentFailures balanceCacheFailures += r.balanceFailures } } - const users = await fetchAllUsers() + const users = invalidateAll ? await fetchAllUsers() : await fetchUsersForAddresses(addresses) let dashboardCacheFailures = 0 await Promise.all( users.map(async (u) => { @@ -112,9 +124,9 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet async (job) => { console.log(`job ${job.id as string}: syncing missed prices, transactions and connecting them...`) await priceService.syncPastDaysNewerPrices() - await multiBlockchainClient.syncMissedTransactions() + const changedAddresses = await multiBlockchainClient.syncMissedTransactions() await connectAllTransactionsToPrices() - await invalidateCachesAfterBlockchainSync() + await invalidateCachesAfterBlockchainSync(changedAddresses) }, { connection: redisBullMQ, diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index 3b5d241e..2a226752 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -172,14 +172,17 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: let balance = new Prisma.Decimal(0) let paymentCount = 0 let txCount = 0 + let skippedUnpriced = 0 const txsWithPaybuttonsGenerator = generateTransactionsWithPaybuttonsAndPricesForAddress(address.id) for await (const batch of txsWithPaybuttonsGenerator) { for (const tx of batch) { txCount++ balance = balance.plus(tx.amount) if (tx.amount.gt(0)) { + // Left out until its prices are linked; connectAllTransactionsToPrices + // then invalidates this address so it is rebuilt with the tx. if (tx.prices.length !== N_OF_QUOTES) { - console.warn(`[CACHE] Skipping tx ${tx.hash} — missing price links (${tx.prices.length}/${N_OF_QUOTES})`) + skippedUnpriced++ continue } const payment = generatePaymentFromTx(tx) @@ -192,6 +195,9 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: } const elapsed = ((Date.now() - startTime) / 1000).toFixed(1) console.log(`[CACHE] Cached address ${address.address.slice(0, 20)}...: ${paymentCount} payments, ${txCount} txs in ${elapsed}s`) + if (skippedUnpriced > 0) { + console.warn(`[CACHE] Address ${address.address}: left out ${skippedUnpriced} payments with missing price links.`) + } const info: AddressPaymentInfo = { balance, paymentCount diff --git a/services/chronikService.ts b/services/chronikService.ts index 35133118..64971f3e 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -409,6 +409,27 @@ export class ChronikBlockchainClient { return txsPage.txs } + private logSyncTimings ( + logPrefix: string, + startedAt: number, + timings: Array<{ address: string, ms: number, chronikMs: number, pages: number, newTxs: number }> + ): void { + const totalPages = timings.reduce((sum, t) => sum + t.pages, 0) + const totalChronikMs = timings.reduce((sum, t) => sum + t.chronikMs, 0) + const withNewTxs = timings.filter(t => t.newTxs > 0).length + console.log( + `${logPrefix} <<< Fetched ${timings.length} addresses in ${((Date.now() - startedAt) / 1000).toFixed(1)}s: ` + + `${withNewTxs} with new txs, ${totalPages} chronik pages, ${(totalChronikMs / 1000).toFixed(1)}s total chronik time.` + ) + const slowest = [...timings].sort((a, b) => b.ms - a.ms).slice(0, SLOWEST_ADDRESSES_TO_LOG) + for (const t of slowest) { + console.log( + `${logPrefix} slowest: ${t.address} ${(t.ms / 1000).toFixed(1)}s, ${t.pages} pages, ${t.newTxs} new txs ` + + `(chronik ${(t.chronikMs / 1000).toFixed(1)}s).` + ) + } + } + /* * For each address, fetch pages in parallel (“burst”), * then use the burst’s newest/oldest timestamps to decide whether to continue. @@ -427,6 +448,11 @@ export class ChronikBlockchainClient { const chronikTxs: ChronikTxWithAddress[] = [] const completedAddresses: string[] = [] + // Per-address timings, to find what makes a startup sync slow. "waited" is + // time not spent fetching from chronik: mostly paused while batches are + // committed to the DB. + const fetchStartedAt = Date.now() + const addressTimings: Array<{ address: string, ms: number, chronikMs: number, pages: number, newTxs: number }> = [] let producersPaused = false const producerPauseWaiters: Array<() => void> = [] @@ -494,6 +520,9 @@ export class ChronikBlockchainClient { let nextBurstBasePageIndex = 0 let hasReachedStoppingCondition = false let newTxs = 0 + const addressStartedAt = Date.now() + let chronikMs = 0 + let pagesFetched = 0 try { while (!hasReachedStoppingCondition) { @@ -502,11 +531,19 @@ export class ChronikBlockchainClient { const pageIndex = nextBurstBasePageIndex let pageTxs: Tx[] = [] + const pageStartedAt = Date.now() try { pageTxs = await this.getPaginatedTxs(address.address, pageIndex, CHRONIK_FETCH_N_TXS_PER_PAGE) + pagesFetched++ } catch (err: any) { console.warn(`${addrLogPrefix} page=${pageIndex} failed: ${err.message as string}`) pageTxs = [] + } finally { + chronikMs += Date.now() - pageStartedAt + } + + if (pageIndex === 0 && pageTxs.length > 0 && lastSyncedTimestampSeconds === 0) { + console.log(`${addrLogPrefix} never synced (no lastSynced), fetching its full history.`) } if (pageIndex === 0 && pageTxs.length === 0) { @@ -547,12 +584,17 @@ export class ChronikBlockchainClient { } newTxs += newTxsInThisPage } - if (newTxs > 0) { - console.log(`${addrLogPrefix} ${newTxs} new txs.`) - } } catch (err: any) { console.error(`${logPrefix}: address job failed: ${err.message as string}`) } finally { + const ms = Date.now() - addressStartedAt + addressTimings.push({ address: address.address, ms, chronikMs, pages: pagesFetched, newTxs }) + if (newTxs > 0 || ms > SLOW_ADDRESS_SYNC_LOG_THRESHOLD) { + console.log( + `${addrLogPrefix} ${newTxs} new txs, ${pagesFetched} pages in ${(ms / 1000).toFixed(1)}s ` + + `(chronik ${(chronikMs / 1000).toFixed(1)}s, waited ${((ms - chronikMs) / 1000).toFixed(1)}s).` + ) + } completedAddresses.push(address.address) } } @@ -625,6 +667,8 @@ export class ChronikBlockchainClient { await Promise.all(Array.from(activeWorkers)) } + this.logSyncTimings(logPrefix, fetchStartedAt, addressTimings) + // Final TX flush after all addresses processed if (chronikTxs.length >= TX_EMIT_BATCH_SIZE) { yield * runDrainCycle() @@ -1099,7 +1143,7 @@ export class ChronikBlockchainClient { commitTuples: Array<{ row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string }>, productionAddressesIds: string[], runTriggers: boolean - ): Promise { + ): Promise { const rows = commitTuples.map(p => p.row) const rowsToUpsert = await filterRowsNeedingCreateMany(rows) const syncResult = await createManyTransactionsForSync(rowsToUpsert) @@ -1108,6 +1152,15 @@ export class ChronikBlockchainClient { `${commitTuples.length}` ) + // Addresses whose cached payments/balance are now stale. + const addressStringById = new Map(commitTuples.map(t => [t.row.addressId, t.addressString])) + const changedAddresses = [...new Set([ + ...syncResult.inserted.map(t => t.addressId), + ...syncResult.updatedAddressIds + ])] + .map(id => addressStringById.get(id)) + .filter((a): a is string => a !== undefined) + // 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. @@ -1190,6 +1243,7 @@ export class ChronikBlockchainClient { } } } + return changedAddresses } public async syncAddresses (addresses: Address[], runTriggers = false): Promise { @@ -1210,6 +1264,11 @@ export class ChronikBlockchainClient { interface RowWithRaw { row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string } let toCommit: RowWithRaw[] = [] + const changedAddresses = new Set() + const commit = async (tuples: RowWithRaw[]): Promise => { + const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) + changed.forEach(a => changedAddresses.add(a)) + } try { const pfx = `${this.CHRONIK_MSG_PREFIX}[PARALLEL FETCHING]` @@ -1225,11 +1284,7 @@ export class ChronikBlockchainClient { if (batch.phase === 'drain-complete') { if (toCommit.length > 0) { const remainder = toCommit.splice(0) - await this.commitTransactionsBatch( - remainder, - productionAddressesIds, - runTriggers - ) + await commit(remainder) remainder.length = 0 } continue @@ -1257,7 +1312,7 @@ export class ChronikBlockchainClient { if (toCommit.length >= DB_COMMIT_BATCH_SIZE) { const commitPairs = toCommit.splice(0, DB_COMMIT_BATCH_SIZE) - await this.commitTransactionsBatch(commitPairs, productionAddressesIds, runTriggers) + await commit(commitPairs) // Clear commitPairs commitPairs.length = 0 } @@ -1275,7 +1330,7 @@ export class ChronikBlockchainClient { // final DB flush (se sobrou menos que DB_COMMIT_BATCH_SIZE) if (toCommit.length > 0) { - await this.commitTransactionsBatch(toCommit, productionAddressesIds, runTriggers) + await commit(toCommit) toCommit = [] } @@ -1297,13 +1352,17 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX} Finished syncing ${total} txs for ${addresses.length} addresses with ${failed.length} errors.`) console.timeEnd(`${this.CHRONIK_MSG_PREFIX} syncAddresses`) - return { failedAddressesWithErrors, successfulAddressesWithCount } + return { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses: [...changedAddresses] } } - public async syncMissedTransactions (): Promise { + /** + * Returns the addresses whose txs changed (new or updated), or undefined if + * the sync failed in a way that leaves that unknown. + */ + public async syncMissedTransactions (): Promise { const addresses = await fetchAllAddressesForNetworkId(this.networkId) try { - const { failedAddressesWithErrors, successfulAddressesWithCount } = await this.syncAddresses(addresses, true) + const { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses } = await this.syncAddresses(addresses, true) Object.keys(failedAddressesWithErrors).forEach((addr) => { console.error(`${this.CHRONIK_MSG_PREFIX}: When syncing missing addresses for address ${addr} encountered error: ${failedAddressesWithErrors[addr]}`) }) @@ -1313,8 +1372,10 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX}:> ${addr} — ${successfulAddressesWithCount[addr]}.`) } }) + return changedAddresses ?? [] } catch (err: any) { console.error(`${this.CHRONIK_MSG_PREFIX}: ERROR: (skipping anyway) initial missing transactions sync failed: ${err.message as string} ${err.stack as string}`) + return undefined } } @@ -1494,16 +1555,19 @@ class MultiBlockchainClient { public async syncAddresses (addresses: Address[], runTriggers = false): Promise { let failedAddressesWithErrors: KeyValueT = {} let successfulAddressesWithCount: KeyValueT = {} + const changedAddresses: string[] = [] for (const networkSlug of Object.keys(this.clients)) { const thisNetworkAddresses = addresses.filter(a => a.networkId === NETWORK_IDS_FROM_SLUGS[networkSlug]) const ret = await this.clients[networkSlug as MainNetworkSlugsType].syncAddresses(thisNetworkAddresses, runTriggers) failedAddressesWithErrors = { ...failedAddressesWithErrors, ...ret.failedAddressesWithErrors } successfulAddressesWithCount = { ...successfulAddressesWithCount, ...ret.successfulAddressesWithCount } + changedAddresses.push(...(ret.changedAddresses ?? [])) } return { failedAddressesWithErrors, - successfulAddressesWithCount + successfulAddressesWithCount, + changedAddresses } } @@ -1520,10 +1584,16 @@ class MultiBlockchainClient { return await this.clients[networkSlug as MainNetworkSlugsType].getBalance(address) } - public async syncMissedTransactions (): Promise { + /** + * Returns the addresses whose txs changed during the sync, or undefined if + * that is unknown for any network (callers should then assume all changed). + */ + public async syncMissedTransactions (): Promise { await this.waitForStart() - await this.clients.bitcoincash.syncMissedTransactions() - await this.clients.ecash.syncMissedTransactions() + const bch = await this.clients.bitcoincash.syncMissedTransactions() + const xec = await this.clients.ecash.syncMissedTransactions() + if (bch === undefined || xec === undefined) return undefined + return [...bch, ...xec] } public async syncAndSubscribeAddresses (addresses: Address[]): Promise { diff --git a/services/transactionService.ts b/services/transactionService.ts index 83f055f5..21e1b7b2 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -838,6 +838,8 @@ export interface SyncPersistedTransaction { export interface CreateManyTransactionsSyncResult { insertedCount: number inserted: SyncPersistedTransaction[] + // Addresses of pre-existing txs whose confirmed/timestamp/orphaned changed. + updatedAddressIds: string[] } interface PersistManyTransactionRowsResult { @@ -1106,13 +1108,14 @@ export async function createManyTransactionsForSync ( transactionsData: Prisma.TransactionUncheckedCreateInput[] ): Promise { if (transactionsData.length === 0) { - return { insertedCount: 0, inserted: [] } + return { insertedCount: 0, inserted: [], updatedAddressIds: [] } } - const { inserted } = await persistManyTransactionRows(transactionsData) + const { inserted, updated } = await persistManyTransactionRows(transactionsData) return { insertedCount: inserted.length, - inserted + inserted, + updatedAddressIds: [...new Set(updated.map(t => t.addressId))] } } diff --git a/services/userService.ts b/services/userService.ts index cf8b6fa5..a68b9cdc 100644 --- a/services/userService.ts +++ b/services/userService.ts @@ -124,6 +124,21 @@ export async function fetchUsersForAddress (addressString: string): Promise { + if (addressStrings.length === 0) return [] + return await prisma.userProfile.findMany({ + where: { + addresses: { + some: { + address: { + address: { in: addressStrings } + } + } + } + } + }) +} + export async function isUserAdmin (id: string): Promise { const user = await prisma.userProfile.findFirst({ where: { diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 1b6bf12d..6fc4ed3e 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -65,7 +65,8 @@ jest.mock('../../services/transactionService', () => ({ createManyTransactions: jest.fn(), createManyTransactionsForSync: jest.fn(async () => ({ insertedCount: 0, - inserted: [] + inserted: [], + updatedAddressIds: [] })), filterRowsNeedingCreateMany: jest.fn(async (rows: unknown[]) => rows), deleteTransactions: jest.fn(), @@ -1728,7 +1729,7 @@ describe('commitTransactionsBatch price linking', () => { beforeEach(() => { process.env.WS_AUTH_KEY = 'test-auth-key' - ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted }) + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted, updatedAddressIds: [] }) jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) jest.spyOn(console, 'log').mockImplementation(() => {}) }) @@ -1754,7 +1755,60 @@ describe('commitTransactionsBatch price linking', () => { const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) const client = new ChronikBlockchainClient('ecash') - await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toBeUndefined() + await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toEqual(['ecash:addr-1']) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down')) }) }) + +describe('changed addresses reported by the sync', () => { + beforeEach(() => { + process.env.WS_AUTH_KEY = 'test-auth-key' + jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) + jest.spyOn(console, 'log').mockImplementation(() => {}) + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue([]) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('commitTransactionsBatch returns the addresses with inserted or updated txs', async () => { + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ + insertedCount: 1, + inserted: [{ id: 'tx-1', hash: 'h1', addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }], + updatedAddressIds: ['addr-2'] + }) + const client = new ChronikBlockchainClient('ecash') + const tuple = (addressId: string, hash: string): any => ({ + row: { hash, addressId, timestamp: 1700000000, amount: 1 }, + raw: {}, + addressString: `ecash:${addressId}` + }) + + const changed = await (client as any).commitTransactionsBatch( + [tuple('addr-1', 'h1'), tuple('addr-2', 'h2'), tuple('addr-3', 'h3')], + [], + false + ) + + expect(changed.sort()).toEqual(['ecash:addr-1', 'ecash:addr-2']) + }) + + it('MultiBlockchainClient.syncMissedTransactions merges both networks', async () => { + const clients = (multiBlockchainClient as any).clients + jest.spyOn(multiBlockchainClient, 'waitForStart').mockResolvedValue() + jest.spyOn(clients.bitcoincash, 'syncMissedTransactions').mockResolvedValue(['bitcoincash:a']) + jest.spyOn(clients.ecash, 'syncMissedTransactions').mockResolvedValue(['ecash:b']) + + await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toEqual(['bitcoincash:a', 'ecash:b']) + }) + + it('MultiBlockchainClient.syncMissedTransactions is undefined when a network sync failed', async () => { + const clients = (multiBlockchainClient as any).clients + jest.spyOn(multiBlockchainClient, 'waitForStart').mockResolvedValue() + jest.spyOn(clients.bitcoincash, 'syncMissedTransactions').mockResolvedValue(undefined) + jest.spyOn(clients.ecash, 'syncMissedTransactions').mockResolvedValue(['ecash:b']) + + await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toBeUndefined() + }) +}) diff --git a/tests/unittests/userService.test.ts b/tests/unittests/userService.test.ts index bf74df29..14126162 100644 --- a/tests/unittests/userService.test.ts +++ b/tests/unittests/userService.test.ts @@ -126,3 +126,24 @@ describe('user trigger limits and pro logic', () => { expect(userService.getUserRemainingTriggerCreditsLimit(user, 'PostData')).toBe(8) }) }) + +describe('fetchUsersForAddresses', () => { + it('fetches the owners of any of the given addresses in one query', async () => { + prisma.userProfile.findMany = prismaMock.userProfile.findMany + prismaMock.userProfile.findMany.mockResolvedValue([mockedUserProfile]) + + const users = await userService.fetchUsersForAddresses(['ecash:a', 'ecash:b']) + + expect(users).toEqual([mockedUserProfile]) + expect(prismaMock.userProfile.findMany).toHaveBeenCalledWith({ + where: { addresses: { some: { address: { address: { in: ['ecash:a', 'ecash:b'] } } } } } + }) + }) + + it('does not query when no address is given', async () => { + prisma.userProfile.findMany = prismaMock.userProfile.findMany + + await expect(userService.fetchUsersForAddresses([])).resolves.toEqual([]) + expect(prismaMock.userProfile.findMany).not.toHaveBeenCalled() + }) +}) diff --git a/tests/unittests/workers.test.ts b/tests/unittests/workers.test.ts new file mode 100644 index 00000000..84829a5b --- /dev/null +++ b/tests/unittests/workers.test.ts @@ -0,0 +1,66 @@ +import { invalidateCachesAfterBlockchainSync } from '../../jobs/workers' +import { clearPaymentCacheForAddress } from '../../redis/paymentCache' +import { clearBalanceCache } from '../../redis/balanceCache' +import { clearDashboardCache } from '../../redis/dashboardCache' +import { fetchAllAddresses } from '../../services/addressService' +import { fetchAllUsers, fetchUsersForAddresses } from '../../services/userService' + +jest.mock('bullmq', () => ({ Worker: jest.fn() })) +jest.mock('../../redis/clientInstance', () => ({ redisBullMQ: {} })) +jest.mock('../../redis/paymentCache', () => ({ clearPaymentCacheForAddress: jest.fn() })) +jest.mock('../../redis/balanceCache', () => ({ clearBalanceCache: jest.fn() })) +jest.mock('../../redis/dashboardCache', () => ({ clearDashboardCache: jest.fn() })) +jest.mock('../../services/addressService', () => ({ fetchAllAddresses: jest.fn() })) +jest.mock('../../services/userService', () => ({ + fetchAllUsers: jest.fn(), + fetchUsersForAddresses: jest.fn() +})) +jest.mock('../../services/clientPaymentService', () => ({ cleanupExpiredClientPayments: jest.fn() })) +jest.mock('../../services/chronikService', () => ({ multiBlockchainClient: {} })) +jest.mock('../../services/transactionService', () => ({ connectAllTransactionsToPrices: jest.fn() })) +jest.mock('../../services/priceService', () => ({})) + +describe('invalidateCachesAfterBlockchainSync', () => { + beforeEach(() => { + jest.clearAllMocks() + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('only clears the changed addresses and the dashboards of their users', async () => { + ;(fetchUsersForAddresses as jest.Mock).mockResolvedValue([{ id: 'user-1' }]) + + await invalidateCachesAfterBlockchainSync(['ecash:a', 'ecash:b', 'ecash:a']) + + expect(fetchAllAddresses).not.toHaveBeenCalled() + expect(fetchAllUsers).not.toHaveBeenCalled() + expect((clearPaymentCacheForAddress as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:b']) + expect((clearBalanceCache as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:b']) + expect(fetchUsersForAddresses).toHaveBeenCalledWith(['ecash:a', 'ecash:b']) + expect(clearDashboardCache).toHaveBeenCalledTimes(1) + expect(clearDashboardCache).toHaveBeenCalledWith('user-1') + }) + + it('clears nothing when no address changed', async () => { + ;(fetchUsersForAddresses as jest.Mock).mockResolvedValue([]) + + await invalidateCachesAfterBlockchainSync([]) + + expect(clearPaymentCacheForAddress).not.toHaveBeenCalled() + expect(clearDashboardCache).not.toHaveBeenCalled() + }) + + it('falls back to clearing every cache when the changed addresses are unknown', async () => { + ;(fetchAllAddresses as jest.Mock).mockResolvedValue([{ address: 'ecash:a' }, { address: 'ecash:c' }]) + ;(fetchAllUsers as jest.Mock).mockResolvedValue([{ id: 'user-1' }, { id: 'user-2' }]) + + await invalidateCachesAfterBlockchainSync(undefined) + + expect((clearPaymentCacheForAddress as jest.Mock).mock.calls.map(c => c[0] as string).sort((a, b) => a.localeCompare(b))).toEqual(['ecash:a', 'ecash:c']) + expect(fetchUsersForAddresses).not.toHaveBeenCalled() + expect(clearDashboardCache).toHaveBeenCalledTimes(2) + }) +}) diff --git a/types/chronikTypes.ts b/types/chronikTypes.ts index 82e47b86..fbfb8046 100644 --- a/types/chronikTypes.ts +++ b/types/chronikTypes.ts @@ -50,4 +50,6 @@ export interface SubscriptionReturn { export interface SyncAndSubscriptionReturn { failedAddressesWithErrors: KeyValueT successfulAddressesWithCount: KeyValueT + // Addresses that got new txs, or existing txs updated, during the sync. + changedAddresses?: string[] } From 9bc157166a6bb6a85db0925db076e9a42d7bcfc9 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:50:05 -0700 Subject: [PATCH 6/7] fix: invalidate caches per sync batch and only report rows this sync created Review follow-ups: - After a sync batch's new txs are linked to prices, drop the caches of their addresses right away. The bulk path never adds txs to cached payments, and the only other invalidation is at the end of the sync, which an interrupted sync (the prod case) never reaches. Uses a shared invalidateCachesForAddresses that keeps failed addresses queued for retry. - persistManyTransactionRows looked created rows up by (hash, addressId) after a skipDuplicates insert, so when two syncs inserted the same tx concurrently both reported it as inserted (triggers and the seed-file append ran twice). Generate the ids in the app and report only rows that carry them. Co-Authored-By: Claude Opus 5.5 --- services/chronikService.ts | 18 ++++++-- services/transactionService.ts | 28 +++++++++---- tests/unittests/chronikService.test.ts | 25 ++++++++++- tests/unittests/transactionService.test.ts | 49 ++++++++++++++++++++++ 4 files changed, 107 insertions(+), 13 deletions(-) diff --git a/services/chronikService.ts b/services/chronikService.ts index 35133118..fa6223ef 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -17,7 +17,8 @@ import { getSimplifiedTransactions, getSimplifiedTrasaction, connectTransactionsToPricesForAddresses, - connectTransactionsListToPrices + connectTransactionsListToPrices, + invalidateCachesForAddresses } from './transactionService' import { CacheSet } from 'redis/index' import { @@ -1113,10 +1114,21 @@ export class ChronikBlockchainClient { // A failure here is not fatal: connectAllTransactionsToPrices retries later. if (syncResult.inserted.length > 0) { try { - await connectTransactionsListToPrices( + 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}`) } diff --git a/services/transactionService.ts b/services/transactionService.ts index 83f055f5..5e5a56f3 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -11,6 +11,7 @@ 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 = { @@ -647,13 +648,23 @@ let connectAllTransactionsToPricesRun: Promise | undefined // 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(`[PRICES] Invalidated caches for ${addresses.length} addresses with newly priced txs.`) + 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}`) } @@ -984,23 +995,24 @@ async function persistManyTransactionRows ( let updatedCount = 0 if (newTxs.length > 0) { + // 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 }) diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 1b6bf12d..ac643180 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -10,7 +10,7 @@ import { } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' import { fetchAddressesArray } from '../../services/addressService' -import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync } from '../../services/transactionService' +import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync, invalidateCachesForAddresses } from '../../services/transactionService' import prisma from '../../prisma-local/clientInstance' import { executeAddressTriggers } from '../../services/triggerService' import { CacheSet } from '../../redis/index' @@ -75,7 +75,8 @@ jest.mock('../../services/transactionService', () => ({ getSimplifiedTrasaction: jest.fn(), connectAllTransactionsToPrices: jest.fn(), connectTransactionsToPricesForAddresses: jest.fn(), - connectTransactionsListToPrices: jest.fn() + connectTransactionsListToPrices: jest.fn(), + invalidateCachesForAddresses: jest.fn() })) jest.mock('../../redis/index', () => ({ @@ -1749,6 +1750,26 @@ describe('commitTransactionsBatch price linking', () => { ) }) + 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(() => {}) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index ab5e136c..fd765d55 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -832,3 +832,52 @@ describe('retryOnTransactionTimeout', () => { 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() + }) +}) From 59d9f7994c8b9b3c3c90501bb1b9d583b19bf8bd Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 23:22:28 -0700 Subject: [PATCH 7/7] fix: treat failed sync commits as unknown scope; invalidate updated addresses per batch A commit that throws may already have persisted rows, so syncAddresses now reports changedAddresses as undefined in that case and the worker falls back to invalidating everything. Addresses whose existing txs were updated are now invalidated per batch, so an interrupted sync doesn't leave them stale. Co-Authored-By: Claude Opus 5.5 --- services/chronikService.ts | 58 ++++++++++++++------ tests/unittests/chronikService.test.ts | 74 ++++++++++++++++++++++++++ types/chronikTypes.ts | 1 + 3 files changed, 116 insertions(+), 17 deletions(-) diff --git a/services/chronikService.ts b/services/chronikService.ts index 3506983e..f8199d6b 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1165,27 +1165,35 @@ export class ChronikBlockchainClient { // 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. + let linkedAddresses: string[] = [] 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 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) - } + linkedAddresses = syncResult.inserted + .filter(t => linkedIds.has(t.id)) + .map(t => addressStringById.get(t.addressId)) + .filter((a): a is string => a !== undefined) } catch (err: any) { console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to link prices for ${syncResult.inserted.length} synced txs: ${err.message as string}`) } } + // The bulk path doesn't update cached payments, so drop the caches of addresses + // with newly priced or updated txs now instead of waiting for the end of the + // sync, which an interrupted sync never reaches (and the next sync won't see + // these txs as changed again). Txs left unpriced are invalidated by + // connectAllTransactionsToPrices once it links them. + const updatedAddresses = syncResult.updatedAddressIds + .map(id => addressStringById.get(id)) + .filter((a): a is string => a !== undefined) + const addressesToInvalidate = [...new Set([...linkedAddresses, ...updatedAddresses])] + if (addressesToInvalidate.length > 0) { + await invalidateCachesForAddresses(addressesToInvalidate) + } + const createdForProd = syncResult.inserted.filter(t => productionAddressesIds.includes(t.addressId) ) @@ -1263,7 +1271,7 @@ export class ChronikBlockchainClient { const productionAddressesIds = productionAddresses.filter(a => a.networkId === this.networkId).map(a => a.id) if (addresses.length === 0) { - return { failedAddressesWithErrors, successfulAddressesWithCount } + return { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses: [] } } console.log(`${this.CHRONIK_MSG_PREFIX} Syncing ${addresses.length} addresses...`) @@ -1276,9 +1284,18 @@ export class ChronikBlockchainClient { interface RowWithRaw { row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string } let toCommit: RowWithRaw[] = [] const changedAddresses = new Set() + // A commit that throws may have persisted some rows (inserts and update + // groups commit separately, and follow-up work runs after both), so which + // addresses changed is then unknown. + let changedAddressesUnknown = false const commit = async (tuples: RowWithRaw[]): Promise => { - const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) - changed.forEach(a => changedAddresses.add(a)) + try { + const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) + changed.forEach(a => changedAddresses.add(a)) + } catch (err) { + changedAddressesUnknown = true + throw err + } } try { @@ -1363,7 +1380,11 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX} Finished syncing ${total} txs for ${addresses.length} addresses with ${failed.length} errors.`) console.timeEnd(`${this.CHRONIK_MSG_PREFIX} syncAddresses`) - return { failedAddressesWithErrors, successfulAddressesWithCount, changedAddresses: [...changedAddresses] } + return { + failedAddressesWithErrors, + successfulAddressesWithCount, + changedAddresses: changedAddressesUnknown ? undefined : [...changedAddresses] + } } /** @@ -1383,7 +1404,7 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX}:> ${addr} — ${successfulAddressesWithCount[addr]}.`) } }) - return changedAddresses ?? [] + return changedAddresses } catch (err: any) { console.error(`${this.CHRONIK_MSG_PREFIX}: ERROR: (skipping anyway) initial missing transactions sync failed: ${err.message as string} ${err.stack as string}`) return undefined @@ -1566,14 +1587,17 @@ class MultiBlockchainClient { public async syncAddresses (addresses: Address[], runTriggers = false): Promise { let failedAddressesWithErrors: KeyValueT = {} let successfulAddressesWithCount: KeyValueT = {} - const changedAddresses: string[] = [] + let changedAddresses: string[] | undefined = [] for (const networkSlug of Object.keys(this.clients)) { const thisNetworkAddresses = addresses.filter(a => a.networkId === NETWORK_IDS_FROM_SLUGS[networkSlug]) const ret = await this.clients[networkSlug as MainNetworkSlugsType].syncAddresses(thisNetworkAddresses, runTriggers) failedAddressesWithErrors = { ...failedAddressesWithErrors, ...ret.failedAddressesWithErrors } successfulAddressesWithCount = { ...successfulAddressesWithCount, ...ret.successfulAddressesWithCount } - changedAddresses.push(...(ret.changedAddresses ?? [])) + // Unknown for one network means unknown overall. + changedAddresses = (changedAddresses === undefined || ret.changedAddresses === undefined) + ? undefined + : [...changedAddresses, ...ret.changedAddresses] } return { failedAddressesWithErrors, diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index e8dcb0f2..5490c726 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -1815,6 +1815,80 @@ describe('changed addresses reported by the sync', () => { expect(changed.sort()).toEqual(['ecash:addr-1', 'ecash:addr-2']) }) + it('commitTransactionsBatch invalidates addresses with updated txs right away', async () => { + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ + insertedCount: 0, + inserted: [], + updatedAddressIds: ['addr-2'] + }) + const invalidate = (invalidateCachesForAddresses as jest.Mock).mockReset() + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch( + [{ row: { hash: 'h2', addressId: 'addr-2', timestamp: 1700000000, amount: 1 }, raw: {}, addressString: 'ecash:addr-2' }], + [], + false + ) + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-2']) + }) + + describe('syncAddresses', () => { + const address = { id: 'addr-1', address: 'ecash:addr-1', networkId: 1 } as any + const setupSync = (): ChronikBlockchainClient => { + const client = new ChronikBlockchainClient('ecash') + jest.spyOn(client as any, 'fetchLatestTxsForAddresses').mockImplementation(async function * () { + yield { phase: 'tx-drain', chronikTxs: [{ tx: {}, address }], addressesSynced: [] } + }) + jest.spyOn(client as any, 'getTransactionFromChronikTransaction').mockReturnValue( + { hash: 'h1', addressId: 'addr-1', timestamp: 1700000000, amount: 1 } + ) + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ + insertedCount: 1, + inserted: [{ id: 'tx-1', hash: 'h1', addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }], + updatedAddressIds: [] + }) + return client + } + + it('reports the changed addresses of a completed sync', async () => { + const client = setupSync() + + const result = await client.syncAddresses([address]) + + expect(result.changedAddresses).toEqual(['ecash:addr-1']) + }) + + it('reports changed addresses as unknown when a commit fails after the DB write', async () => { + jest.spyOn(console, 'error').mockImplementation(() => {}) + const client = setupSync() + // Runs after createManyTransactionsForSync has persisted the batch. + jest.spyOn(prisma.address, 'findMany').mockRejectedValue(new Error('db gone')) + + const result = await client.syncAddresses([address]) + + expect(createManyTransactionsForSync).toHaveBeenCalled() + expect(result.changedAddresses).toBeUndefined() + }) + + it('syncMissedTransactions propagates an unknown scope instead of reporting no changes', async () => { + const client = new ChronikBlockchainClient('ecash') + jest.spyOn(client, 'syncAddresses').mockResolvedValue({ + failedAddressesWithErrors: {}, + successfulAddressesWithCount: {}, + changedAddresses: undefined + }) + + await expect(client.syncMissedTransactions()).resolves.toBeUndefined() + }) + + it('returns no changes when there is nothing to sync', async () => { + const client = new ChronikBlockchainClient('ecash') + + await expect(client.syncAddresses([])).resolves.toMatchObject({ changedAddresses: [] }) + }) + }) + it('MultiBlockchainClient.syncMissedTransactions merges both networks', async () => { const clients = (multiBlockchainClient as any).clients jest.spyOn(multiBlockchainClient, 'waitForStart').mockResolvedValue() diff --git a/types/chronikTypes.ts b/types/chronikTypes.ts index fbfb8046..b50753aa 100644 --- a/types/chronikTypes.ts +++ b/types/chronikTypes.ts @@ -51,5 +51,6 @@ export interface SyncAndSubscriptionReturn { failedAddressesWithErrors: KeyValueT successfulAddressesWithCount: KeyValueT // Addresses that got new txs, or existing txs updated, during the sync. + // Undefined when that is unknown (a commit failed after it may have written). changedAddresses?: string[] }