Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
107 changes: 91 additions & 16 deletions redis/cacheGeneration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ 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`
}

// 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<string> => {
return (await redis.get(getGenerationKey(addressString))) ?? '0'
}
Expand All @@ -17,37 +39,90 @@ export const bumpCacheGeneration = async (addressString: string): Promise<void>
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
export const getCacheClearEpoch = async (addressString: string): Promise<string> => {
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<void> => {
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<void> => {
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_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 = 2, #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`. Returns false (and writes nothing) if the address was invalidated
* since, in which case the result is stale and the next read rebuilds it.
* 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]>
entries: Array<[key: string, value: string]>,
{ generation, requireBuilt = false, clearEpoch }: SetIfUnchangedConditions
): Promise<boolean> => {
const result = await redis.eval(
SET_IF_GENERATION_UNCHANGED_SCRIPT,
entries.length + 1,
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<boolean> => {
return await setCacheEntriesIfUnchanged(addressString, entries, { generation })
}
132 changes: 115 additions & 17 deletions redis/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
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, getCacheClearEpoch, getCacheGeneration, setCacheEntriesIfUnchanged } from './cacheGeneration'
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'

Expand All @@ -18,21 +19,118 @@ 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<string, Promise<boolean>>()
// 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<string, number>()

/**
* Rebuilds the address's payment and balance caches from the DB. If the address
* 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. 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<boolean> => {
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]> = [
...Object.entries(groupedPayments).map(([key, payments]): [string, string] => [key, JSON.stringify(payments)]),
[getBalanceKey(addressString), JSON.stringify(info)],
[getCacheBuiltKey(addressString), '1']
]
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
}
} 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<void> => {
const users = await fetchUsersForAddress(addressString)
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<void> => {
await clearBalanceCache(addressString)
await clearDashboardsForAddress(addressString)
}

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<boolean> => {
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
if (isAddressRebuildBackedOff(addressString)) return false

const run = (async () => {
let written: boolean
try {
written = await rebuildAddressCache(address)
rebuildFailedAt.delete(addressString)
} catch (err) {
rebuildFailedAt.set(addressString, Date.now())
throw err
} finally {
rebuildsInFlight.delete(addressString)
Comment thread
Klakurka marked this conversation as resolved.
Resolved
}
if (!written) return false
// 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<void> => {
// A rebuild already reading this address's txs may have missed this one.
Expand Down
Loading
Loading