diff --git a/redis/index.ts b/redis/index.ts index d2048170..a2b64d56 100644 --- a/redis/index.ts +++ b/redis/index.ts @@ -4,7 +4,7 @@ import { TransactionsWithPaybuttonsAndPrices } from 'services/transactionService import { fetchUsersForAddress } from 'services/userService' import { cacheBalanceForAddress, clearBalanceCache, getBalanceForAddress, updateBalanceCacheFromTx } from './balanceCache' import { clearDashboardCache, getUserDashboardData } from './dashboardCache' -import { appendPaybuttonToAddressesCache, cacheGroupedPayments, cacheManyTxs, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' +import { appendPaybuttonToAddressesCache, cacheGroupedPayments, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' import { DashboardData, Payment } from './types' import { Address } from '@prisma/client' @@ -48,6 +48,23 @@ export const CacheSet = { await clearBalanceCache(addr) } }, + // After a bulk (on-demand) sync committed txs for these addresses without + // touching the cache: drop their payment, balance and users' dashboard caches + // so they are rebuilt from the DB, now including the synced txs. + addressesSynced: async (addressStringList: string[]): Promise => { + const userIds = new Set() + for (const addressString of addressStringList) { + await clearPaymentCacheForAddress(addressString) + await clearBalanceCache(addressString) + const users = await fetchUsersForAddress(addressString) + users.forEach(u => userIds.add(u.id)) + } + await Promise.all( + [...userIds].map(async id => { + await clearDashboardCache(id) + }) + ) + }, paybuttonCreation: async ({ paybutton, addressStringList, userId }: PaybuttonCreationParams): Promise => { await appendPaybuttonToAddressesCache( addressStringList, diff --git a/services/chronikService.ts b/services/chronikService.ts index 3197ab14..1f77f7a7 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -15,8 +15,10 @@ import { markTransactionsOrphaned, upsertTransaction, getSimplifiedTransactions, - getSimplifiedTrasaction + getSimplifiedTrasaction, + connectTransactionsToPricesForAddresses } from './transactionService' +import { CacheSet } from 'redis/index' import { updateClientPaymentStatus, getClientPayment @@ -1511,7 +1513,28 @@ class MultiBlockchainClient { public async syncAndSubscribeAddresses (addresses: Address[]): Promise { await this.subscribeAddresses(addresses) - return await this.syncAddresses(addresses) + const result = await this.syncAddresses(addresses) + await this.finalizeOnDemandSync(addresses) + return result + } + + // syncAddresses commits through the bulk path, which defers price linking and + // cache updates to the sync job. On-demand syncs (new paybutton/address, client + // payment) run outside that job, so link prices and drop stale caches here — + // otherwise the synced txs stay unpriced and missing from payments until the + // next restart, and a cache rebuilt mid-sync stays partial. + private async finalizeOnDemandSync (addresses: Address[]): Promise { + if (addresses.length === 0) return + try { + await connectTransactionsToPricesForAddresses(addresses.map(a => a.id)) + } catch (err: any) { + console.error(`[CHRONIK]: Failed to link prices after syncing ${addresses.length} addresses: ${err.message as string}`) + } + try { + await CacheSet.addressesSynced(addresses.map(a => a.address)) + } catch (err: any) { + console.error(`[CHRONIK]: Failed to invalidate caches after syncing ${addresses.length} addresses: ${err.message as string}`) + } } public async destroy (): Promise { diff --git a/services/transactionService.ts b/services/transactionService.ts index 8be87155..90d54865 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -633,6 +633,36 @@ export async function connectAllTransactionsToPrices (): Promise { console.log('[PRICES] Finished connecting txs to prices.') } +/** + * 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. + */ +export async function connectTransactionsToPricesForAddresses (addressIds: string[]): Promise { + if (addressIds.length === 0) return + const noPricesTxs = await prisma.transaction.findMany({ + where: { + addressId: { in: addressIds }, + prices: { none: {} } + }, + include: includeNetwork + }) + const irregular = await prisma.pricesOnTransactions.groupBy({ + by: ['transactionId'], + where: { transaction: { addressId: { in: addressIds } } }, + _count: { transactionId: true }, + having: { transactionId: { _count: { lt: N_OF_QUOTES } } } + }) + const irregularTxs = irregular.length === 0 + ? [] + : await prisma.transaction.findMany({ + where: { id: { in: irregular.map(g => g.transactionId) } }, + include: includeNetwork + }) + await connectTransactionsListToPrices([...noPricesTxs, ...irregularTxs]) +} + interface ExistingTxSnapshot { confirmed: boolean timestamp: number diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index f9e34232..9f43d70e 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -10,8 +10,9 @@ import { } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' import { fetchAddressesArray } from '../../services/addressService' -import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction } from '../../services/transactionService' +import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses } from '../../services/transactionService' import { executeAddressTriggers } from '../../services/triggerService' +import { CacheSet } from '../../redis/index' process.env.WS_AUTH_KEY = 'test-auth-key' @@ -71,7 +72,14 @@ jest.mock('../../services/transactionService', () => ({ upsertTransaction: jest.fn(), getSimplifiedTransactions: jest.fn(), getSimplifiedTrasaction: jest.fn(), - connectAllTransactionsToPrices: jest.fn() + connectAllTransactionsToPrices: jest.fn(), + connectTransactionsToPricesForAddresses: jest.fn() +})) + +jest.mock('../../redis/index', () => ({ + CacheSet: { + addressesSynced: jest.fn() + } })) jest.mock('../../services/priceService', () => ({ @@ -1145,6 +1153,53 @@ describe('MultiBlockchainClient method coverage', () => { expect(result).toHaveProperty('successfulAddressesWithCount') }) + it('Should link prices and invalidate caches after an on-demand sync', async () => { + const validAddress = fromHash160('ecash', 'p2pkh', 'c5d2460186f7233c927e7db2dcc703c0e500b653') + const mockAddresses = [ + { id: 'addr-1', address: validAddress, networkId: 1, syncing: false, createdAt: new Date(), updatedAt: new Date(), lastSynced: null } + ] + const linkPrices = connectTransactionsToPricesForAddresses as jest.Mock + const invalidate = CacheSet.addressesSynced as jest.Mock + const order: string[] = [] + linkPrices.mockReset().mockImplementation(async () => { order.push('prices') }) + invalidate.mockReset().mockImplementation(async () => { order.push('cache') }) + jest.spyOn(multiBlockchainClient, 'subscribeAddresses').mockResolvedValue() + jest.spyOn(multiBlockchainClient, 'syncAddresses').mockImplementation(async () => { + order.push('sync') + return { failedAddressesWithErrors: {}, successfulAddressesWithCount: { [validAddress]: 3 } } + }) + + await multiBlockchainClient.syncAndSubscribeAddresses(mockAddresses) + + expect(linkPrices).toHaveBeenCalledWith(['addr-1']) + expect(invalidate).toHaveBeenCalledWith([validAddress]) + expect(order).toEqual(['sync', 'prices', 'cache']) + }) + + it('Should still invalidate caches and return the sync result if price linking fails', async () => { + const validAddress = fromHash160('ecash', 'p2pkh', 'c5d2460186f7233c927e7db2dcc703c0e500b653') + const mockAddresses = [ + { id: 'addr-1', address: validAddress, networkId: 1, syncing: false, createdAt: new Date(), updatedAt: new Date(), lastSynced: null } + ] + const linkPrices = connectTransactionsToPricesForAddresses as jest.Mock + const invalidate = CacheSet.addressesSynced as jest.Mock + linkPrices.mockReset().mockRejectedValue(new Error('price API down')) + invalidate.mockReset().mockResolvedValue(undefined) + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + jest.spyOn(multiBlockchainClient, 'subscribeAddresses').mockResolvedValue() + jest.spyOn(multiBlockchainClient, 'syncAddresses').mockResolvedValue({ + failedAddressesWithErrors: {}, + successfulAddressesWithCount: { [validAddress]: 3 } + }) + + const result = await multiBlockchainClient.syncAndSubscribeAddresses(mockAddresses) + + expect(result.successfulAddressesWithCount[validAddress]).toBe(3) + expect(invalidate).toHaveBeenCalledWith([validAddress]) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down')) + errorSpy.mockRestore() + }) + it('Should get transaction details for specific network', async () => { // Mock the method const mockDetails = {