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
85 changes: 81 additions & 4 deletions services/chronikService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ export class ChronikBlockchainClient {
// retry loops belonging to a replaced endpoint can tell they are stale.
private wsGeneration = 0
private wsClosedOnPurpose = false
// Whether a WS connection has been opened before, so later ones are reconnects.
private wsHasConnected = false
// Post-reconnect backfill in progress, and whether another reconnect asked for one meanwhile.
private wsBackfillRun: Promise<void> | undefined
private wsBackfillPending = false
private confirmedTxsBeingProcessed = 0

constructor (networkSlug: string) {
Expand Down Expand Up @@ -210,7 +215,12 @@ export class ChronikBlockchainClient {
for (let attempt = 1; this.isCurrentWs(generation); attempt++) {
try {
await endpoint.waitForOpen()
if (!this.isCurrentWs(generation)) return
console.log(`${this.CHRONIK_MSG_PREFIX}: WebSocket connected.`)
if (this.wsHasConnected) {
void this.backfillAfterReconnect()
}
this.wsHasConnected = true
return
} catch (err: any) {
const delay = Math.min(baseDelay * Math.pow(2, Math.min(attempt - 1, 16)), CHRONIK_WS_MAX_DELAY_MS)
Expand All @@ -220,6 +230,40 @@ export class ChronikBlockchainClient {
}
}

// Txs that hit the mempool or a block while the WS was down never produce a WS
// message, so their payments, triggers and client payment statuses would be
// missed until the next restart. After each reconnect, sync the subscribed
// addresses to catch them.
// Runs one at a time; reconnects during a run schedule a single follow-up run.
public async backfillAfterReconnect (): Promise<void> {
if (this.wsBackfillRun !== undefined) {
this.wsBackfillPending = true
return
}
this.wsBackfillRun = (async () => {
do {
this.wsBackfillPending = false
const subscribed = this.getSubscribedAddresses()
if (subscribed.length === 0) continue
try {
const addresses = await fetchAddressesArray(subscribed)
console.log(`${this.CHRONIK_MSG_PREFIX}: Syncing ${addresses.length} subscribed addresses for txs missed while the WebSocket was down...`)
const { failedAddressesWithErrors, successfulAddressesWithCount } = await this.syncAddresses(addresses, true, true)
const missed = Object.values(successfulAddressesWithCount).reduce((p, c) => p + c, 0)
const failed = Object.keys(failedAddressesWithErrors).length
console.log(`${this.CHRONIK_MSG_PREFIX}: Post-reconnect sync found ${missed} missed txs (${failed} addresses failed).`)
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: Post-reconnect sync failed: ${err.message as string}`)
}
} while (this.wsBackfillPending)
})()
try {
await this.wsBackfillRun
} finally {
this.wsBackfillRun = undefined
}
}

private async handleWsEnded (generation: number): Promise<void> {
if (!this.isCurrentWs(generation)) return
console.log(`${this.CHRONIK_MSG_PREFIX}: Reconnecting chronik WebSocket in ${CHRONIK_WS_BASE_DELAY_MS / 1000}s...`)
Expand Down Expand Up @@ -804,7 +848,11 @@ export class ChronikBlockchainClient {
// round is not retried. With autoReconnect off every close ends up in onEnd
// (onReconnect is never called), and we reconnect from there ourselves.
onEnd: (e: ws.Event) => {
console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}.`)
// The close code tells who ended it: 1006 means the connection dropped
// without a close frame (network/NAT/firewall), while 1000/1001 or other
// codes with a reason mean the server or a proxy closed it on purpose.
const { code, reason, wasClean } = e as ws.CloseEvent
console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}, code: ${code}, reason: ${reason === '' ? '(none)' : reason}, clean: ${String(wasClean)}.`)
void this.handleWsEnded(generation)
},
autoReconnect: false
Expand Down Expand Up @@ -1143,7 +1191,8 @@ export class ChronikBlockchainClient {
private async commitTransactionsBatch (
commitTuples: Array<{ row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string }>,
productionAddressesIds: string[],
runTriggers: boolean
runTriggers: boolean,
reconcileClientPayments = false
): Promise<string[]> {
const rows = commitTuples.map(p => p.row)
const rowsToUpsert = await filterRowsNeedingCreateMany(rows)
Expand Down Expand Up @@ -1225,6 +1274,10 @@ export class ChronikBlockchainClient {
triggerBatch.length = 0
}

if (reconcileClientPayments) {
await this.reconcileClientPaymentsForBatch(commitTuples)
}

// Get the latest timestamp of all committed transactions (including pre-existent) for each address.
// This is redundant under normal circumstances, but is more robust than only updating for the newly created transactions.
const addressMaxTimestamp = new Map<string, number>()
Expand Down Expand Up @@ -1265,7 +1318,31 @@ export class ChronikBlockchainClient {
return changedAddresses
}

public async syncAddresses (addresses: Address[], runTriggers = false): Promise<SyncAndSubscriptionReturn> {
// Applies the live WS handlers' client payment rules to synced txs, whose
// messages were missed: a confirmed tx sets its client payment to CONFIRMED,
// an unconfirmed one to ADDED_TO_MEMPOOL. Covers every tx in the batch, not
// only new rows, so a tx first seen before a disconnect and confirmed during
// it is reconciled too. A failure is logged and doesn't fail the batch.
private async reconcileClientPaymentsForBatch (
commitTuples: Array<{ row: Prisma.TransactionUncheckedCreateInput, addressString: string }>
): Promise<void> {
const zero = new Prisma.Decimal(0)
for (const { row, addressString } of commitTuples) {
// Same filter as getAddressesForTransaction in the live handlers.
if (zero.equals(row.amount as Prisma.Decimal)) continue
const opReturn = typeof row.opReturn === 'string' ? row.opReturn : undefined
const status: ClientPaymentStatus = row.confirmed === true ? 'CONFIRMED' : 'ADDED_TO_MEMPOOL'
try {
await this.handleUpdateClientPaymentStatus(row.amount, opReturn, status, addressString)
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to reconcile client payment for ${row.hash} (${addressString}): ${err.message as string}`)
}
}
}

// reconcileClientPayments: also update client payment statuses as the live WS
// handlers would (used by the post-reconnect backfill).
public async syncAddresses (addresses: Address[], runTriggers = false, reconcileClientPayments = false): Promise<SyncAndSubscriptionReturn> {
const failedAddressesWithErrors: KeyValueT<string> = {}
const successfulAddressesWithCount: KeyValueT<number> = {}
const productionAddressesIds = productionAddresses.filter(a => a.networkId === this.networkId).map(a => a.id)
Expand All @@ -1290,7 +1367,7 @@ export class ChronikBlockchainClient {
let changedAddressesUnknown = false
const commit = async (tuples: RowWithRaw[]): Promise<void> => {
try {
const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers)
const changed = await this.commitTransactionsBatch(tuples, productionAddressesIds, runTriggers, reconcileClientPayments)
changed.forEach(a => changedAddresses.add(a))
} catch (err) {
changedAddressesUnknown = true
Expand Down
120 changes: 120 additions & 0 deletions tests/unittests/chronikService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1711,6 +1711,126 @@ describe('chronik WebSocket reconnection', () => {

expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16)
})

it('logs the close code, reason and whether the close was clean', async () => {
const log = jest.spyOn(console, 'log').mockImplementation(() => {})
configs[0].onEnd({ type: 'close', code: 1006, reason: '', wasClean: false })

expect(log).toHaveBeenCalledWith(expect.stringContaining('code: 1006, reason: (none), clean: false'))
log.mockRestore()
})

describe('post-reconnect backfill', () => {
const mockedFetchAddresses = fetchAddressesArray as jest.Mock

it('backfills on a reconnect but not on the first connection', async () => {
const backfill = jest.spyOn(client, 'backfillAfterReconnect').mockResolvedValue(undefined)
client.wsHasConnected = false

await client.connectWsWithRetry(mkEndpoint(), client.wsGeneration)
expect(backfill).not.toHaveBeenCalled()

configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)
expect(backfill).toHaveBeenCalledTimes(1)
})

it('syncs the subscribed addresses with triggers and client payment reconciliation enabled', async () => {
const addresses = [{ address: subscribedAddresses[0] }]
mockedFetchAddresses.mockResolvedValue(addresses as any)
const sync = jest.spyOn(client, 'syncAddresses').mockResolvedValue({ failedAddressesWithErrors: {}, successfulAddressesWithCount: {} })

await client.backfillAfterReconnect()

expect(fetchAddressesArray).toHaveBeenCalledWith(subscribedAddresses)
expect(sync).toHaveBeenCalledWith(addresses, true, true)
})

it('runs one backfill at a time and coalesces reconnects during a run into one more', async () => {
mockedFetchAddresses.mockResolvedValue([] as any)
let release!: () => void
const sync = jest.spyOn(client, 'syncAddresses')
.mockImplementationOnce(async () => await new Promise(resolve => { release = () => resolve({ failedAddressesWithErrors: {}, successfulAddressesWithCount: {} }) }))
.mockResolvedValue({ failedAddressesWithErrors: {}, successfulAddressesWithCount: {} })

const first = client.backfillAfterReconnect()
await jest.advanceTimersByTimeAsync(0)
await client.backfillAfterReconnect()
await client.backfillAfterReconnect()
expect(sync).toHaveBeenCalledTimes(1)

release()
await first
expect(sync).toHaveBeenCalledTimes(2)
})

it('does not throw when the sync fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
mockedFetchAddresses.mockRejectedValue(new Error('db down'))

await expect(client.backfillAfterReconnect()).resolves.toBeUndefined()
})
})
})

describe('commitTransactionsBatch client payment reconciliation', () => {
const tuple = (hash: string, amount: number, confirmed: boolean, opReturn = '{"paymentId":"pid"}'): any => ({
row: { hash, addressId: 'addr-1', timestamp: 1700000000, amount: new Prisma.Decimal(amount), confirmed, opReturn },
raw: {},
addressString: 'ecash:addr-1'
})

let client: any
let update: jest.SpyInstance

beforeEach(() => {
process.env.WS_AUTH_KEY = 'test-auth-key'
;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 0, inserted: [], updatedAddressIds: [] })
jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any)
jest.spyOn(console, 'log').mockImplementation(() => {})
client = new ChronikBlockchainClient('ecash')
update = jest.spyOn(client, 'handleUpdateClientPaymentStatus').mockResolvedValue(undefined)
})

