From 7d2a7a81a4e502ba8d299800df2b172b535dc2d5 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Thu, 26 Nov 2026 10:14:20 -0700 Subject: [PATCH 1/2] 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/2] 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 }))