From 7d2a7a81a4e502ba8d299800df2b172b535dc2d5 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Thu, 26 Nov 2026 10:14:20 -0700 Subject: [PATCH 1/3] fix: stop payment cache rebuilds from exhausting DB connections Production went down repeatedly with the next process's Prisma pool exhausted (P2024) and RDS refusing connections (P1001). Logs showed a background rebuild of one user's large addresses running for 7.7 hours (~23 min per 25k-tx address), restarting after a failure, while every new tx for an uncached address started another full-history rebuild inline. - One rebuild per address at a time in a process: concurrent callers (dashboard loads, each new tx) share it. - initPaymentCache starts the rebuild in the background instead of holding up tx handling until it finishes. - A rebuild invalidated while reading is no longer discarded (which made a busy address never finish caching). It writes its result, then re-applies the txs created, updated or price-linked since it started. - Catch-up writes require a new :cacheBuilt marker, checked atomically, so a cache cleared meanwhile isn't refilled with a few weeks and taken as complete. - After a failed rebuild, further requests for that address back off for 10 minutes instead of restarting the full read. - Users' dashboards are cleared after a rebuild so they include it. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 12 ++ redis/cacheGeneration.ts | 31 +++-- redis/index.ts | 100 ++++++++++++--- redis/paymentCache.ts | 55 +++++++- services/transactionService.ts | 34 +++++ tests/unittests/cacheGeneration.test.ts | 160 +++++++++++++++++++++--- 6 files changed, 348 insertions(+), 44 deletions(-) diff --git a/constants/index.ts b/constants/index.ts index 93f08a13..4d9f629e 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -208,6 +208,18 @@ export const DEFAULT_TX_PAGE_SIZE = 100 export const PAYMENT_WEEK_KEY_FORMAT = 'YYYY:WW' +// After a payment cache rebuild of an address fails, further rebuild requests +// for it are skipped for this long instead of restarting the full read on every +// dashboard load or new tx. +export const CACHE_REBUILD_FAILURE_BACKOFF_MS = 10 * 60 * 1000 +// A rebuild invalidated while it was reading writes its result anyway and then +// re-applies the txs touched since it started. The start is moved back by this +// margin to cover clock skew between app (updatedAt) and DB (createdAt) clocks. +export const CACHE_CATCH_UP_MARGIN_MS = 5 * 60 * 1000 +// Catch-up passes (each re-applying what changed during the previous one) +// before giving up on an address that keeps changing. +export const CACHE_CATCH_UP_MAX_ROUNDS = 5 + export const PRIMARY_XEC_COLOR = '#0074C2' export const SECONDARY_XEC_COLOR = '#FFFFFF' export const TERTIARY_XEC_COLOR = '#231f20' diff --git a/redis/cacheGeneration.ts b/redis/cacheGeneration.ts index 832c67bd..2b03b55e 100644 --- a/redis/cacheGeneration.ts +++ b/redis/cacheGeneration.ts @@ -9,6 +9,14 @@ const getGenerationKey = (addressString: string): string => { return `${addressString}:cacheGeneration` } +// Set when a full rebuild writes the address's payment cache and deleted when +// that cache is cleared. Incremental writes (catch-up after a rebuild) require +// it, so they can't recreate a few weeks of a cache that was cleared meanwhile +// and make it look complete. Not under `:payments:`, so not taken for a week key. +export const getCacheBuiltKey = (addressString: string): string => { + return `${addressString}:cacheBuilt` +} + export const getCacheGeneration = async (addressString: string): Promise => { return (await redis.get(getGenerationKey(addressString))) ?? '0' } @@ -17,15 +25,19 @@ export const bumpCacheGeneration = async (addressString: string): Promise await redis.incr(getGenerationKey(addressString)) } -// KEYS[1]: generation key, KEYS[2..n]: cache keys. -// ARGV[1]: generation the rebuild started at, ARGV[2..n]: values for KEYS[2..n]. -// The check and the writes run atomically, so no invalidation can land in between. +// KEYS[1]: generation key, KEYS[2]: built marker key, KEYS[3..n]: cache keys. +// ARGV[1]: generation the writer read, ARGV[2]: '1' to also require the built +// marker, ARGV[3..n]: values for KEYS[3..n]. +// The checks and the writes run atomically, so no invalidation can land in between. const SET_IF_GENERATION_UNCHANGED_SCRIPT = ` local current = redis.call('GET', KEYS[1]) or '0' if current ~= ARGV[1] then return 0 end -for i = 2, #KEYS do +if ARGV[2] == '1' and redis.call('EXISTS', KEYS[2]) == 0 then + return 0 +end +for i = 3, #KEYS do redis.call('SET', KEYS[i], ARGV[i]) end return 1 @@ -33,20 +45,23 @@ return 1 /** * Writes the given cache entries only if the address's cache generation is still - * `generation`. Returns false (and writes nothing) if the address was invalidated - * since, in which case the result is stale and the next read rebuilds it. + * `generation` (and, with `requireBuilt`, its payment cache is still built). + * Returns false (and writes nothing) otherwise. */ export const setIfGenerationUnchanged = async ( addressString: string, generation: string, - entries: Array<[key: string, value: string]> + entries: Array<[key: string, value: string]>, + { requireBuilt = false }: { requireBuilt?: boolean } = {} ): Promise => { const result = await redis.eval( SET_IF_GENERATION_UNCHANGED_SCRIPT, - entries.length + 1, + entries.length + 2, getGenerationKey(addressString), + getCacheBuiltKey(addressString), ...entries.map(([key]) => key), generation, + requireBuilt ? '1' : '0', ...entries.map(([, value]) => value) ) return Number(result) === 1 diff --git a/redis/index.ts b/redis/index.ts index 00211412..eec33d50 100644 --- a/redis/index.ts +++ b/redis/index.ts @@ -1,11 +1,13 @@ -import { AddressPaymentInfo } from 'services/addressService' +import { AddressPaymentInfo, generateAddressPaymentInfo } from 'services/addressService' import { PaybuttonWithAddresses } from 'services/paybuttonService' -import { TransactionsWithPaybuttonsAndPrices } from 'services/transactionService' +import { fetchTransactionsWithPaybuttonsAndPricesTouchedSince, TransactionsWithPaybuttonsAndPrices } from 'services/transactionService' import { fetchUsersForAddress } from 'services/userService' +import { CACHE_CATCH_UP_MARGIN_MS, CACHE_CATCH_UP_MAX_ROUNDS, CACHE_REBUILD_FAILURE_BACKOFF_MS } from 'constants/index' import { clearBalanceCache, getBalanceForAddress, getBalanceKey, updateBalanceCacheFromTx } from './balanceCache' -import { bumpCacheGeneration, getCacheGeneration, setIfGenerationUnchanged } from './cacheGeneration' +import { bumpCacheGeneration, getCacheBuiltKey, getCacheGeneration, setIfGenerationUnchanged } from './cacheGeneration' +import { redis } from './clientInstance' import { clearDashboardCache, getUserDashboardData } from './dashboardCache' -import { appendPaybuttonToAddressesCache, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' +import { appendPaybuttonToAddressesCache, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPatchedWeekEntries, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' import { DashboardData, Payment } from './types' import { Address } from '@prisma/client' @@ -18,21 +20,85 @@ interface PaybuttonCreationParams { type PaybuttonUpdateParams = PaybuttonCreationParams type PaybuttonDeletionParams = PaybuttonCreationParams +// Rebuilds running in this process, by address: concurrent callers (a dashboard +// load, each new tx for the address) share one instead of each reading the +// address's whole history from the DB. +const rebuildsInFlight = new Map>() +// When each address's last rebuild failed, so requests back off instead of +// restarting the full read on every dashboard load or new tx. +const rebuildFailedAt = new Map() + +/** + * Rebuilds the address's payment and balance caches from the DB. If the address + * changed while its txs were being read (a new tx, prices linked, a sync), the + * result is written anyway and the txs touched since the read started are then + * re-applied. Discarding it instead would make a busy address, whose rebuild can + * take many minutes, never get cached. + */ +const rebuildAddressCache = async (address: Address): Promise => { + const addressString = address.address + const since = new Date(Date.now() - CACHE_CATCH_UP_MARGIN_MS) + const startGeneration = await getCacheGeneration(addressString) + const { groupedPayments, info } = await generateAndCacheGroupedPaymentsAndInfoForAddress(address) + const entries: Array<[string, string]> = [ + ...Object.entries(groupedPayments).map(([key, payments]): [string, string] => [key, JSON.stringify(payments)]), + [getBalanceKey(addressString), JSON.stringify(info)], + [getCacheBuiltKey(addressString), '1'] + ] + if (await setIfGenerationUnchanged(addressString, startGeneration, entries)) return + + await Promise.all(entries.map(async ([key, value]) => await redis.set(key, value))) + for (let round = 1; round <= CACHE_CATCH_UP_MAX_ROUNDS; round++) { + const generation = await getCacheGeneration(addressString) + const touched = await fetchTransactionsWithPaybuttonsAndPricesTouchedSince(address.id, since) + const balance = await generateAddressPaymentInfo(addressString) + const patched: Array<[string, string]> = [ + ...await getPatchedWeekEntries(addressString, touched), + [getBalanceKey(addressString), JSON.stringify(balance)] + ] + // Only onto the cache written above: if it was cleared meanwhile, the next + // read rebuilds it, and writing a few weeks would make it look complete. + if (await setIfGenerationUnchanged(addressString, generation, patched, { requireBuilt: true })) { + console.log(`[CACHE] Rebuild of ${addressString} caught up ${touched.length} txs changed while it was reading.`) + return + } + if ((await redis.get(getCacheBuiltKey(addressString))) === null) return + } + console.warn(`[CACHE] Rebuild of ${addressString} still changing after ${CACHE_CATCH_UP_MAX_ROUNDS} catch-up rounds; recent txs may be missing until its next invalidation.`) +} + +const clearDashboardsForAddress = async (addressString: string): Promise => { + const users = await fetchUsersForAddress(addressString) + await Promise.all(users.map(async u => await clearDashboardCache(u.id))) +} + export const CacheSet = { - // Rebuilds the address's payment and balance caches from the DB. The result is - // written only if the address wasn't invalidated while the DB was being read; - // otherwise it's discarded and the next read rebuilds it. + // Rebuilds the address's payment and balance caches from the DB, sharing a + // rebuild already running for it. Returns false without rebuilding if its last + // rebuild failed less than CACHE_REBUILD_FAILURE_BACKOFF_MS ago. addressCreation: async (address: Address): Promise => { - const generation = await getCacheGeneration(address.address) - const { groupedPayments, info } = await generateAndCacheGroupedPaymentsAndInfoForAddress(address) - const written = await setIfGenerationUnchanged(address.address, generation, [ - ...Object.entries(groupedPayments).map(([key, payments]): [string, string] => [key, JSON.stringify(payments)]), - [getBalanceKey(address.address), JSON.stringify(info)] - ]) - if (!written) { - console.log(`[CACHE] Discarded rebuild of ${address.address}: invalidated while it was being rebuilt.`) - } - return written + const addressString = address.address + const inFlight = rebuildsInFlight.get(addressString) + if (inFlight !== undefined) return await inFlight + const failedAt = rebuildFailedAt.get(addressString) + if (failedAt !== undefined && Date.now() - failedAt < CACHE_REBUILD_FAILURE_BACKOFF_MS) return false + + const run = (async () => { + try { + await rebuildAddressCache(address) + rebuildFailedAt.delete(addressString) + } catch (err) { + rebuildFailedAt.set(addressString, Date.now()) + throw err + } finally { + rebuildsInFlight.delete(addressString) + } + // Dashboards built while the address was uncached left its payments out. + await clearDashboardsForAddress(addressString) + return true + })() + rebuildsInFlight.set(addressString, run) + return await run }, txCreation: async (tx: TransactionsWithPaybuttonsAndPrices): Promise => { // A rebuild already reading this address's txs may have missed this one. diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index ded299aa..2b0d0c41 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -14,7 +14,7 @@ import { QuoteValues } from 'services/priceService' import { RESPONSE_MESSAGES, PAYMENT_WEEK_KEY_FORMAT, KeyValueT, N_OF_QUOTES } from 'constants/index' import moment from 'moment-timezone' import { CacheSet } from 'redis/index' -import { bumpCacheGeneration } from './cacheGeneration' +import { bumpCacheGeneration, getCacheBuiltKey } from './cacheGeneration' import { ButtonDisplayData, Payment } from './types' import { getUserDashboardData, clearDashboardCache } from './dashboardCache' // ADDRESS:payments:YYYY:MM @@ -329,6 +329,7 @@ export const clearPaymentCacheForAddress = async (addressString: string): Promis // Bumped even when nothing is cached yet: that is exactly when a rebuild may be // in flight, and it must not publish what it read before this invalidation. await bumpCacheGeneration(addressString) + await redis.del(getCacheBuiltKey(addressString), () => {}) const weekKeys = await getCachedWeekKeysForAddress(addressString) if (weekKeys.length === 0) { return @@ -338,16 +339,63 @@ export const clearPaymentCacheForAddress = async (addressString: string): Promis ) } +/** + * If the address has no payment cache, starts rebuilding it in the background + * and returns true: the rebuild reads the address's txs from the DB, so the + * caller has nothing to add incrementally. It doesn't wait for the rebuild, + * which can take minutes for a large address and must not hold up tx handling. + */ export const initPaymentCache = async (address: Address): Promise => { if (process.env.SKIP_CACHE_REBUILD !== undefined) return false const cachedKeys = await getCachedWeekKeysForAddress(address.address) if (cachedKeys.length === 0) { - await CacheSet.addressCreation(address) + void CacheSet.addressCreation(address).catch((err: any) => { + console.error(`[CACHE] Failed to rebuild ${address.address}: ${String(err?.message ?? err)}`) + }) return true } return false } +/** + * The payment a tx contributes to its address's cache, or undefined if a rebuild + * would leave it out (not incoming, prices not linked yet, or no USD value). + */ +const cacheablePaymentFromTx = (tx: TransactionsWithPaybuttonsAndPrices): Payment | undefined => { + if (!new Prisma.Decimal(tx.amount).gt(0)) return undefined + if (tx.prices.length !== N_OF_QUOTES) return undefined + const payment = generatePaymentFromTx(tx) + if (!new Prisma.Decimal(payment.values.usd).gt(0)) return undefined + return payment +} + +/** + * Week-key entries of the address's payment cache with these txs replaced by + * their current version (or dropped, if a rebuild would now leave them out). + * Reads the current weeks but writes nothing: the caller writes the entries. + * A tx whose timestamp moved to another week is not removed from its old week. + */ +export const getPatchedWeekEntries = async ( + addressString: string, + txs: TransactionsWithPaybuttonsAndPrices[] +): Promise> => { + const txsByWeekKey = new Map() + for (const tx of txs) { + const key = getPaymentsWeekKey(addressString, tx.timestamp) + txsByWeekKey.set(key, [...(txsByWeekKey.get(key) ?? []), tx]) + } + const entries: Array<[string, string]> = [] + for (const [key, weekTxs] of txsByWeekKey) { + const current: Payment[] = JSON.parse((await redis.get(key)) ?? '[]') + const hashes = new Set(weekTxs.map(t => t.hash)) + const updated = weekTxs + .map(cacheablePaymentFromTx) + .filter((p): p is Payment => p !== undefined) + entries.push([key, JSON.stringify(current.filter(p => !hashes.has(p.hash)).concat(updated))]) + } + return entries +} + const activeBackgroundRebuilds = new Set() export const isBackgroundRebuildActive = (userId: string): boolean => { @@ -365,7 +413,8 @@ const cacheAddressesInBackground = async (addresses: Address[], userId: string): try { for (const address of addresses) { try { - // Not written if the address was invalidated meanwhile; the next read retries. + // Shares a rebuild already running for the address; false if skipped + // because its last rebuild failed recently. if (!(await CacheSet.addressCreation(address))) continue cached++ if (cached % 10 === 0 || cached === addresses.length) { diff --git a/services/transactionService.ts b/services/transactionService.ts index ea68264c..18f85eaa 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -323,6 +323,40 @@ export async function * generateTransactionsWithPaybuttonsAndPricesForAddress (a } } +/** + * Txs of an address created, updated or linked to prices at or after `since`: + * what a cache rebuild that started reading at `since` may have missed. Same + * shape as generateTransactionsWithPaybuttonsAndPricesForAddress yields. + */ +export async function fetchTransactionsWithPaybuttonsAndPricesTouchedSince (addressId: string, since: Date): Promise { + const txs = await prisma.transaction.findMany({ + where: { + addressId, + OR: [ + { createdAt: { gte: since } }, + { updatedAt: { gte: since } }, + { prices: { some: { createdAt: { gte: since } } } } + ] + }, + include: { + address: { + include: { + paybuttons: { + include: { + paybutton: true + } + } + } + }, + ...includePrices + }, + orderBy: { + timestamp: 'asc' + } + }) + return txs as TransactionsWithPaybuttonsAndPrices[] +} + export async function fetchPaginatedAddressTransactions (addressString: string, page: number, pageSize: number, orderBy?: string, orderDesc = true): Promise { const orderByQuery = transactionOrderBy(orderBy, orderDesc) const parsedAddress = parseAddress(addressString) diff --git a/tests/unittests/cacheGeneration.test.ts b/tests/unittests/cacheGeneration.test.ts index df8eaa60..2660c0db 100644 --- a/tests/unittests/cacheGeneration.test.ts +++ b/tests/unittests/cacheGeneration.test.ts @@ -1,9 +1,16 @@ import { EventEmitter } from 'events' -import { Address } from '@prisma/client' +import { Address, Prisma } from '@prisma/client' import { CacheSet } from 'redis/index' import * as paymentCache from 'redis/paymentCache' import { clearBalanceCache, getBalanceForAddress } from 'redis/balanceCache' import * as addressService from 'services/addressService' +import * as transactionService from 'services/transactionService' +import * as userService from 'services/userService' +import moment from 'moment-timezone' +import { PAYMENT_WEEK_KEY_FORMAT } from 'constants/index' + +const weekKeyFor = (addressString: string, timestamp: number): string => + `${addressString}:payments:${moment.unix(timestamp).format(PAYMENT_WEEK_KEY_FORMAT)}` // In-memory stand-in for the commands the caches use. eval mirrors the // generation-check script in redis/cacheGeneration.ts (that script is the only @@ -23,7 +30,8 @@ jest.mock('redis/clientInstance', () => ({ const keys = rest.slice(0, numKeys) const args = rest.slice(numKeys) if ((store.get(keys[0]) ?? '0') !== args[0]) return 0 - for (let i = 1; i < keys.length; i++) store.set(keys[i], args[i]) + if (args[1] === '1' && !store.has(keys[1])) return 0 + for (let i = 2; i < keys.length; i++) store.set(keys[i], args[i]) return 1 }, scanStream: ({ match }: { match: string }) => { @@ -48,20 +56,54 @@ jest.mock('services/addressService', () => ({ generateAddressPaymentInfo: jest.fn() })) +jest.mock('services/transactionService', () => ({ + ...jest.requireActual('services/transactionService'), + fetchTransactionsWithPaybuttonsAndPricesTouchedSince: jest.fn() +})) + +jest.mock('services/userService', () => ({ + ...jest.requireActual('services/userService'), + fetchUsersForAddress: jest.fn(async () => [{ id: 'user-1' }]) +})) + const mockedGenerate = paymentCache.generateAndCacheGroupedPaymentsAndInfoForAddress as jest.Mock const mockedGenerateBalance = addressService.generateAddressPaymentInfo as jest.Mock - -const address = { id: 'addr-1', address: 'ecash:addr-1' } as unknown as Address -const rebuilt = { - groupedPayments: { 'ecash:addr-1:payments:2024:01': [{ hash: 'h1' }] }, - info: { balance: '1', paymentCount: 1 } -} +const mockedTouchedSince = transactionService.fetchTransactionsWithPaybuttonsAndPricesTouchedSince as jest.Mock + +// Rebuild bookkeeping (in-flight rebuilds, failure backoff) is per address and +// lives for the process, so each test uses its own address. +let addressCounter = 0 +let address: Address +let rebuilt: { groupedPayments: Record, info: { balance: string, paymentCount: number } } +let weekKey: string + +// A priced incoming tx, as fetchTransactionsWithPaybuttonsAndPricesTouchedSince returns it. +const pricedTx = (hash: string, timestamp: number): unknown => ({ + id: `id-${hash}`, + hash, + amount: new Prisma.Decimal(5), + timestamp, + address: { address: address.address, networkId: 1, paybuttons: [] }, + prices: [ + { price: { quoteId: 1, value: new Prisma.Decimal(2) } }, + { price: { quoteId: 2, value: new Prisma.Decimal(3) } } + ] +}) describe('cache rebuilds vs invalidation', () => { beforeEach(() => { store.clear() mockedGenerate.mockReset() mockedGenerateBalance.mockReset() + mockedTouchedSince.mockReset() + ;(userService.fetchUsersForAddress as jest.Mock).mockResolvedValue([{ id: 'user-1' }]) + addressCounter++ + address = { id: `addr-${addressCounter}`, address: `ecash:addr-${addressCounter}` } as unknown as Address + weekKey = `${address.address}:payments:2024:01` + rebuilt = { + groupedPayments: { [weekKey]: [{ hash: 'h1' }] }, + info: { balance: '1', paymentCount: 1 } + } jest.spyOn(console, 'log').mockImplementation(() => {}) }) @@ -74,21 +116,106 @@ describe('cache rebuilds vs invalidation', () => { await expect(CacheSet.addressCreation(address)).resolves.toBe(true) - expect(store.get('ecash:addr-1:payments:2024:01')).toBe(JSON.stringify([{ hash: 'h1' }])) - expect(store.get('ecash:addr-1:balance')).toBe(JSON.stringify(rebuilt.info)) + expect(store.get(weekKey)).toBe(JSON.stringify([{ hash: 'h1' }])) + expect(store.get(`${address.address}:balance`)).toBe(JSON.stringify(rebuilt.info)) + expect(mockedTouchedSince).not.toHaveBeenCalled() + }) + + it('keeps a rebuild invalidated mid-read and re-applies the txs touched since it started', async () => { + const ts = 1710000000 + const newTx = pricedTx('h-new', ts) + mockedGenerate.mockImplementation(async () => { + // e.g. a new tx for the address arrives, or prices are linked and its caches invalidated + await paymentCache.clearPaymentCacheForAddress(address.address) + return rebuilt + }) + mockedTouchedSince.mockResolvedValue([newTx]) + mockedGenerateBalance.mockResolvedValue({ balance: '6', paymentCount: 2 }) + + await expect(CacheSet.addressCreation(address)).resolves.toBe(true) + + expect(store.get(weekKey)).toBe(JSON.stringify([{ hash: 'h1' }])) + const patchedWeek = JSON.parse(store.get(weekKeyFor(address.address, ts)) as string) + expect(patchedWeek.map((p: { hash: string }) => p.hash)).toContain('h-new') + expect(store.get(`${address.address}:balance`)).toBe(JSON.stringify({ balance: '6', paymentCount: 2 })) + const since = mockedTouchedSince.mock.calls[0][1] as Date + expect(since.getTime()).toBeLessThan(Date.now()) }) - it('discards a rebuild if the address is invalidated while its txs are being read', async () => { + it('replaces a touched tx in its week and drops it if it no longer qualifies', async () => { + const ts = 1704500000 + const key = weekKeyFor(address.address, ts) + rebuilt.groupedPayments = { [key]: [{ hash: 'h1' }, { hash: 'h-gone' }] } mockedGenerate.mockImplementation(async () => { - // e.g. prices linked for one of its txs, then its caches invalidated await paymentCache.clearPaymentCacheForAddress(address.address) return rebuilt }) + // Now unpriced (e.g. prices unlinked for relinking): a rebuild would leave it out. + const unpriced = { ...(pricedTx('h-gone', ts) as object), prices: [] } + mockedTouchedSince.mockResolvedValue([unpriced]) + mockedGenerateBalance.mockResolvedValue(rebuilt.info) + + await CacheSet.addressCreation(address) + expect(JSON.parse(store.get(key) as string)).toEqual([{ hash: 'h1' }]) + }) + + it('does not patch weeks into a cache cleared during the catch-up', async () => { + const ts = 1704500000 + mockedGenerate.mockImplementation(async () => { + await paymentCache.clearPaymentCacheForAddress(address.address) + return rebuilt + }) + mockedTouchedSince.mockImplementation(async () => { + await paymentCache.clearPaymentCacheForAddress(address.address) + return [pricedTx('h-new', ts)] + }) + mockedGenerateBalance.mockResolvedValue(rebuilt.info) + + await expect(CacheSet.addressCreation(address)).resolves.toBe(true) + + expect(store.has(weekKeyFor(address.address, ts))).toBe(false) + expect(mockedTouchedSince).toHaveBeenCalledTimes(1) + }) + + it('shares one rebuild between concurrent callers for the same address', async () => { + let finish: (v: typeof rebuilt) => void = () => {} + mockedGenerate.mockImplementation(async () => await new Promise(resolve => { finish = resolve })) + + const first = CacheSet.addressCreation(address) + const second = CacheSet.addressCreation(address) + await new Promise(resolve => setImmediate(resolve)) + finish(rebuilt) + + await expect(Promise.all([first, second])).resolves.toEqual([true, true]) + expect(mockedGenerate).toHaveBeenCalledTimes(1) + }) + + it('backs off after a failed rebuild instead of restarting it on every request', async () => { + mockedGenerate.mockRejectedValueOnce(new Error('db unreachable')) + + await expect(CacheSet.addressCreation(address)).rejects.toThrow('db unreachable') await expect(CacheSet.addressCreation(address)).resolves.toBe(false) - expect(store.has('ecash:addr-1:payments:2024:01')).toBe(false) - expect(store.has('ecash:addr-1:balance')).toBe(false) + expect(mockedGenerate).toHaveBeenCalledTimes(1) + }) + + it('initPaymentCache starts the rebuild without waiting for it', async () => { + let finish: (v: typeof rebuilt) => void = () => {} + mockedGenerate.mockImplementation(async () => await new Promise(resolve => { finish = resolve })) + + await expect(paymentCache.initPaymentCache(address)).resolves.toBe(true) + expect(store.has(weekKey)).toBe(false) + + // A tx arriving meanwhile shares the running rebuild rather than starting another. + await expect(paymentCache.initPaymentCache(address)).resolves.toBe(true) + await new Promise(resolve => setImmediate(resolve)) + expect(mockedGenerate).toHaveBeenCalledTimes(1) + + finish(rebuilt) + await new Promise(resolve => setImmediate(resolve)) + await new Promise(resolve => setImmediate(resolve)) + expect(store.get(weekKey)).toBe(JSON.stringify([{ hash: 'h1' }])) }) it('rebuilds normally after an earlier invalidation', async () => { @@ -96,6 +223,7 @@ describe('cache rebuilds vs invalidation', () => { mockedGenerate.mockResolvedValue(rebuilt) await expect(CacheSet.addressCreation(address)).resolves.toBe(true) + expect(mockedTouchedSince).not.toHaveBeenCalled() }) it('does not cache a balance computed before a balance invalidation', async () => { @@ -106,7 +234,7 @@ describe('cache rebuilds vs invalidation', () => { await expect(getBalanceForAddress(address.address)).resolves.toEqual(rebuilt.info) - expect(store.has('ecash:addr-1:balance')).toBe(false) + expect(store.has(`${address.address}:balance`)).toBe(false) }) it('caches a balance computed without interference', async () => { @@ -114,6 +242,6 @@ describe('cache rebuilds vs invalidation', () => { await getBalanceForAddress(address.address) - expect(store.get('ecash:addr-1:balance')).toBe(JSON.stringify(rebuilt.info)) + expect(store.get(`${address.address}:balance`)).toBe(JSON.stringify(rebuilt.info)) }) }) From 116bef61381d77fa63b2ee81090386ad6f0c450c Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Thu, 26 Nov 2026 10:31:29 -0700 Subject: [PATCH 2/3] fix: keep rebuild writes from racing payment cache clears Review follow-ups to the rebuild changes: - The fallback write after a lost generation race was an unconditional SET, so it could land while clearPaymentCacheForAddress was between deleting the :cacheBuilt marker and deleting the week keys, restoring the marker over a partially deleted cache that catch-up then completed. Clears now bump a per-address clear epoch and set an expiring :cacheClearing flag while they delete. Every rebuild write (normal, fallback and catch-up) atomically requires the epoch read when the rebuild started and no clear in progress. New txs still only bump the generation, so they don't make a rebuild discard its result. A clear during the rebuild does. - If catch-up fails after the fallback write, the published weeks, marker and balance are cleared before rethrowing, so a cache missing the changes made during the read isn't taken as complete. Backoff and in-flight cleanup are unchanged. - initPaymentCache during a rebuild backoff no longer looks like a scheduled rebuild: it drops the address's balance and its users' dashboards (still without writing a lone payment week). Co-Authored-By: Claude Opus 5.5 --- redis/cacheGeneration.ts | 90 ++++++++++++++++++++----- redis/index.ts | 82 +++++++++++++++------- redis/paymentCache.ts | 31 ++++++--- tests/unittests/cacheGeneration.test.ts | 71 +++++++++++++++++-- 4 files changed, 218 insertions(+), 56 deletions(-) diff --git a/redis/cacheGeneration.ts b/redis/cacheGeneration.ts index 2b03b55e..c371303e 100644 --- a/redis/cacheGeneration.ts +++ b/redis/cacheGeneration.ts @@ -17,6 +17,20 @@ export const getCacheBuiltKey = (addressString: string): string => { return `${addressString}:cacheBuilt` } +// Per-address counter bumped only when a payment cache clear starts (new txs +// don't bump it, unlike the generation), plus a flag set while the clear is +// deleting week keys. Rebuild writes require the epoch read when the rebuild +// started and no clear in progress, so none can land during or after a clear +// that started meanwhile and leave a partially deleted cache marked as built. +// The flag expires, so a clear that dies midway doesn't block writes forever. +const getClearEpochKey = (addressString: string): string => { + return `${addressString}:cacheClearEpoch` +} +const getClearingKey = (addressString: string): string => { + return `${addressString}:cacheClearing` +} +const CLEARING_FLAG_TTL_MS = 60_000 + export const getCacheGeneration = async (addressString: string): Promise => { return (await redis.get(getGenerationKey(addressString))) ?? '0' } @@ -25,44 +39,90 @@ export const bumpCacheGeneration = async (addressString: string): Promise await redis.incr(getGenerationKey(addressString)) } -// KEYS[1]: generation key, KEYS[2]: built marker key, KEYS[3..n]: cache keys. -// ARGV[1]: generation the writer read, ARGV[2]: '1' to also require the built -// marker, ARGV[3..n]: values for KEYS[3..n]. +export const getCacheClearEpoch = async (addressString: string): Promise => { + return (await redis.get(getClearEpochKey(addressString))) ?? '0' +} + +/** Marks a payment cache clear as started: bumps the clear epoch and sets the clearing flag. */ +export const beginCacheClear = async (addressString: string): Promise => { + await redis.set(getClearingKey(addressString), '1', 'PX', CLEARING_FLAG_TTL_MS) + await redis.incr(getClearEpochKey(addressString)) +} + +/** Marks a payment cache clear as finished. */ +export const endCacheClear = async (addressString: string): Promise => { + await redis.del(getClearingKey(addressString), () => {}) +} + +// KEYS[1]: generation key, KEYS[2]: built marker key, KEYS[3]: clear epoch key, +// KEYS[4]: clearing flag key, KEYS[5..n]: cache keys. +// ARGV[1]: generation the writer read ('' to skip the check), ARGV[2]: '1' to +// require the built marker, ARGV[3]: clear epoch the writer read ('' to skip; +// otherwise it must be unchanged with no clear in progress), ARGV[4]: unused, +// ARGV[5..n]: values for KEYS[5..n]. // The checks and the writes run atomically, so no invalidation can land in between. -const SET_IF_GENERATION_UNCHANGED_SCRIPT = ` -local current = redis.call('GET', KEYS[1]) or '0' -if current ~= ARGV[1] then +const SET_IF_UNCHANGED_SCRIPT = ` +if ARGV[1] ~= '' and (redis.call('GET', KEYS[1]) or '0') ~= ARGV[1] then return 0 end if ARGV[2] == '1' and redis.call('EXISTS', KEYS[2]) == 0 then return 0 end -for i = 3, #KEYS do +if ARGV[3] ~= '' then + if (redis.call('GET', KEYS[3]) or '0') ~= ARGV[3] or redis.call('EXISTS', KEYS[4]) == 1 then + return 0 + end +end +for i = 5, #KEYS do redis.call('SET', KEYS[i], ARGV[i]) end return 1 ` +interface SetIfUnchangedConditions { + // Generation the writer read; omitted to skip the check. + generation?: string + // Require the payment cache to still be marked as built. + requireBuilt?: boolean + // Clear epoch the writer read; omitted to skip the check. + clearEpoch?: string +} + /** - * Writes the given cache entries only if the address's cache generation is still - * `generation` (and, with `requireBuilt`, its payment cache is still built). + * Writes the given cache entries only if all the given conditions still hold. * Returns false (and writes nothing) otherwise. */ -export const setIfGenerationUnchanged = async ( +export const setCacheEntriesIfUnchanged = async ( addressString: string, - generation: string, entries: Array<[key: string, value: string]>, - { requireBuilt = false }: { requireBuilt?: boolean } = {} + { generation, requireBuilt = false, clearEpoch }: SetIfUnchangedConditions ): Promise => { const result = await redis.eval( - SET_IF_GENERATION_UNCHANGED_SCRIPT, - entries.length + 2, + SET_IF_UNCHANGED_SCRIPT, + entries.length + 4, getGenerationKey(addressString), getCacheBuiltKey(addressString), + getClearEpochKey(addressString), + getClearingKey(addressString), ...entries.map(([key]) => key), - generation, + generation ?? '', requireBuilt ? '1' : '0', + clearEpoch ?? '', + '', ...entries.map(([, value]) => value) ) return Number(result) === 1 } + +/** + * Writes the given cache entries only if the address's cache generation is still + * `generation`. Returns false (and writes nothing) if the address was invalidated + * since, in which case the result is stale and the next read rebuilds it. + */ +export const setIfGenerationUnchanged = async ( + addressString: string, + generation: string, + entries: Array<[key: string, value: string]> +): Promise => { + return await setCacheEntriesIfUnchanged(addressString, entries, { generation }) +} diff --git a/redis/index.ts b/redis/index.ts index eec33d50..9a4be52a 100644 --- a/redis/index.ts +++ b/redis/index.ts @@ -4,8 +4,7 @@ import { fetchTransactionsWithPaybuttonsAndPricesTouchedSince, TransactionsWithP import { fetchUsersForAddress } from 'services/userService' import { CACHE_CATCH_UP_MARGIN_MS, CACHE_CATCH_UP_MAX_ROUNDS, CACHE_REBUILD_FAILURE_BACKOFF_MS } from 'constants/index' import { clearBalanceCache, getBalanceForAddress, getBalanceKey, updateBalanceCacheFromTx } from './balanceCache' -import { bumpCacheGeneration, getCacheBuiltKey, getCacheGeneration, setIfGenerationUnchanged } from './cacheGeneration' -import { redis } from './clientInstance' +import { bumpCacheGeneration, getCacheBuiltKey, getCacheClearEpoch, getCacheGeneration, setCacheEntriesIfUnchanged } from './cacheGeneration' import { clearDashboardCache, getUserDashboardData } from './dashboardCache' import { appendPaybuttonToAddressesCache, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPatchedWeekEntries, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' import { DashboardData, Payment } from './types' @@ -30,14 +29,18 @@ const rebuildFailedAt = new Map() /** * Rebuilds the address's payment and balance caches from the DB. If the address - * changed while its txs were being read (a new tx, prices linked, a sync), the + * changed while its txs were being read (a new tx, a balance invalidation), the * result is written anyway and the txs touched since the read started are then * re-applied. Discarding it instead would make a busy address, whose rebuild can - * take many minutes, never get cached. + * take many minutes, never get cached. If its payment cache was cleared while + * the rebuild ran, nothing is written: every write requires the clear epoch read + * at the start, so none can restore weeks or the built marker over a clear. + * Returns whether the result was written. */ -const rebuildAddressCache = async (address: Address): Promise => { +const rebuildAddressCache = async (address: Address): Promise => { const addressString = address.address const since = new Date(Date.now() - CACHE_CATCH_UP_MARGIN_MS) + const clearEpoch = await getCacheClearEpoch(addressString) const startGeneration = await getCacheGeneration(addressString) const { groupedPayments, info } = await generateAndCacheGroupedPaymentsAndInfoForAddress(address) const entries: Array<[string, string]> = [ @@ -45,26 +48,45 @@ const rebuildAddressCache = async (address: Address): Promise => { [getBalanceKey(addressString), JSON.stringify(info)], [getCacheBuiltKey(addressString), '1'] ] - if (await setIfGenerationUnchanged(addressString, startGeneration, entries)) return - - await Promise.all(entries.map(async ([key, value]) => await redis.set(key, value))) - for (let round = 1; round <= CACHE_CATCH_UP_MAX_ROUNDS; round++) { - const generation = await getCacheGeneration(addressString) - const touched = await fetchTransactionsWithPaybuttonsAndPricesTouchedSince(address.id, since) - const balance = await generateAddressPaymentInfo(addressString) - const patched: Array<[string, string]> = [ - ...await getPatchedWeekEntries(addressString, touched), - [getBalanceKey(addressString), JSON.stringify(balance)] - ] - // Only onto the cache written above: if it was cleared meanwhile, the next - // read rebuilds it, and writing a few weeks would make it look complete. - if (await setIfGenerationUnchanged(addressString, generation, patched, { requireBuilt: true })) { - console.log(`[CACHE] Rebuild of ${addressString} caught up ${touched.length} txs changed while it was reading.`) - return + if (await setCacheEntriesIfUnchanged(addressString, entries, { generation: startGeneration, clearEpoch })) return true + + if (!(await setCacheEntriesIfUnchanged(addressString, entries, { clearEpoch }))) { + console.log(`[CACHE] Discarded rebuild of ${addressString}: its payment cache was cleared while it was being rebuilt.`) + return false + } + try { + for (let round = 1; round <= CACHE_CATCH_UP_MAX_ROUNDS; round++) { + const generation = await getCacheGeneration(addressString) + const touched = await fetchTransactionsWithPaybuttonsAndPricesTouchedSince(address.id, since) + const balance = await generateAddressPaymentInfo(addressString) + const patched: Array<[string, string]> = [ + ...await getPatchedWeekEntries(addressString, touched), + [getBalanceKey(addressString), JSON.stringify(balance)] + ] + // Only onto the cache written above: if it was cleared meanwhile, the next + // read rebuilds it, and writing a few weeks would make it look complete. + if (await setCacheEntriesIfUnchanged(addressString, patched, { generation, requireBuilt: true, clearEpoch })) { + console.log(`[CACHE] Rebuild of ${addressString} caught up ${touched.length} txs changed while it was reading.`) + return true + } + if ((await getCacheClearEpoch(addressString)) !== clearEpoch) return true } - if ((await redis.get(getCacheBuiltKey(addressString))) === null) return + } catch (err) { + // What was published lacks the changes made during the read; don't leave + // it passing for a complete cache. The next request rebuilds it. + await clearPaymentCacheForAddress(addressString).catch(() => {}) + await clearBalanceCache(addressString).catch(() => {}) + throw err } console.warn(`[CACHE] Rebuild of ${addressString} still changing after ${CACHE_CATCH_UP_MAX_ROUNDS} catch-up rounds; recent txs may be missing until its next invalidation.`) + return true +} + +/** Whether a rebuild request for the address would be skipped for backoff. */ +export const isAddressRebuildBackedOff = (addressString: string): boolean => { + if (rebuildsInFlight.has(addressString)) return false + const failedAt = rebuildFailedAt.get(addressString) + return failedAt !== undefined && Date.now() - failedAt < CACHE_REBUILD_FAILURE_BACKOFF_MS } const clearDashboardsForAddress = async (addressString: string): Promise => { @@ -72,6 +94,15 @@ const clearDashboardsForAddress = async (addressString: string): Promise = await Promise.all(users.map(async u => await clearDashboardCache(u.id))) } +/** + * Drops the address's balance and its users' dashboard caches, which were built + * without a tx that couldn't be added to its (unbuilt) payment cache. + */ +export const dropCachesBuiltWithoutAddressTxs = async (addressString: string): Promise => { + await clearBalanceCache(addressString) + await clearDashboardsForAddress(addressString) +} + export const CacheSet = { // Rebuilds the address's payment and balance caches from the DB, sharing a // rebuild already running for it. Returns false without rebuilding if its last @@ -80,12 +111,12 @@ export const CacheSet = { const addressString = address.address const inFlight = rebuildsInFlight.get(addressString) if (inFlight !== undefined) return await inFlight - const failedAt = rebuildFailedAt.get(addressString) - if (failedAt !== undefined && Date.now() - failedAt < CACHE_REBUILD_FAILURE_BACKOFF_MS) return false + if (isAddressRebuildBackedOff(addressString)) return false const run = (async () => { + let written: boolean try { - await rebuildAddressCache(address) + written = await rebuildAddressCache(address) rebuildFailedAt.delete(addressString) } catch (err) { rebuildFailedAt.set(addressString, Date.now()) @@ -93,6 +124,7 @@ export const CacheSet = { } finally { rebuildsInFlight.delete(addressString) } + if (!written) return false // Dashboards built while the address was uncached left its payments out. await clearDashboardsForAddress(addressString) return true diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index 2b0d0c41..b4f071a1 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -13,8 +13,8 @@ import { QuoteValues } from 'services/priceService' import { RESPONSE_MESSAGES, PAYMENT_WEEK_KEY_FORMAT, KeyValueT, N_OF_QUOTES } from 'constants/index' import moment from 'moment-timezone' -import { CacheSet } from 'redis/index' -import { bumpCacheGeneration, getCacheBuiltKey } from './cacheGeneration' +import { CacheSet, dropCachesBuiltWithoutAddressTxs, isAddressRebuildBackedOff } from 'redis/index' +import { beginCacheClear, bumpCacheGeneration, endCacheClear, getCacheBuiltKey } from './cacheGeneration' import { ButtonDisplayData, Payment } from './types' import { getUserDashboardData, clearDashboardCache } from './dashboardCache' // ADDRESS:payments:YYYY:MM @@ -328,15 +328,19 @@ export const clearRecentAddressCache = async (addressString: string, timestamps: export const clearPaymentCacheForAddress = async (addressString: string): Promise => { // Bumped even when nothing is cached yet: that is exactly when a rebuild may be // in flight, and it must not publish what it read before this invalidation. - await bumpCacheGeneration(addressString) - await redis.del(getCacheBuiltKey(addressString), () => {}) - const weekKeys = await getCachedWeekKeysForAddress(addressString) - if (weekKeys.length === 0) { - return + // Marked as in progress first, so no rebuild write can land between deleting + // the marker and deleting the week keys (see beginCacheClear). + await beginCacheClear(addressString) + try { + await bumpCacheGeneration(addressString) + await redis.del(getCacheBuiltKey(addressString), () => {}) + const weekKeys = await getCachedWeekKeysForAddress(addressString) + await Promise.all( + weekKeys.map(async (key) => await redis.del(key, () => {})) + ) + } finally { + await endCacheClear(addressString) } - await Promise.all( - weekKeys.map(async (key) => await redis.del(key, () => {})) - ) } /** @@ -349,6 +353,13 @@ export const initPaymentCache = async (address: Address): Promise => { if (process.env.SKIP_CACHE_REBUILD !== undefined) return false const cachedKeys = await getCachedWeekKeysForAddress(address.address) if (cachedKeys.length === 0) { + if (isAddressRebuildBackedOff(address.address)) { + // Its last rebuild failed recently, so none starts now. The tx isn't added + // as a lone week (that would pass for a complete cache), but the balance + // and dashboards built without it are dropped. + await dropCachesBuiltWithoutAddressTxs(address.address) + return true + } void CacheSet.addressCreation(address).catch((err: any) => { console.error(`[CACHE] Failed to rebuild ${address.address}: ${String(err?.message ?? err)}`) }) diff --git a/tests/unittests/cacheGeneration.test.ts b/tests/unittests/cacheGeneration.test.ts index 2660c0db..a6f0678d 100644 --- a/tests/unittests/cacheGeneration.test.ts +++ b/tests/unittests/cacheGeneration.test.ts @@ -3,6 +3,7 @@ import { Address, Prisma } from '@prisma/client' import { CacheSet } from 'redis/index' import * as paymentCache from 'redis/paymentCache' import { clearBalanceCache, getBalanceForAddress } from 'redis/balanceCache' +import { beginCacheClear, bumpCacheGeneration } from 'redis/cacheGeneration' import * as addressService from 'services/addressService' import * as transactionService from 'services/transactionService' import * as userService from 'services/userService' @@ -26,12 +27,15 @@ jest.mock('redis/clientInstance', () => ({ store.set(key, String(next)) return next }, + // KEYS: generation, built marker, clear epoch, clearing flag, then cache keys. + // ARGV: generation ('' skips), '1' to require built, clear epoch ('' skips), unused, then values. eval: async (_script: string, numKeys: number, ...rest: string[]) => { const keys = rest.slice(0, numKeys) const args = rest.slice(numKeys) - if ((store.get(keys[0]) ?? '0') !== args[0]) return 0 + if (args[0] !== '' && (store.get(keys[0]) ?? '0') !== args[0]) return 0 if (args[1] === '1' && !store.has(keys[1])) return 0 - for (let i = 2; i < keys.length; i++) store.set(keys[i], args[i]) + if (args[2] !== '' && ((store.get(keys[2]) ?? '0') !== args[2] || store.has(keys[3]))) return 0 + for (let i = 4; i < keys.length; i++) store.set(keys[i], args[i]) return 1 }, scanStream: ({ match }: { match: string }) => { @@ -125,8 +129,8 @@ describe('cache rebuilds vs invalidation', () => { const ts = 1710000000 const newTx = pricedTx('h-new', ts) mockedGenerate.mockImplementation(async () => { - // e.g. a new tx for the address arrives, or prices are linked and its caches invalidated - await paymentCache.clearPaymentCacheForAddress(address.address) + // e.g. a new tx for the address arrives while the history is being read + await bumpCacheGeneration(address.address) return rebuilt }) mockedTouchedSince.mockResolvedValue([newTx]) @@ -147,7 +151,7 @@ describe('cache rebuilds vs invalidation', () => { const key = weekKeyFor(address.address, ts) rebuilt.groupedPayments = { [key]: [{ hash: 'h1' }, { hash: 'h-gone' }] } mockedGenerate.mockImplementation(async () => { - await paymentCache.clearPaymentCacheForAddress(address.address) + await bumpCacheGeneration(address.address) return rebuilt }) // Now unpriced (e.g. prices unlinked for relinking): a rebuild would leave it out. @@ -163,7 +167,7 @@ describe('cache rebuilds vs invalidation', () => { it('does not patch weeks into a cache cleared during the catch-up', async () => { const ts = 1704500000 mockedGenerate.mockImplementation(async () => { - await paymentCache.clearPaymentCacheForAddress(address.address) + await bumpCacheGeneration(address.address) return rebuilt }) mockedTouchedSince.mockImplementation(async () => { @@ -178,6 +182,61 @@ describe('cache rebuilds vs invalidation', () => { expect(mockedTouchedSince).toHaveBeenCalledTimes(1) }) + it('discards a rebuild whose payment cache was cleared while its txs were being read', async () => { + mockedGenerate.mockImplementation(async () => { + // e.g. prices linked for one of its txs, then its caches cleared + await paymentCache.clearPaymentCacheForAddress(address.address) + return rebuilt + }) + + await expect(CacheSet.addressCreation(address)).resolves.toBe(false) + + expect(store.has(weekKey)).toBe(false) + expect(store.has(`${address.address}:cacheBuilt`)).toBe(false) + expect(mockedTouchedSince).not.toHaveBeenCalled() + }) + + it('writes nothing while a clear of the payment cache is still in progress', async () => { + // A clear that started before the rebuild and hasn't finished deleting week keys. + await beginCacheClear(address.address) + mockedGenerate.mockResolvedValue(rebuilt) + + await expect(CacheSet.addressCreation(address)).resolves.toBe(false) + + expect(store.has(weekKey)).toBe(false) + expect(store.has(`${address.address}:cacheBuilt`)).toBe(false) + }) + + it('drops the published cache if the catch-up fails, then backs off', async () => { + mockedGenerate.mockImplementation(async () => { + await bumpCacheGeneration(address.address) + return rebuilt + }) + mockedTouchedSince.mockRejectedValue(new Error('db unreachable')) + + await expect(CacheSet.addressCreation(address)).rejects.toThrow('db unreachable') + + expect(store.has(weekKey)).toBe(false) + expect(store.has(`${address.address}:cacheBuilt`)).toBe(false) + expect(store.has(`${address.address}:balance`)).toBe(false) + await expect(CacheSet.addressCreation(address)).resolves.toBe(false) + expect(mockedGenerate).toHaveBeenCalledTimes(1) + }) + + it('initPaymentCache during backoff drops the balance and dashboards without writing a week', async () => { + mockedGenerate.mockRejectedValueOnce(new Error('db unreachable')) + await expect(CacheSet.addressCreation(address)).rejects.toThrow('db unreachable') + store.set(`${address.address}:balance`, JSON.stringify(rebuilt.info)) + store.set('user-1:dashboard', 'cached') + + await expect(paymentCache.initPaymentCache(address)).resolves.toBe(true) + + expect(store.has(`${address.address}:balance`)).toBe(false) + expect(store.has('user-1:dashboard')).toBe(false) + expect([...store.keys()].some(k => k.startsWith(`${address.address}:payments:`))).toBe(false) + expect(mockedGenerate).toHaveBeenCalledTimes(1) + }) + it('shares one rebuild between concurrent callers for the same address', async () => { let finish: (v: typeof rebuilt) => void = () => {} mockedGenerate.mockImplementation(async () => await new Promise(resolve => { finish = resolve })) From 83d2376c4155c92ff61cda9bace1e9107f3abc3d Mon Sep 17 00:00:00 2001 From: David Date: Thu, 26 Nov 2026 11:08:33 -0700 Subject: [PATCH 3/3] perf: find a user's cached payment weeks without scanning Redis Loading the dashboard (or payment list) SCANned the whole Redis keyspace once per user address, twice per request, to find the address's week keys, then fetched each week with its own GET. With a large keyspace that is hundreds of thousands of sequential round trips, so uncached dashboards took minutes. Week keys are named after their week, so the candidates for each address are now derived from its oldest and newest tx (one grouped query that MySQL answers from the (addressId, timestamp) index alone), checked with pipelined EXISTS, and read with batched MGET. An address counts as cached if it has the built marker or any cached week, so caches written before the marker existed aren't rebuilt, and addresses with no payments stop being rebuilt (and holding the dashboard in "rebuilding") on every load once they have the marker. --- constants/index.ts | 5 + redis/clientInstance.ts | 8 +- redis/paymentCache.ts | 189 +++++++++++++++++---------- services/transactionService.ts | 26 ++++ tests/unittests/paymentCache.test.ts | 178 +++++++++++++++++++++++++ 5 files changed, 337 insertions(+), 69 deletions(-) create mode 100644 tests/unittests/paymentCache.test.ts diff --git a/constants/index.ts b/constants/index.ts index 4d9f629e..ff430621 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -219,6 +219,11 @@ export const CACHE_CATCH_UP_MARGIN_MS = 5 * 60 * 1000 // Catch-up passes (each re-applying what changed during the previous one) // before giving up on an address that keeps changing. export const CACHE_CATCH_UP_MAX_ROUNDS = 5 +// Payment cache keys checked for existence per Redis pipeline round trip. +export const CACHE_EXISTS_BATCH_SIZE = 1000 +// Payment cache week keys fetched per MGET. Kept smaller than the EXISTS batch +// since each value holds a whole week of payments. +export const CACHE_MGET_BATCH_SIZE = 200 export const PRIMARY_XEC_COLOR = '#0074C2' export const SECONDARY_XEC_COLOR = '#FFFFFF' diff --git a/redis/clientInstance.ts b/redis/clientInstance.ts index 1d2786cb..da748a08 100755 --- a/redis/clientInstance.ts +++ b/redis/clientInstance.ts @@ -9,6 +9,10 @@ class RedisMocked { return null } + async mget (keys: string[]): Promise { + return keys.map(() => null) + } + async sadd (key: string, ...members: string[]): Promise { const set = this.sets.get(key) ?? new Set() const before = set.size @@ -57,8 +61,10 @@ class RedisMocked { return stream } - pipeline (commands?: unknown[][]): any { + // Nothing is ever stored, so every queued command (only EXISTS is queued) yields 0. + pipeline (commands: unknown[][] = []): any { return { + exec: async (): Promise> => commands.map(() => [null, 0]) } } diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index b4f071a1..2d78c997 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -1,6 +1,7 @@ import { redis } from 'redis/clientInstance' import { Address, Prisma } from '@prisma/client' import { + fetchTxTimestampRangesByAddressId, generateTransactionsWithPaybuttonsAndPricesForAddress, getTransactionValue, TransactionsWithPaybuttonsAndPrices, @@ -11,7 +12,7 @@ import { fetchAllUserAddresses, AddressPaymentInfo } from 'services/addressServi import { fetchPaybuttonArrayByUserId } from 'services/paybuttonService' import { QuoteValues } from 'services/priceService' -import { RESPONSE_MESSAGES, PAYMENT_WEEK_KEY_FORMAT, KeyValueT, N_OF_QUOTES } from 'constants/index' +import { PAYMENT_WEEK_KEY_FORMAT, KeyValueT, N_OF_QUOTES, CACHE_EXISTS_BATCH_SIZE, CACHE_MGET_BATCH_SIZE } from 'constants/index' import moment from 'moment-timezone' import { CacheSet, dropCachesBuiltWithoutAddressTxs, isAddressRebuildBackedOff } from 'redis/index' import { beginCacheClear, bumpCacheGeneration, endCacheClear, getCacheBuiltKey } from './cacheGeneration' @@ -22,23 +23,101 @@ const getPaymentsWeekKey = (addressString: string, timestamp: number): string => return `${addressString}:payments:${moment.unix(timestamp).format(PAYMENT_WEEK_KEY_FORMAT)}` } -export async function * getUserUncachedAddresses (userId: string): AsyncGenerator
{ - const addresses = await fetchAllUserAddresses(userId, false, false) as Address[] - for (const address of addresses) { - const keys = await getCachedWeekKeysForAddress(address.address) - if (keys.length === 0) { - yield address +interface AddressCacheState { + address: Address + // Whether a full rebuild wrote the address's payment cache (see getCacheBuiltKey). + built: boolean + // The address's week keys present in the cache. + weekKeys: string[] +} + +interface DaySpan { + start: number + end: number + weekSuffix: string +} + +/** + * Each local day from `from` to `to` (unix seconds), with the suffix that + * getPaymentsWeekKey gives the payments timestamped on it. + */ +const getDaySpans = (from: number, to: number): DaySpan[] => { + const spans: DaySpan[] = [] + const last = moment.unix(to) + let day = moment.unix(from).startOf('day') + while (day.isSameOrBefore(last)) { + const next = day.clone().add(1, 'day') + spans.push({ start: day.unix(), end: next.unix() - 1, weekSuffix: day.format(PAYMENT_WEEK_KEY_FORMAT) }) + day = next + } + return spans +} + +/** For each key, whether it exists, batching the checks into pipelines. */ +const getKeysExist = async (keys: string[]): Promise => { + const exist: boolean[] = [] + for (let i = 0; i < keys.length; i += CACHE_EXISTS_BATCH_SIZE) { + const batch = keys.slice(i, i + CACHE_EXISTS_BATCH_SIZE) + const results: Array<[Error | null, unknown]> = (await redis.pipeline(batch.map(k => ['exists', k])).exec()) ?? [] + for (const [err, count] of results) { + if (err !== null) throw err + exist.push(Number(count) === 1) } } + return exist } -const triggerBackgroundRebuildIfNeeded = async (userId: string): Promise => { - if (process.env.SKIP_CACHE_REBUILD !== undefined) return - const uncachedAddresses: Address[] = [] - const uncachedAddressStream = getUserUncachedAddresses(userId) - for await (const address of uncachedAddressStream) { - uncachedAddresses.push(address) +/** + * The payment cache state of each of the user's addresses. Week keys are named + * after their week, so instead of SCANning the whole keyspace (twice, per + * address) for them, this derives the weeks each address can have payments in + * from its oldest and newest tx, and checks which of those keys exist. + */ +const getUserAddressCacheStates = async (userId: string): Promise => { + const addresses = await fetchAllUserAddresses(userId) as Address[] + if (addresses.length === 0) return [] + const ranges = await fetchTxTimestampRangesByAddressId(addresses.map(a => a.id)) + // Up to now at least: a tx arriving after the ranges were read may already be cached. + const now = moment().unix() + let from = now + let to = now + for (const range of ranges.values()) { + from = Math.min(from, range.min) + to = Math.max(to, range.max) } + const daySpans = getDaySpans(from, to) + + const candidateKeysByAddress = addresses.map(address => { + const range = ranges.get(address.id) + if (range === undefined) return [] + const suffixes = new Set() + for (const span of daySpans) { + if (span.end >= range.min && span.start <= Math.max(range.max, now)) { + suffixes.add(span.weekSuffix) + } + } + return [...suffixes].map(suffix => `${address.address}:payments:${suffix}`) + }) + const keysToCheck = addresses.flatMap((address, i) => [getCacheBuiltKey(address.address), ...candidateKeysByAddress[i]]) + const exist = await getKeysExist(keysToCheck) + + let pos = 0 + return addresses.map((address, i) => { + const built = exist[pos++] + const weekKeys = candidateKeysByAddress[i].filter(() => exist[pos++]) + return { address, built, weekKeys } + }) +} + +/** + * Whether the address's payment cache has been written. Caches written before + * the built marker existed are recognized by their week keys. + */ +const isAddressCached = (state: AddressCacheState): boolean => state.built || state.weekKeys.length > 0 + +const triggerBackgroundRebuildIfNeeded = (userId: string, states: AddressCacheState[]): void => { + if (process.env.SKIP_CACHE_REBUILD !== undefined) return + const uncachedAddresses = states.filter(s => !isAddressCached(s)).map(s => s.address) if (uncachedAddresses.length > 0) { if (!isBackgroundRebuildActive(userId)) { console.log(`[CACHE] ${uncachedAddresses.length} uncached addresses for user ${userId}, starting background rebuild`) @@ -47,9 +126,29 @@ const triggerBackgroundRebuildIfNeeded = async (userId: string): Promise = } } +/** Yields the payments stored under the given week keys, fetching them in MGET batches. */ +async function * getPaymentsForWeekKeys (weekKeys: string[], userButtonIds: string[]): AsyncGenerator { + const userButtonIdSet = new Set(userButtonIds) + for (let i = 0; i < weekKeys.length; i += CACHE_MGET_BATCH_SIZE) { + const values = await redis.mget(weekKeys.slice(i, i + CACHE_MGET_BATCH_SIZE)) + for (const paymentsString of values) { + // Deleted since its existence was checked, e.g. by a cache clear. + if (paymentsString === null) continue + const weekPayments: Payment[] = JSON.parse(paymentsString) + for (const payment of weekPayments) { + payment.buttonDisplayDataList = payment.buttonDisplayDataList.filter(d => userButtonIdSet.has(d.id)) + yield payment + } + } + } +} + export const getPaymentList = async (userId: string): Promise => { - await triggerBackgroundRebuildIfNeeded(userId) - return await getCachedPaymentsForUser(userId) + const payments: Payment[] = [] + for await (const payment of getPaymentStream(userId)) { + payments.push(payment) + } + return payments } const getCachedWeekKeysForAddress = async (addressString: string): Promise => { @@ -68,15 +167,6 @@ const getCachedWeekKeysForAddress = async (addressString: string): Promise => { - const addresses = await fetchAllUserAddresses(userId) - let ret: string[] = [] - for (const addr of addresses) { - ret = ret.concat(await getCachedWeekKeysForAddress(addr.address)) - } - return ret -} - const getPaymentsByWeek = (addressString: string, payments: Payment[]): KeyValueT => { const paymentsGroupedByKey: KeyValueT = {} for (const payment of payments) { @@ -212,29 +302,6 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: } } -export const getCachedPaymentsForUser = async (userId: string): Promise => { - const weekKeys = await getCachedWeekKeysForUser(userId) - const userButtonIds: string[] = (await fetchPaybuttonArrayByUserId(userId)) - .map(p => p.id) - let allPayments: Payment[] = [] - for (const weekKey of weekKeys) { - const paymentsString = await redis.get(weekKey) - if (paymentsString === null) { - throw new Error(RESPONSE_MESSAGES.CACHED_PAYMENT_NOT_FOUND_404.message) - } - let weekPayments: Payment[] = JSON.parse(paymentsString) - weekPayments = weekPayments - .map(pay => { - pay.buttonDisplayDataList = pay.buttonDisplayDataList.filter(d => - userButtonIds.includes(d.id) - ) - return pay - }) - allPayments = allPayments.concat(weekPayments) - } - return allPayments -} - export const getCachedPaymentsCountForUser = async (userId: string, timezone: string): Promise => { const dashboardData = await getUserDashboardData(userId, timezone) @@ -443,29 +510,15 @@ const cacheAddressesInBackground = async (addresses: Address[], userId: string): } } +/** + * Yields the user's cached payments, starting a background rebuild of any of + * their addresses that aren't cached yet (whose payments are left out). + */ export async function * getPaymentStream (userId: string): AsyncGenerator { - await triggerBackgroundRebuildIfNeeded(userId) + const states = await getUserAddressCacheStates(userId) + triggerBackgroundRebuildIfNeeded(userId, states) const userButtonIds: string[] = (await fetchPaybuttonArrayByUserId(userId)) .map(p => p.id) - const weekKeys = await getCachedWeekKeysForUser(userId) - - for (const weekKey of weekKeys) { - const paymentsString = await redis.get(weekKey) - - if (paymentsString !== null) { - let weekPayments: Payment[] = JSON.parse(paymentsString) - weekPayments = weekPayments - .map(pay => { - pay.buttonDisplayDataList = pay.buttonDisplayDataList.filter(d => - userButtonIds.includes(d.id) - ) - return pay - }) - - for (const payment of weekPayments) { - yield payment - } - } - } + yield * getPaymentsForWeekKeys(states.flatMap(s => s.weekKeys), userButtonIds) } diff --git a/services/transactionService.ts b/services/transactionService.ts index 18f85eaa..30e01338 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -323,6 +323,32 @@ export async function * generateTransactionsWithPaybuttonsAndPricesForAddress (a } } +export interface TimestampRange { + min: number + max: number +} + +/** + * Oldest and newest tx timestamp of each given address, keyed by address id. + * Addresses with no txs are left out. Uses only the (addressId, timestamp) + * index, so it stays cheap for addresses with huge histories. + */ +export async function fetchTxTimestampRangesByAddressId (addressIds: string[]): Promise> { + const ranges = new Map() + if (addressIds.length === 0) return ranges + const rows = await prisma.transaction.groupBy({ + by: ['addressId'], + where: { addressId: { in: addressIds } }, + _min: { timestamp: true }, + _max: { timestamp: true } + }) + for (const row of rows) { + if (row._min.timestamp === null || row._max.timestamp === null) continue + ranges.set(row.addressId, { min: row._min.timestamp, max: row._max.timestamp }) + } + return ranges +} + /** * Txs of an address created, updated or linked to prices at or after `since`: * what a cache rebuild that started reading at `since` may have missed. Same diff --git a/tests/unittests/paymentCache.test.ts b/tests/unittests/paymentCache.test.ts new file mode 100644 index 00000000..80c5fc5c --- /dev/null +++ b/tests/unittests/paymentCache.test.ts @@ -0,0 +1,178 @@ +import { Address } from '@prisma/client' +import moment from 'moment-timezone' +import { CacheSet } from 'redis/index' +import { getPaymentList, getPaymentStream } from 'redis/paymentCache' +import { getCacheBuiltKey } from 'redis/cacheGeneration' +import * as addressService from 'services/addressService' +import * as paybuttonService from 'services/paybuttonService' +import * as transactionService from 'services/transactionService' +import { PAYMENT_WEEK_KEY_FORMAT } from 'constants/index' + +const weekKeyFor = (addressString: string, timestamp: number): string => + `${addressString}:payments:${moment.unix(timestamp).format(PAYMENT_WEEK_KEY_FORMAT)}` + +// In-memory stand-in for the commands the payment cache reads with. +const store = new Map() +const scanStream = jest.fn() +// Runs before each MGET is served, to change the store between existence checks and reads. +let beforeMget = (): void => {} +jest.mock('redis/clientInstance', () => ({ + redis: { + get: async (key: string) => store.get(key) ?? null, + mget: async (keys: string[]) => { + beforeMget() + return keys.map(k => store.get(k) ?? null) + }, + set: async (key: string, value: string) => { store.set(key, value) }, + del: async (key: string) => { store.delete(key) }, + pipeline: (commands: string[][]) => ({ + exec: async () => commands.map(([cmd, key]) => { + if (cmd !== 'exists') throw new Error(`unexpected pipelined command ${cmd}`) + return [null, store.has(key) ? 1 : 0] + }) + }), + scanStream: (...args: unknown[]) => scanStream(...args) + } +})) + +// Plain factories (no requireActual): these modules import each other, and +// loading the real ones here would hand paymentCache other copies of the mocks. +jest.mock('redis/index', () => ({ + CacheSet: { addressCreation: jest.fn() }, + dropCachesBuiltWithoutAddressTxs: jest.fn(), + isAddressRebuildBackedOff: jest.fn(() => false) +})) + +jest.mock('services/addressService', () => ({ + fetchAllUserAddresses: jest.fn() +})) + +jest.mock('services/paybuttonService', () => ({ + fetchPaybuttonArrayByUserId: jest.fn() +})) + +jest.mock('services/transactionService', () => ({ + fetchTxTimestampRangesByAddressId: jest.fn(), + generateTransactionsWithPaybuttonsAndPricesForAddress: jest.fn(), + getTransactionValue: jest.fn(), + getOldestPositiveTxForUser: jest.fn() +})) + +const mockedAddressCreation = CacheSet.addressCreation as jest.Mock +const mockedFetchAddresses = addressService.fetchAllUserAddresses as jest.Mock +const mockedFetchButtons = paybuttonService.fetchPaybuttonArrayByUserId as jest.Mock +const mockedFetchRanges = transactionService.fetchTxTimestampRangesByAddressId as jest.Mock + +// Background rebuilds are tracked per user for the process, so each test uses its own. +let userCounter = 0 +let userId: string + +const makeAddress = (n: number): Address => ({ id: `addr-id-${n}`, address: `ecash:addr-${n}` }) as unknown as Address + +const payment = (hash: string, timestamp: number, buttonIds: string[]): unknown => ({ + hash, + timestamp, + values: { usd: '1', cad: '1' }, + buttonDisplayDataList: buttonIds.map(id => ({ id, name: id })) +}) + +const cacheWeek = (address: Address, payments: Array<{ hash: string, timestamp: number }>): void => { + store.set(weekKeyFor(address.address, payments[0].timestamp), JSON.stringify(payments)) +} + +const collect = async (stream: AsyncGenerator<{ hash: string }>): Promise => { + const hashes: string[] = [] + for await (const p of stream) hashes.push(p.hash) + return hashes.sort() +} + +describe('payment cache week key lookup', () => { + beforeEach(() => { + store.clear() + beforeMget = () => {} + jest.clearAllMocks() + userCounter++ + userId = `user-${userCounter}` + mockedFetchButtons.mockResolvedValue([{ id: 'button-1' }]) + mockedAddressCreation.mockResolvedValue(true) + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('reads every cached week in the address\'s tx range, across year boundaries, without scanning', async () => { + const address = makeAddress(1) + // Late December and early January land in ISO weeks named after the other year. + const timestamps = [ + moment('2024-06-15T12:00:00').unix(), + moment('2024-12-30T12:00:00').unix(), + moment('2025-01-02T12:00:00').unix(), + moment('2026-01-01T12:00:00').unix() + ] + timestamps.forEach((ts, i) => cacheWeek(address, [payment(`h${i}`, ts, ['button-1']) as any])) + mockedFetchAddresses.mockResolvedValue([address]) + mockedFetchRanges.mockResolvedValue(new Map([[address.id, { min: timestamps[0], max: timestamps[3] }]])) + + await expect(collect(getPaymentStream(userId) as any)).resolves.toEqual(['h0', 'h1', 'h2', 'h3']) + expect(scanStream).not.toHaveBeenCalled() + expect(mockedAddressCreation).not.toHaveBeenCalled() + }) + + it('reads a week cached after the address\'s newest tx was read, up to now', async () => { + const address = makeAddress(2) + const old = moment().subtract(60, 'days').unix() + const recent = moment().subtract(1, 'hour').unix() + cacheWeek(address, [payment('old', old, ['button-1']) as any]) + cacheWeek(address, [payment('recent', recent, ['button-1']) as any]) + mockedFetchAddresses.mockResolvedValue([address]) + mockedFetchRanges.mockResolvedValue(new Map([[address.id, { min: old, max: old }]])) + + await expect(collect(getPaymentStream(userId) as any)).resolves.toEqual(['old', 'recent']) + }) + + it('keeps only the user\'s own buttons on each payment', async () => { + const address = makeAddress(3) + const ts = moment('2025-03-10T12:00:00').unix() + cacheWeek(address, [payment('h', ts, ['button-1', 'someone-elses-button']) as any]) + mockedFetchAddresses.mockResolvedValue([address]) + mockedFetchRanges.mockResolvedValue(new Map([[address.id, { min: ts, max: ts }]])) + + const payments = await getPaymentList(userId) + + expect(payments).toHaveLength(1) + expect(payments[0].buttonDisplayDataList.map(b => b.id)).toEqual(['button-1']) + }) + + it('rebuilds only addresses that have neither the built marker nor any cached week', async () => { + const ts = moment('2025-03-10T12:00:00').unix() + const legacyCached = makeAddress(4) // cached before the built marker existed + const builtEmpty = makeAddress(5) // rebuilt, but has no payments to cache + const uncached = makeAddress(6) + const noTxs = makeAddress(7) + cacheWeek(legacyCached, [payment('h', ts, ['button-1']) as any]) + store.set(getCacheBuiltKey(builtEmpty.address), '1') + mockedFetchAddresses.mockResolvedValue([legacyCached, builtEmpty, uncached, noTxs]) + mockedFetchRanges.mockResolvedValue(new Map([ + [legacyCached.id, { min: ts, max: ts }], + [builtEmpty.id, { min: ts, max: ts }], + [uncached.id, { min: ts, max: ts }] + ])) + + await expect(collect(getPaymentStream(userId) as any)).resolves.toEqual(['h']) + + expect(mockedAddressCreation.mock.calls.map(([a]) => a.address)).toEqual([uncached.address, noTxs.address]) + }) + + it('skips a week deleted between the existence check and the read', async () => { + const address = makeAddress(8) + const ts = moment('2025-03-10T12:00:00').unix() + cacheWeek(address, [payment('h', ts, ['button-1']) as any]) + mockedFetchAddresses.mockResolvedValue([address]) + mockedFetchRanges.mockImplementation(async () => new Map([[address.id, { min: ts, max: ts }]])) + beforeMget = () => store.clear() + + await expect(collect(getPaymentStream(userId) as any)).resolves.toEqual([]) + }) +})