diff --git a/redis/balanceCache.ts b/redis/balanceCache.ts index 8633f14b..47e357b7 100644 --- a/redis/balanceCache.ts +++ b/redis/balanceCache.ts @@ -1,9 +1,10 @@ import { AddressPaymentInfo, generateAddressPaymentInfo } from 'services/addressService' import { TransactionWithAddressAndPrices } from 'services/transactionService' import { redis } from './clientInstance' +import { bumpCacheGeneration, getCacheGeneration, setIfGenerationUnchanged } from './cacheGeneration' // ADDRESS:balance -const getBalanceKey = (addressString: string): string => { +export const getBalanceKey = (addressString: string): string => { return `${addressString}:balance` } @@ -22,8 +23,12 @@ export const getCachedBalanceForAddress = async (addressString: string): Promise export const getBalanceForAddress = async (addressString: string): Promise => { let paymentInfo = await getCachedBalanceForAddress(addressString) if (paymentInfo === null) { + // Read before the DB so an invalidation during the read discards the result. + const generation = await getCacheGeneration(addressString) paymentInfo = await generateAddressPaymentInfo(addressString) - await cacheBalanceForAddress(paymentInfo, addressString) + await setIfGenerationUnchanged(addressString, generation, [ + [getBalanceKey(addressString), JSON.stringify(paymentInfo)] + ]) } return paymentInfo } @@ -40,6 +45,7 @@ export const updateBalanceCacheFromTx = async (tx: TransactionWithAddressAndPric } export const clearBalanceCache = async (addressString: string): Promise => { + await bumpCacheGeneration(addressString) const key = getBalanceKey(addressString) await redis.del(key, () => {}) } diff --git a/redis/cacheGeneration.ts b/redis/cacheGeneration.ts new file mode 100644 index 00000000..832c67bd --- /dev/null +++ b/redis/cacheGeneration.ts @@ -0,0 +1,53 @@ +import { redis } from './clientInstance' + +// Per-address counter, bumped whenever the address's payment or balance cache is +// invalidated (or a tx for it is created). A rebuild reads it before loading txs +// from the DB and writes its result only if it is unchanged, so a rebuild that +// started before an invalidation can't publish data that predates it, e.g. +// without txs whose prices were linked while it was reading. +const getGenerationKey = (addressString: string): string => { + return `${addressString}:cacheGeneration` +} + +export const getCacheGeneration = async (addressString: string): Promise => { + return (await redis.get(getGenerationKey(addressString))) ?? '0' +} + +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. +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 + redis.call('SET', KEYS[i], ARGV[i]) +end +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. + */ +export const setIfGenerationUnchanged = async ( + addressString: string, + generation: string, + entries: Array<[key: string, value: string]> +): Promise => { + const result = await redis.eval( + SET_IF_GENERATION_UNCHANGED_SCRIPT, + entries.length + 1, + getGenerationKey(addressString), + ...entries.map(([key]) => key), + generation, + ...entries.map(([, value]) => value) + ) + return Number(result) === 1 +} diff --git a/redis/clientInstance.ts b/redis/clientInstance.ts index 64a19bdc..1d2786cb 100755 --- a/redis/clientInstance.ts +++ b/redis/clientInstance.ts @@ -37,6 +37,14 @@ class RedisMocked { return [] } + async incr (key: string): Promise { + return 1 + } + + async eval (...args: unknown[]): Promise { + return 1 + } + scanStream (opt: ScanStreamOptions): ScanStream { const stream = new ScanStream({ ...opt, diff --git a/redis/index.ts b/redis/index.ts index a2b64d56..00211412 100644 --- a/redis/index.ts +++ b/redis/index.ts @@ -2,9 +2,10 @@ import { AddressPaymentInfo } from 'services/addressService' import { PaybuttonWithAddresses } from 'services/paybuttonService' import { TransactionsWithPaybuttonsAndPrices } from 'services/transactionService' import { fetchUsersForAddress } from 'services/userService' -import { cacheBalanceForAddress, clearBalanceCache, getBalanceForAddress, updateBalanceCacheFromTx } from './balanceCache' +import { clearBalanceCache, getBalanceForAddress, getBalanceKey, updateBalanceCacheFromTx } from './balanceCache' +import { bumpCacheGeneration, getCacheGeneration, setIfGenerationUnchanged } from './cacheGeneration' import { clearDashboardCache, getUserDashboardData } from './dashboardCache' -import { appendPaybuttonToAddressesCache, cacheGroupedPayments, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' +import { appendPaybuttonToAddressesCache, cacheManyTxs, clearPaymentCacheForAddress, generateAndCacheGroupedPaymentsAndInfoForAddress, getCachedPaymentsCountForUser, getPaymentList, initPaymentCache, removePaybuttonToAddressesCache } from './paymentCache' import { DashboardData, Payment } from './types' import { Address } from '@prisma/client' @@ -18,12 +19,24 @@ type PaybuttonUpdateParams = PaybuttonCreationParams type PaybuttonDeletionParams = PaybuttonCreationParams export const CacheSet = { - addressCreation: async (address: Address): Promise => { - const groupedPaymentsAndInfo = await generateAndCacheGroupedPaymentsAndInfoForAddress(address) - await cacheGroupedPayments(groupedPaymentsAndInfo.groupedPayments) - await cacheBalanceForAddress(groupedPaymentsAndInfo.info, address.address) + // 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. + 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 }, txCreation: async (tx: TransactionsWithPaybuttonsAndPrices): Promise => { + // A rebuild already reading this address's txs may have missed this one. + await bumpCacheGeneration(tx.address.address) const cacheInitialized = await initPaymentCache(tx.address) if (cacheInitialized) return void await cacheManyTxs([tx]) diff --git a/redis/paymentCache.ts b/redis/paymentCache.ts index 2a226752..ded299aa 100755 --- a/redis/paymentCache.ts +++ b/redis/paymentCache.ts @@ -14,6 +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 { ButtonDisplayData, Payment } from './types' import { getUserDashboardData, clearDashboardCache } from './dashboardCache' // ADDRESS:payments:YYYY:MM @@ -240,14 +241,6 @@ export const getCachedPaymentsCountForUser = async (userId: string, timezone: st return dashboardData.total.payments } -export const cacheGroupedPayments = async (paymentsGroupedByKey: KeyValueT): Promise => { - await Promise.all( - Object.keys(paymentsGroupedByKey).map(async key => - await redis.set(key, JSON.stringify(paymentsGroupedByKey[key])) - ) - ) -} - export const getPaymentsForWeekKey = async (weekKey: string): Promise => { const paymentsString = await redis.get(weekKey) return (paymentsString === null) ? [] : JSON.parse(paymentsString) @@ -333,6 +326,9 @@ export const clearRecentAddressCache = async (addressString: string, timestamps: /** Remove all week-grouped payment keys for an address (forces rebuild from DB). */ 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) const weekKeys = await getCachedWeekKeysForAddress(addressString) if (weekKeys.length === 0) { return @@ -369,7 +365,8 @@ const cacheAddressesInBackground = async (addresses: Address[], userId: string): try { for (const address of addresses) { try { - await CacheSet.addressCreation(address) + // Not written if the address was invalidated meanwhile; the next read retries. + if (!(await CacheSet.addressCreation(address))) continue cached++ if (cached % 10 === 0 || cached === addresses.length) { console.log(`[CACHE] Background: cached ${cached}/${addresses.length} addresses for user ${userId}`) diff --git a/tests/unittests/cacheGeneration.test.ts b/tests/unittests/cacheGeneration.test.ts new file mode 100644 index 00000000..df8eaa60 --- /dev/null +++ b/tests/unittests/cacheGeneration.test.ts @@ -0,0 +1,119 @@ +import { EventEmitter } from 'events' +import { Address } 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' + +// 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 +// one run through eval). +const store = new Map() +jest.mock('redis/clientInstance', () => ({ + redis: { + get: async (key: string) => store.get(key) ?? null, + set: async (key: string, value: string) => { store.set(key, value) }, + del: async (key: string) => { store.delete(key) }, + incr: async (key: string) => { + const next = Number(store.get(key) ?? '0') + 1 + store.set(key, String(next)) + return next + }, + 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 + for (let i = 1; i < keys.length; i++) store.set(keys[i], args[i]) + return 1 + }, + scanStream: ({ match }: { match: string }) => { + const emitter = new EventEmitter() + const prefix = match.replace(/\*$/, '') + process.nextTick(() => { + emitter.emit('data', [...store.keys()].filter(k => k.startsWith(prefix))) + emitter.emit('end') + }) + return emitter + } + } +})) + +jest.mock('redis/paymentCache', () => ({ + ...jest.requireActual('redis/paymentCache'), + generateAndCacheGroupedPaymentsAndInfoForAddress: jest.fn() +})) + +jest.mock('services/addressService', () => ({ + ...jest.requireActual('services/addressService'), + generateAddressPaymentInfo: jest.fn() +})) + +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 } +} + +describe('cache rebuilds vs invalidation', () => { + beforeEach(() => { + store.clear() + mockedGenerate.mockReset() + mockedGenerateBalance.mockReset() + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('writes the rebuilt payment and balance caches when nothing invalidated them', async () => { + mockedGenerate.mockResolvedValue(rebuilt) + + 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)) + }) + + it('discards a rebuild if the address is invalidated while its txs are being read', async () => { + mockedGenerate.mockImplementation(async () => { + // e.g. prices linked for one of its txs, then its caches invalidated + await paymentCache.clearPaymentCacheForAddress(address.address) + return rebuilt + }) + + 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) + }) + + it('rebuilds normally after an earlier invalidation', async () => { + await paymentCache.clearPaymentCacheForAddress(address.address) + mockedGenerate.mockResolvedValue(rebuilt) + + await expect(CacheSet.addressCreation(address)).resolves.toBe(true) + }) + + it('does not cache a balance computed before a balance invalidation', async () => { + mockedGenerateBalance.mockImplementation(async () => { + await clearBalanceCache(address.address) + return rebuilt.info + }) + + await expect(getBalanceForAddress(address.address)).resolves.toEqual(rebuilt.info) + + expect(store.has('ecash:addr-1:balance')).toBe(false) + }) + + it('caches a balance computed without interference', async () => { + mockedGenerateBalance.mockResolvedValue(rebuilt.info) + + await getBalanceForAddress(address.address) + + expect(store.get('ecash:addr-1:balance')).toBe(JSON.stringify(rebuilt.info)) + }) +})