diff --git a/constants/index.ts b/constants/index.ts index 8d153d728..290ec3c06 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 cb5763040..2d815b5b9 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 3b5d241ef..2a2267524 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 fa6223efc..f8199d6be 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 { @@ -410,6 +410,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. @@ -428,6 +449,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> = [] @@ -495,6 +521,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) { @@ -503,11 +532,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) { @@ -548,12 +585,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) } } @@ -626,6 +668,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() @@ -1100,7 +1144,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) @@ -1109,31 +1153,47 @@ 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. + 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 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) - } + 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) ) @@ -1202,6 +1262,7 @@ export class ChronikBlockchainClient { } } } + return changedAddresses } public async syncAddresses (addresses: Address[], runTriggers = false): Promise { @@ -1210,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...`) @@ -1222,6 +1283,20 @@ 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 => { + try { + const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers) + changed.forEach(a => changedAddresses.add(a)) + } catch (err) { + changedAddressesUnknown = true + throw err + } + } try { const pfx = `${this.CHRONIK_MSG_PREFIX}[PARALLEL FETCHING]` @@ -1237,11 +1312,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 @@ -1269,7 +1340,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 } @@ -1287,7 +1358,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 = [] } @@ -1309,13 +1380,21 @@ 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: changedAddressesUnknown ? undefined : [...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]}`) }) @@ -1325,8 +1404,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 } } @@ -1506,16 +1587,22 @@ class MultiBlockchainClient { public async syncAddresses (addresses: Address[], runTriggers = false): Promise { let failedAddressesWithErrors: KeyValueT = {} let successfulAddressesWithCount: KeyValueT = {} + 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 } + // Unknown for one network means unknown overall. + changedAddresses = (changedAddresses === undefined || ret.changedAddresses === undefined) + ? undefined + : [...changedAddresses, ...ret.changedAddresses] } return { failedAddressesWithErrors, - successfulAddressesWithCount + successfulAddressesWithCount, + changedAddresses } } @@ -1532,10 +1619,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 5e5a56f3d..ea68264cb 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -849,6 +849,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 { @@ -1118,13 +1120,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 cf8b6fa59..a68b9cdc6 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 ac643180c..5490c7262 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(), @@ -1729,7 +1730,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(() => {}) }) @@ -1775,7 +1776,134 @@ 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('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() + 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 bf74df29c..141261627 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 000000000..84829a5b5 --- /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 82e47b866..b50753aa1 100644 --- a/types/chronikTypes.ts +++ b/types/chronikTypes.ts @@ -50,4 +50,7 @@ export interface SubscriptionReturn { 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[] }