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
10 changes: 10 additions & 0 deletions constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,16 @@ export const TRIGGER_LOG_BATCH_SIZE = 200
export const PRICES_CONNECTION_BATCH_SIZE = 1_000
// interactive $transaction timeout in ms (for batched delete + createMany of prices)
export const PRICES_CONNECTION_TIMEOUT = 30_000
// Txs whose price links are replaced per DB transaction (2 links per tx). Small
// chunks keep each transaction well under PRICES_CONNECTION_TIMEOUT and mean a
// failure only loses that chunk, not the whole run.
export const PRICES_CONNECTION_TX_CHUNK_SIZE = 500
// Unpriced txs loaded into memory per page by connectAllTransactionsToPrices.
export const UNPRICED_TXS_PAGE_SIZE = 5_000
// How often the jobs process retries linking prices for txs that still have none.
export const PRICE_LINKING_REPEAT_DELAY = 60 * 60 * 1000
// Wait before retrying a sync insert whose DB transaction timed out.
export const SYNC_INSERT_RETRY_DELAY = 2_000

export const CLIENT_PAYMENT_EXPIRATION_TIME = (7) * (24 * 60 * 60 * 1000) // (number of days) * (24 * 60 * 60 * 1000)

Expand Down
23 changes: 21 additions & 2 deletions jobs/initJobs.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY } from 'constants/index'
import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY, PRICE_LINKING_REPEAT_DELAY } from 'constants/index'
import { Queue } from 'bullmq'
import { redisBullMQ } from 'redis/clientInstance'
import EventEmitter from 'events'
import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker } from './workers'
import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker, linkUnpricedTransactionsWorker } from './workers'

EventEmitter.defaultMaxListeners = 20

Expand All @@ -11,10 +11,12 @@ const main = async (): Promise<void> => {
const pricesQueue = new Queue('pricesSync', { connection: redisBullMQ })
const blockchainQueue = new Queue('blockchainSync', { connection: redisBullMQ })
const cleanupQueue = new Queue('clientPaymentCleanup', { connection: redisBullMQ })
const priceLinkingQueue = new Queue('priceLinking', { connection: redisBullMQ })

await pricesQueue.obliterate({ force: true })
await blockchainQueue.obliterate({ force: true })
await cleanupQueue.obliterate({ force: true })
await priceLinkingQueue.obliterate({ force: true })

// Start blockchain sync first; current prices job starts only after it completes
await blockchainQueue.add('syncBlockchainAndPrices',
Expand Down Expand Up @@ -54,6 +56,23 @@ const main = async (): Promise<void> => {
)

await cleanupClientPaymentsWorker(cleanupQueue.name)

// Runs right away and then periodically, independent of the blockchain sync,
// so unpriced txs get linked even if that sync is interrupted before its end.
await priceLinkingQueue.add(
'linkUnpricedTransactions',
{},
{
jobId: 'linkUnpricedTransactions',
removeOnComplete: true,
removeOnFail: true,
repeat: {
every: PRICE_LINKING_REPEAT_DELAY,
immediately: true
}
}
)
await linkUnpricedTransactionsWorker(priceLinkingQueue.name)
}

void main()
20 changes: 20 additions & 0 deletions jobs/workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,26 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet
})
}

// Links txs that still have no prices (e.g. a failed per-batch link during sync,
// or a startup sync that was interrupted before finishing).
export const linkUnpricedTransactionsWorker = async (queueName: string): Promise<void> => {
const worker = new Worker(
queueName,
async (job) => {
console.log(`[PRICES] job ${job.id as string}: linking txs without prices...`)
await connectAllTransactionsToPrices()
},
{
connection: redisBullMQ,
lockDuration: DEFAULT_WORKER_LOCK_DURATION
}
)

worker.on('failed', (job, err) => {
console.error(`[PRICES] job ${job?.id as string}: linking txs without prices FAILED — ${err.message}`)
})
}

export const cleanupClientPaymentsWorker = async (queueName: string): Promise<void> => {
const worker = new Worker(
queueName,
Expand Down
20 changes: 20 additions & 0 deletions redis/clientInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@ import IORedis, { ScanStream } from 'ioredis'
import { ScanStreamOptions } from 'ioredis/built/types'

class RedisMocked {
private readonly sets = new Map<string, Set<string>>()

async get (_: string): Promise<null> {
return null
}

async sadd (key: string, ...members: string[]): Promise<number> {
const set = this.sets.get(key) ?? new Set<string>()
const before = set.size
members.forEach(m => set.add(m))
this.sets.set(key, set)
return set.size - before
}

async smembers (key: string): Promise<string[]> {
return [...(this.sets.get(key) ?? [])]
}

async srem (key: string, ...members: string[]): Promise<number> {
const set = this.sets.get(key)
if (set === undefined) return 0
return members.filter(m => set.delete(m)).length
}

async del (key: string, data: any): Promise<void> {
}

Expand Down
29 changes: 28 additions & 1 deletion services/chronikService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import {
upsertTransaction,
getSimplifiedTransactions,
getSimplifiedTrasaction,
connectTransactionsToPricesForAddresses
connectTransactionsToPricesForAddresses,
connectTransactionsListToPrices,
invalidateCachesForAddresses
} from './transactionService'
import { CacheSet } from 'redis/index'
import {
Expand Down Expand Up @@ -1107,6 +1109,31 @@ export class ChronikBlockchainClient {
`${commitTuples.length}`
)

// Link prices batch by batch instead of only at the end of the sync job, so
// an interrupted sync (restart, deploy) doesn't leave everything unpriced.
// A failure here is not fatal: connectAllTransactionsToPrices retries later.
if (syncResult.inserted.length > 0) {
try {
const linkedIds = new Set(await connectTransactionsListToPrices(
syncResult.inserted.map(t => ({ ...t, address: { networkId: this.networkId } })),
{ skipUnlink: true }
))
// The bulk path doesn't add txs to cached payments, so drop the caches of
// addresses whose new txs are now priced instead of waiting for the end of
// the sync, which an interrupted sync never reaches. Txs left unpriced are
// invalidated by connectAllTransactionsToPrices once it links them.
const addressStringById = new Map(commitTuples.map(t => [t.row.addressId, t.addressString]))
const linkedAddresses = [...new Set(
syncResult.inserted.filter(t => linkedIds.has(t.id)).map(t => addressStringById.get(t.addressId))
)].filter((a): a is string => a !== undefined)
if (linkedAddresses.length > 0) {
await invalidateCachesForAddresses(linkedAddresses)
}
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to link prices for ${syncResult.inserted.length} synced txs: ${err.message as string}`)
}
}

const createdForProd = syncResult.inserted.filter(t =>
productionAddressesIds.includes(t.addressId)
)
Expand Down
Loading
Loading