From 521d69661e6b3922eea22278330d9bf9bcf7793a Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 23:49:53 -0700 Subject: [PATCH 1/3] fix: keep chronik WS alive and backfill txs missed while it was down The BCH chronik WebSocket was being closed exactly 60s after every connect, consistent with an idle-timeout proxy in front of the node. Each drop left a gap of 5s+ (longer when reconnect attempts failed) in which mempool/block messages were lost, and nothing re-synced them until the next restart, so payments and triggers for those txs could be missed. - Ping the socket every 25s while it is the current endpoint, so idle proxies see traffic and don't drop it. Stopped on end and on closeWs. - After every reconnect (not the first connect), sync the subscribed addresses through the regular sync path with triggers on, to pick up txs that arrived while disconnected. One run at a time; reconnects during a run coalesce into a single follow-up run. Price linking and cache invalidation already happen per committed batch. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 3 + services/chronikService.ts | 75 +++++++++++++++++++- tests/unittests/chronikService.test.ts | 95 ++++++++++++++++++++++++++ 3 files changed, 172 insertions(+), 1 deletion(-) diff --git a/constants/index.ts b/constants/index.ts index 290ec3c0..853d4129 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -282,6 +282,9 @@ export const CONFIRMED_TX_PROCESS_DELAY = 100 export const CHRONIK_WS_MAX_DELAY_MS = 60000 export const CHRONIK_WS_BASE_DELAY_MS = 5000 +// Ping the chronik WS this often so proxies in front of the node (nginx's default +// proxy_read_timeout is 60s) don't drop it as idle when no txs or blocks arrive. +export const CHRONIK_WS_KEEPALIVE_INTERVAL_MS = 25000 // Number of tries before failing a chronik HTTP call (min 1) export const CHRONIK_HTTP_MAX_TRIES = 3 diff --git a/services/chronikService.ts b/services/chronikService.ts index f8199d6b..5bf998f7 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS, CHRONIK_WS_KEEPALIVE_INTERVAL_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -145,6 +145,12 @@ export class ChronikBlockchainClient { // retry loops belonging to a replaced endpoint can tell they are stale. private wsGeneration = 0 private wsClosedOnPurpose = false + private wsKeepAliveTimer: ReturnType | undefined + // 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 | undefined + private wsBackfillPending = false private confirmedTxsBeingProcessed = 0 constructor (networkSlug: string) { @@ -210,7 +216,13 @@ 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.`) + this.startWsKeepAlive(endpoint, generation) + 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) @@ -220,8 +232,68 @@ export class ChronikBlockchainClient { } } + // Sends a WS ping on an interval while this endpoint is the current one. The + // ping/pong traffic keeps idle-timeout proxies from closing the socket. + private startWsKeepAlive (endpoint: WsEndpoint, generation: number): void { + this.stopWsKeepAlive() + this.wsKeepAliveTimer = setInterval(() => { + if (!this.isCurrentWs(generation)) { + this.stopWsKeepAlive() + return + } + const socket = endpoint.ws + if (socket?.readyState !== ws.WebSocket.OPEN) return + try { + socket.ping() + } catch (err: any) { + console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket keepalive ping failed: ${err.message as string}`) + } + }, CHRONIK_WS_KEEPALIVE_INTERVAL_MS) + } + + private stopWsKeepAlive (): void { + if (this.wsKeepAliveTimer !== undefined) { + clearInterval(this.wsKeepAliveTimer) + this.wsKeepAliveTimer = undefined + } + } + + // Txs that hit the mempool or a block while the WS was down never produce a WS + // message, so their payments and triggers 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 { + 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) + 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 { if (!this.isCurrentWs(generation)) return + this.stopWsKeepAlive() console.log(`${this.CHRONIK_MSG_PREFIX}: Reconnecting chronik WebSocket in ${CHRONIK_WS_BASE_DELAY_MS / 1000}s...`) await new Promise(resolve => setTimeout(resolve, CHRONIK_WS_BASE_DELAY_MS)) if (!this.isCurrentWs(generation)) return @@ -230,6 +302,7 @@ export class ChronikBlockchainClient { public closeWs (): void { this.wsClosedOnPurpose = true + this.stopWsKeepAlive() this.chronikWSEndpoint?.close() } diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 5490c726..61df95ff 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -1711,6 +1711,101 @@ describe('chronik WebSocket reconnection', () => { expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16) }) + + describe('keepalive', () => { + const KEEPALIVE_MS = 25000 + const OPEN = 1 + + it('pings the open socket on an interval', async () => { + const endpoint = mkEndpoint() + endpoint.ws = { readyState: OPEN, ping: jest.fn() } + await client.connectWsWithRetry(endpoint, client.wsGeneration) + + await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 3) + expect(endpoint.ws.ping).toHaveBeenCalledTimes(3) + }) + + it('does not ping a socket that is not open', async () => { + const endpoint = mkEndpoint() + endpoint.ws = { readyState: 3, ping: jest.fn() } + await client.connectWsWithRetry(endpoint, client.wsGeneration) + + await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) + expect(endpoint.ws.ping).not.toHaveBeenCalled() + }) + + it('stops pinging once the socket ends', async () => { + const endpoint = mkEndpoint() + endpoint.ws = { readyState: OPEN, ping: jest.fn() } + await client.connectWsWithRetry(endpoint, client.wsGeneration) + configs[0].onEnd({ type: 'close' }) + + await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) + expect(endpoint.ws.ping).not.toHaveBeenCalled() + }) + + it('stops pinging after closeWs', async () => { + const endpoint = mkEndpoint() + endpoint.ws = { readyState: OPEN, ping: jest.fn() } + await client.connectWsWithRetry(endpoint, client.wsGeneration) + client.closeWs() + + await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) + expect(endpoint.ws.ping).not.toHaveBeenCalled() + }) + }) + + 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 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) + }) + + 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 price linking', () => { From e2611476147fb39c1ac8d0031b8372b4dcfc9439 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Thu, 26 Nov 2026 00:16:12 -0700 Subject: [PATCH 2/3] fix: reconcile client payment statuses in the post-reconnect backfill Txs recovered by the backfill went through the bulk sync path, which never updates client payments, so a payment made while the WS was down stayed pending. syncAddresses/commitTransactionsBatch take an opt-in reconcileClientPayments flag (set by the backfill) that runs every tx in the batch through handleUpdateClientPaymentStatus with the live handlers' rules: zero-amount txs skipped, confirmed -> CONFIRMED, unconfirmed -> ADDED_TO_MEMPOOL. Pre-existing txs are included so one confirmed during the disconnect is reconciled too. Failures are logged per tx and don't fail the batch. Co-Authored-By: Claude Opus 5.5 --- services/chronikService.ts | 42 ++++++++++++++--- tests/unittests/chronikService.test.ts | 64 +++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 8 deletions(-) diff --git a/services/chronikService.ts b/services/chronikService.ts index 5bf998f7..1dcc62a2 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -259,8 +259,9 @@ export class ChronikBlockchainClient { } // Txs that hit the mempool or a block while the WS was down never produce a WS - // message, so their payments and triggers would be missed until the next - // restart. After each reconnect, sync the subscribed addresses to catch them. + // 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 { if (this.wsBackfillRun !== undefined) { @@ -275,7 +276,7 @@ export class ChronikBlockchainClient { 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) + 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).`) @@ -1216,7 +1217,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 { const rows = commitTuples.map(p => p.row) const rowsToUpsert = await filterRowsNeedingCreateMany(rows) @@ -1298,6 +1300,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() @@ -1338,7 +1344,31 @@ export class ChronikBlockchainClient { return changedAddresses } - public async syncAddresses (addresses: Address[], runTriggers = false): Promise { + // 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 { + 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 { const failedAddressesWithErrors: KeyValueT = {} const successfulAddressesWithCount: KeyValueT = {} const productionAddressesIds = productionAddresses.filter(a => a.networkId === this.networkId).map(a => a.id) @@ -1363,7 +1393,7 @@ export class ChronikBlockchainClient { let changedAddressesUnknown = false const commit = async (tuples: RowWithRaw[]): Promise => { 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 diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 61df95ff..73c2549c 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -1770,7 +1770,7 @@ describe('chronik WebSocket reconnection', () => { expect(backfill).toHaveBeenCalledTimes(1) }) - it('syncs the subscribed addresses with triggers enabled', async () => { + 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: {} }) @@ -1778,7 +1778,7 @@ describe('chronik WebSocket reconnection', () => { await client.backfillAfterReconnect() expect(fetchAddressesArray).toHaveBeenCalledWith(subscribedAddresses) - expect(sync).toHaveBeenCalledWith(addresses, true) + expect(sync).toHaveBeenCalledWith(addresses, true, true) }) it('runs one backfill at a time and coalesces reconnects during a run into one more', async () => { @@ -1808,6 +1808,66 @@ describe('chronik WebSocket reconnection', () => { }) }) +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', () => { const inserted = [{ id: 'tx-1', From 2234107141574bb490dab2e2adbf7768ba85cecb Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Thu, 26 Nov 2026 00:17:34 -0700 Subject: [PATCH 3/3] fix: drop the chronik WS keepalive ping and log close codes instead The keepalive was added on the theory that an idle-timeout proxy dropped the BCH socket every 60s. Testing against bch.paybutton.io disproved that: the server pings clients every 45s itself, and sockets stay open without any client pings (even ones that never pong). So the ping didn't address the cause and is removed. What does cause the drops is still unknown, so log the close code, reason and wasClean on every WS end: 1006 means the connection was cut without a close frame (network/NAT/firewall); 1000/1001 or a reason means the server or a proxy closed it on purpose. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 3 -- services/chronikService.ts | 38 ++++------------------ tests/unittests/chronikService.test.ts | 45 +++----------------------- 3 files changed, 11 insertions(+), 75 deletions(-) diff --git a/constants/index.ts b/constants/index.ts index 853d4129..290ec3c0 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -282,9 +282,6 @@ export const CONFIRMED_TX_PROCESS_DELAY = 100 export const CHRONIK_WS_MAX_DELAY_MS = 60000 export const CHRONIK_WS_BASE_DELAY_MS = 5000 -// Ping the chronik WS this often so proxies in front of the node (nginx's default -// proxy_read_timeout is 60s) don't drop it as idle when no txs or blocks arrive. -export const CHRONIK_WS_KEEPALIVE_INTERVAL_MS = 25000 // Number of tries before failing a chronik HTTP call (min 1) export const CHRONIK_HTTP_MAX_TRIES = 3 diff --git a/services/chronikService.ts b/services/chronikService.ts index 1dcc62a2..b41eeef8 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS, CHRONIK_WS_KEEPALIVE_INTERVAL_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -145,7 +145,6 @@ export class ChronikBlockchainClient { // retry loops belonging to a replaced endpoint can tell they are stale. private wsGeneration = 0 private wsClosedOnPurpose = false - private wsKeepAliveTimer: ReturnType | undefined // 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. @@ -218,7 +217,6 @@ export class ChronikBlockchainClient { await endpoint.waitForOpen() if (!this.isCurrentWs(generation)) return console.log(`${this.CHRONIK_MSG_PREFIX}: WebSocket connected.`) - this.startWsKeepAlive(endpoint, generation) if (this.wsHasConnected) { void this.backfillAfterReconnect() } @@ -232,32 +230,6 @@ export class ChronikBlockchainClient { } } - // Sends a WS ping on an interval while this endpoint is the current one. The - // ping/pong traffic keeps idle-timeout proxies from closing the socket. - private startWsKeepAlive (endpoint: WsEndpoint, generation: number): void { - this.stopWsKeepAlive() - this.wsKeepAliveTimer = setInterval(() => { - if (!this.isCurrentWs(generation)) { - this.stopWsKeepAlive() - return - } - const socket = endpoint.ws - if (socket?.readyState !== ws.WebSocket.OPEN) return - try { - socket.ping() - } catch (err: any) { - console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket keepalive ping failed: ${err.message as string}`) - } - }, CHRONIK_WS_KEEPALIVE_INTERVAL_MS) - } - - private stopWsKeepAlive (): void { - if (this.wsKeepAliveTimer !== undefined) { - clearInterval(this.wsKeepAliveTimer) - this.wsKeepAliveTimer = undefined - } - } - // 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 @@ -294,7 +266,6 @@ export class ChronikBlockchainClient { private async handleWsEnded (generation: number): Promise { if (!this.isCurrentWs(generation)) return - this.stopWsKeepAlive() console.log(`${this.CHRONIK_MSG_PREFIX}: Reconnecting chronik WebSocket in ${CHRONIK_WS_BASE_DELAY_MS / 1000}s...`) await new Promise(resolve => setTimeout(resolve, CHRONIK_WS_BASE_DELAY_MS)) if (!this.isCurrentWs(generation)) return @@ -303,7 +274,6 @@ export class ChronikBlockchainClient { public closeWs (): void { this.wsClosedOnPurpose = true - this.stopWsKeepAlive() this.chronikWSEndpoint?.close() } @@ -878,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 diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 73c2549c..cbe08ed7 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -1712,47 +1712,12 @@ describe('chronik WebSocket reconnection', () => { expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16) }) - describe('keepalive', () => { - const KEEPALIVE_MS = 25000 - const OPEN = 1 + 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 }) - it('pings the open socket on an interval', async () => { - const endpoint = mkEndpoint() - endpoint.ws = { readyState: OPEN, ping: jest.fn() } - await client.connectWsWithRetry(endpoint, client.wsGeneration) - - await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 3) - expect(endpoint.ws.ping).toHaveBeenCalledTimes(3) - }) - - it('does not ping a socket that is not open', async () => { - const endpoint = mkEndpoint() - endpoint.ws = { readyState: 3, ping: jest.fn() } - await client.connectWsWithRetry(endpoint, client.wsGeneration) - - await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) - expect(endpoint.ws.ping).not.toHaveBeenCalled() - }) - - it('stops pinging once the socket ends', async () => { - const endpoint = mkEndpoint() - endpoint.ws = { readyState: OPEN, ping: jest.fn() } - await client.connectWsWithRetry(endpoint, client.wsGeneration) - configs[0].onEnd({ type: 'close' }) - - await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) - expect(endpoint.ws.ping).not.toHaveBeenCalled() - }) - - it('stops pinging after closeWs', async () => { - const endpoint = mkEndpoint() - endpoint.ws = { readyState: OPEN, ping: jest.fn() } - await client.connectWsWithRetry(endpoint, client.wsGeneration) - client.closeWs() - - await jest.advanceTimersByTimeAsync(KEEPALIVE_MS * 2) - expect(endpoint.ws.ping).not.toHaveBeenCalled() - }) + expect(log).toHaveBeenCalledWith(expect.stringContaining('code: 1006, reason: (none), clean: false')) + log.mockRestore() }) describe('post-reconnect backfill', () => {