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([]) + }) +})