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
4 changes: 4 additions & 0 deletions constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ export const CHRONIK_FETCH_N_TXS_PER_PAGE = 200
export const INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY = 16
export const TX_EMIT_BATCH_SIZE = 200 // for our generator, not chronik
export const DB_COMMIT_BATCH_SIZE = 200 // tamanho dos lotes para commit no DB
// Addresses whose startup sync takes longer than this are logged with timings.
export const SLOW_ADDRESS_SYNC_LOG_THRESHOLD = 30_000
// How many of the slowest addresses to list at the end of a startup sync.
export const SLOWEST_ADDRESSES_TO_LOG = 10
export const TX_BATCH_POLLING_DELAY = 500 // delay (ms) between polling for new batches of txs to commit to the DB

export const TRIGGER_POST_CONCURRENCY = 100
Expand Down
32 changes: 22 additions & 10 deletions jobs/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { fetchAllAddresses } from 'services/addressService'
import { cleanupExpiredClientPayments } from 'services/clientPaymentService'
import { multiBlockchainClient } from 'services/chronikService'
import { connectAllTransactionsToPrices } from 'services/transactionService'
import { fetchAllUsers } from 'services/userService'
import { fetchAllUsers, fetchUsersForAddresses } from 'services/userService'

import * as priceService from 'services/priceService'

Expand Down Expand Up @@ -38,25 +38,37 @@ const invalidateAddressCaches = async (
}

/**
* Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync.
* Rebuild is lazy on the next API request.
* Drop Redis payment-week, balance, and dashboard caches after bulk blockchain sync,
* for the addresses whose txs changed and the users who own them. Rebuild is lazy
* on the next API request. Every other cache stays warm: wiping all of them made
* each user's next page load rebuild their whole history from the DB.
* Addresses whose txs were newly linked to prices are invalidated separately by
* connectAllTransactionsToPrices. If the changed set is unknown (the sync failed
* part-way), falls back to invalidating everything.
*/
async function invalidateCachesAfterBlockchainSync (): Promise<void> {
console.log('[CACHE]: Invalidating caches after blockchain sync...')
const addresses = await fetchAllAddresses()
export async function invalidateCachesAfterBlockchainSync (changedAddresses: string[] | undefined): Promise<void> {
const invalidateAll = changedAddresses === undefined
const addresses = invalidateAll
? (await fetchAllAddresses()).map(a => a.address)
: [...new Set(changedAddresses)]
Comment thread
Klakurka marked this conversation as resolved.
Resolved
console.log(
invalidateAll
? `[CACHE]: Invalidating caches for all ${addresses.length} addresses after blockchain sync (changed addresses unknown)...`
: `[CACHE]: Invalidating caches for ${addresses.length} addresses changed by blockchain sync...`
)
let paymentCacheFailures = 0
let balanceCacheFailures = 0
for (let i = 0; i < addresses.length; i += ADDRESS_INVALIDATION_BATCH_SIZE) {
const batch = addresses.slice(i, i + ADDRESS_INVALIDATION_BATCH_SIZE)
const results = await Promise.all(
batch.map(async (a) => await invalidateAddressCaches(a.address))
batch.map(async (a) => await invalidateAddressCaches(a))
)
for (const r of results) {
paymentCacheFailures += r.paymentFailures
balanceCacheFailures += r.balanceFailures
}
}
const users = await fetchAllUsers()
const users = invalidateAll ? await fetchAllUsers() : await fetchUsersForAddresses(addresses)
let dashboardCacheFailures = 0
await Promise.all(
users.map(async (u) => {
Expand Down Expand Up @@ -112,9 +124,9 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet
async (job) => {
console.log(`job ${job.id as string}: syncing missed prices, transactions and connecting them...`)
await priceService.syncPastDaysNewerPrices()
await multiBlockchainClient.syncMissedTransactions()
const changedAddresses = await multiBlockchainClient.syncMissedTransactions()
await connectAllTransactionsToPrices()
await invalidateCachesAfterBlockchainSync()
await invalidateCachesAfterBlockchainSync(changedAddresses)
},
{
connection: redisBullMQ,
Expand Down
8 changes: 7 additions & 1 deletion redis/paymentCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,14 +172,17 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address:
let balance = new Prisma.Decimal(0)
let paymentCount = 0
let txCount = 0
let skippedUnpriced = 0
const txsWithPaybuttonsGenerator = generateTransactionsWithPaybuttonsAndPricesForAddress(address.id)
for await (const batch of txsWithPaybuttonsGenerator) {
for (const tx of batch) {
txCount++
balance = balance.plus(tx.amount)
if (tx.amount.gt(0)) {
// Left out until its prices are linked; connectAllTransactionsToPrices
// then invalidates this address so it is rebuilt with the tx.
Comment thread
Klakurka marked this conversation as resolved.
Resolved
if (tx.prices.length !== N_OF_QUOTES) {
console.warn(`[CACHE] Skipping tx ${tx.hash} — missing price links (${tx.prices.length}/${N_OF_QUOTES})`)
skippedUnpriced++
continue
}
const payment = generatePaymentFromTx(tx)
Expand All @@ -192,6 +195,9 @@ export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address:
}
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1)
console.log(`[CACHE] Cached address ${address.address.slice(0, 20)}...: ${paymentCount} payments, ${txCount} txs in ${elapsed}s`)
if (skippedUnpriced > 0) {
console.warn(`[CACHE] Address ${address.address}: left out ${skippedUnpriced} payments with missing price links.`)
}
const info: AddressPaymentInfo = {
balance,
paymentCount
Expand Down
Loading
Loading