afterEach(() => {
jest.restoreAllMocks()
})

it('sets CONFIRMED for confirmed txs and ADDED_TO_MEMPOOL for unconfirmed ones, as the live handlers do', async () => {
const confirmed = tuple('hash-1', 5, true)
const unconfirmed = tuple('hash-2', 7, false)

await client.commitTransactionsBatch([confirmed, unconfirmed], [], false, true)

expect(update).toHaveBeenCalledWith(confirmed.row.amount, confirmed.row.opReturn, 'CONFIRMED', 'ecash:addr-1')
expect(update).toHaveBeenCalledWith(unconfirmed.row.amount, unconfirmed.row.opReturn, 'ADDED_TO_MEMPOOL', 'ecash:addr-1')
})

it('reconciles txs that already existed, not only newly inserted ones', async () => {
await client.commitTransactionsBatch([tuple('hash-1', 5, true)], [], false, true)

expect(update).toHaveBeenCalledTimes(1)
})

it('skips zero-amount txs, like the live handlers', async () => {
await client.commitTransactionsBatch([tuple('hash-1', 0, true)], [], false, true)

expect(update).not.toHaveBeenCalled()
})

it('does nothing unless asked to', async () => {
await client.commitTransactionsBatch([tuple('hash-1', 5, true)], [], false)

expect(update).not.toHaveBeenCalled()
})

it('keeps going and does not fail the batch when one update fails', async () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
update.mockRejectedValueOnce(new Error('db down'))

await expect(client.commitTransactionsBatch([tuple('hash-1', 5, true), tuple('hash-2', 6, false)], [], false, true)).resolves.toBeDefined()
expect(update).toHaveBeenCalledTimes(2)
})
})

describe('commitTransactionsBatch price linking', () => {
Expand Down
Loading