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
2 changes: 1 addition & 1 deletion constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ export const CHRONIK_INITIALIZATION_DELAY = 2000
export const MEMPOOL_PROCESS_DELAY = 100
export const CONFIRMED_TX_PROCESS_DELAY = 100

export const CHRONIK_WS_MAX_CONNECTION_ATTEMPTS = 10
export const CHRONIK_WS_MAX_DELAY_MS = 60000
export const CHRONIK_WS_BASE_DELAY_MS = 5000

// Number of tries before failing a chronik HTTP call (min 1)
Expand Down
91 changes: 52 additions & 39 deletions services/chronikService.ts
Original file line number Diff line number Diff line change
@@ -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, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_MAX_CONNECTION_ATTEMPTS, CHRONIK_WS_BASE_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, 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 {
Expand Down Expand Up @@ -137,7 +137,10 @@ export class ChronikBlockchainClient {
mempoolTxsBeingProcessed!: number

private latencyTestFinished: boolean
private wsReconnecting = false
// Bumped every time a new chronik WS endpoint is created, so callbacks and
// retry loops belonging to a replaced endpoint can tell they are stale.
private wsGeneration = 0
private wsClosedOnPurpose = false
private confirmedTxsBeingProcessed = 0

constructor (networkSlug: string) {
Expand All @@ -156,12 +159,10 @@ export class ChronikBlockchainClient {
config.networkBlockchainURLs[networkSlug]
)
this.latencyTestFinished = true
this.chronikWSEndpoint = this.chronik.ws(this.getWsConfig())
this.CHRONIK_MSG_PREFIX = `[CHRONIK — ${networkSlug}]`
this.confirmedTxsHashesFromLastBlock = []
this.chronikWSEndpoint.subscribeToBlocks()
void this.connectWsWithRetry()
this.openWs()
this.lastProcessedMessages = { confirmed: {}, unconfirmed: {} }
this.CHRONIK_MSG_PREFIX = `[CHRONIK — ${networkSlug}]`
this.wsEndpoint = io(`${config.wsBaseURL}/broadcast`, {
query: {
key: process.env.WS_AUTH_KEY
Expand All @@ -183,40 +184,49 @@ export class ChronikBlockchainClient {
}
}

private async connectWsWithRetry (maxAttempts = CHRONIK_WS_MAX_CONNECTION_ATTEMPTS, baseDelay = CHRONIK_WS_BASE_DELAY_MS): Promise<void> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
private isCurrentWs (generation: number): boolean {
return !this.wsClosedOnPurpose && generation === this.wsGeneration
}

// Creates a fresh chronik WS endpoint (carrying over the given address
// subscriptions) and keeps trying to connect it until it opens or is replaced.
private openWs (addresses: string[] = []): void {
const generation = ++this.wsGeneration
const endpoint = this.chronik.ws(this.getWsConfig(generation))
endpoint.subscribeToBlocks()
for (const addr of addresses) {
endpoint.subscribeToAddress(addr)
}
this.chronikWSEndpoint = endpoint
void this.connectWsWithRetry(endpoint, generation)
}

private async connectWsWithRetry (endpoint: WsEndpoint, generation: number, baseDelay = CHRONIK_WS_BASE_DELAY_MS): Promise<void> {
// Never give up: without this socket no new payments are detected and no triggers run.
for (let attempt = 1; this.isCurrentWs(generation); attempt++) {
try {
await this.chronikWSEndpoint.waitForOpen()
await endpoint.waitForOpen()
console.log(`${this.CHRONIK_MSG_PREFIX}: WebSocket connected.`)
return
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket connection attempt ${attempt}/${maxAttempts} failed: ${err.message as string}`)
if (attempt < maxAttempts) {
const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), 60000)
console.log(`${this.CHRONIK_MSG_PREFIX}: Retrying WebSocket in ${delay / 1000}s...`)
await new Promise(resolve => setTimeout(resolve, delay))
}
const delay = Math.min(baseDelay * Math.pow(2, Math.min(attempt - 1, 16)), CHRONIK_WS_MAX_DELAY_MS)
console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket connection attempt ${attempt} failed: ${err.message as string}. Retrying in ${delay / 1000}s...`)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket failed after ${maxAttempts} attempts. Continuing without real-time updates.`)
}

private async reconnectWs (): Promise<void> {
if (this.wsReconnecting) return
this.wsReconnecting = true
try {
const addresses = this.getSubscribedAddresses()
this.chronikWSEndpoint = this.chronik.ws(this.getWsConfig())
this.chronikWSEndpoint.subscribeToBlocks()
for (const addr of addresses) {
this.chronikWSEndpoint.subscribeToAddress(addr)
}
await this.connectWsWithRetry()
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: WebSocket reconnection error: ${err.message as string}`)
} finally {
this.wsReconnecting = false
}
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...`)
await new Promise(resolve => setTimeout(resolve, CHRONIK_WS_BASE_DELAY_MS))
if (!this.isCurrentWs(generation)) return
this.openWs(this.getSubscribedAddresses())
}

public closeWs (): void {
this.wsClosedOnPurpose = true
this.chronikWSEndpoint?.close()
}

public getUrls (): string[] {
Expand Down Expand Up @@ -736,16 +746,19 @@ export class ChronikBlockchainClient {
return details
}

private getWsConfig (): WsConfig {
private getWsConfig (generation: number): WsConfig {
return {
onMessage: (msg: WsMsgClient) => { void this.processWsMessage(msg) },
onError: (e: ws.ErrorEvent) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket error, type: ${e.type} | message: ${e.message} | error: ${e.error as string}`) },
onReconnect: (_: ws.Event) => {
console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket unexpectedly closed. Attempting reconnection...`)
void this.reconnectWs()
},
onConnect: (_: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket connection (re)established.`) },
onEnd: (e: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}.`) },
// chronik-client's own reconnect is unreliable: a socket error marks the
// endpoint as manually closed (so it never reconnects), and a failed failover
// 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}.`)
void this.handleWsEnded(generation)
},
autoReconnect: false
}
}
Expand Down Expand Up @@ -1505,7 +1518,7 @@ class MultiBlockchainClient {
await Promise.all(
Object.values(this.clients).map(async (c) => {
try {
c.chronikWSEndpoint.close()
c.closeWs()
c.wsEndpoint.close()
} catch (err: any) {
console.error(`Failed to close connections for client: ${err.message as string}`)
Expand Down
64 changes: 60 additions & 4 deletions services/triggerService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { PaybuttonTrigger, Prisma } from '@prisma/client'
import axios from 'axios'
import { RESPONSE_MESSAGES, NETWORK_TICKERS_FROM_ID, SUPPORTED_QUOTES_FROM_ID, TRIGGER_LOG_BATCH_SIZE, TRIGGER_POST_CONCURRENCY, TRIGGER_EMAIL_CONCURRENCY } from 'constants/index'
import { RESPONSE_MESSAGES, NETWORK_TICKERS_FROM_ID, SUPPORTED_QUOTES_FROM_ID, TRIGGER_LOG_BATCH_SIZE, TRIGGER_POST_CONCURRENCY, TRIGGER_EMAIL_CONCURRENCY, N_OF_QUOTES } from 'constants/index'
import prisma from 'prisma-local/clientInstance'
import { EMPTY_OP_RETURN, OpReturnData, parseTriggerPostData } from 'utils/validators'
import { BroadcastTxData, SimplifiedTransaction } from 'ws-service/types'
import { fetchPaybuttonById, fetchPaybuttonWithTriggers } from './paybuttonService'
import config from 'config'
import { MAIL_FROM, MAIL_HTML_REPLACER, MAIL_SUBJECT, getMailerTransporter } from 'constants/mail'
import { getTransactionValue } from './transactionService'
import { AllPrices, QuoteValues, fetchPricesForNetworkAndTimestamp, flattenTimestamp } from './priceService'
import { runAsyncInBatches } from 'utils/index'

// Include Paybutton.owner user inline so we don't refetch per trigger
Expand Down Expand Up @@ -330,6 +331,31 @@ async function fetchTriggersGroupedByAddress (addresses: string[]): Promise<Map<
return triggersByAddress
}

const VALUE_POST_VARIABLE = '<value>'

// Txs persisted by the bulk sync path have no prices linked yet (that happens
// after the sync finishes), so fall back to looking up that day's prices.
async function resolveTransactionValues (
tx: SimplifiedTransaction,
networkId: number,
pricesByDay: Map<number, Promise<AllPrices>>
): Promise<QuoteValues> {
if (tx.prices?.length === N_OF_QUOTES) {
return getTransactionValue(tx)
}
const day = flattenTimestamp(tx.timestamp)
let dayPrices = pricesByDay.get(day)
if (dayPrices === undefined) {
dayPrices = fetchPricesForNetworkAndTimestamp(networkId, day, prisma, true)
pricesByDay.set(day, dayPrices)
}
const { usd, cad } = await dayPrices
return {
usd: usd.value.times(tx.amount),
cad: cad.value.times(tx.amount)
}
}

function buildPostParams (
trigger: TriggerWithPaybuttonAndUser,
tx: SimplifiedTransaction,
Expand Down Expand Up @@ -566,11 +592,23 @@ export async function executeTriggersBatch (broadcasts: BroadcastTxData[], netwo
// Build queues
console.log(`[TRIGGER ${currency}]: preparing triggers for ${txItems.length} txs belonging to ${uniqueAddresses.length} addresses`)

const pricesByDay = new Map<number, Promise<AllPrices>>()
for (const { address, tx } of txItems) {
const triggers = triggersByAddress.get(address) ?? []
if (triggers.length === 0) continue

const values = getTransactionValue(tx)
// Only post triggers that use <value> need prices; a missing price must not
// block email triggers or post triggers that don't send the value.
let values: QuoteValues | undefined
let valuesError: any
if (triggers.some(t => !t.isEmailTrigger && t.postData.includes(VALUE_POST_VARIABLE))) {
try {
values = await resolveTransactionValues(tx, networkId, pricesByDay)
} catch (err: any) {
valuesError = err
console.error(`[TRIGGER ${currency}]: could not get value of tx ${tx.hash}: ${err?.message as string}`)
}
}

for (const trigger of triggers) {
const user = trigger.paybutton.user
Expand All @@ -582,10 +620,28 @@ export async function executeTriggersBatch (broadcasts: BroadcastTxData[], netwo
actionType: 'SendEmail'
})
} else {
let valueStr = ''
if (trigger.postData.includes(VALUE_POST_VARIABLE)) {
if (values === undefined) {
logs.push({
triggerId: trigger.id,
isError: true,
actionType: 'PostData',
data: JSON.stringify({
errorName: valuesError?.name ?? 'Error',
errorMessage: `Could not get the value of tx ${tx.hash}: ${valuesError?.message as string}`,
errorStack: valuesError?.stack ?? '',
triggerPostData: trigger.postData,
triggerPostURL: trigger.postURL
})
})
continue
}
valueStr = values[SUPPORTED_QUOTES_FROM_ID[user.preferredCurrencyId]].toString()
}
userPostCredits[user.id] ??= user.postCredits
const quoteSlug = SUPPORTED_QUOTES_FROM_ID[user.preferredCurrencyId]
;(postTaskQueueByUser[user.id] ??= []).push({
run: makePostTask(trigger, tx, currency, values[quoteSlug].toString(), logs, address),
run: makePostTask(trigger, tx, currency, valueStr, logs, address),
triggerId: trigger.id,
actionType: 'PostData'
})
Expand Down
99 changes: 99 additions & 0 deletions tests/unittests/chronikService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1554,3 +1554,102 @@ describe('WS onMessage matrix (no re-mocks)', () => {
logSpy.mockRestore()
})
})

describe('chronik WebSocket reconnection', () => {
const WS_BASE_DELAY_MS = 5000
const subscribedAddresses = ['ecash:qqkv9wr69ry2p9l53lxp635va4h86wv435995w8p2h']

let client: any
let endpoints: any[]
let configs: any[]

const mkEndpoint = (): any => ({
waitForOpen: jest.fn(async () => {}),
subscribeToBlocks: jest.fn(),
subscribeToAddress: jest.fn(),
close: jest.fn(),
subs: { scripts: [] }
})

beforeEach(async () => {
process.env.WS_AUTH_KEY = 'test-auth-key'
client = new ChronikBlockchainClient('ecash')
await new Promise(resolve => setImmediate(resolve)) // let the async ctor finish

endpoints = []
configs = []
client.chronik = {
ws: jest.fn((config: any) => {
configs.push(config)
const endpoint = mkEndpoint()
endpoints.push(endpoint)
return endpoint
})
}
jest.spyOn(client, 'getSubscribedAddresses').mockReturnValue(subscribedAddresses)
client.openWs()
await Promise.resolve()
jest.useFakeTimers()
})

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

it('opens a new endpoint with the previous subscriptions when the socket ends', async () => {
configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)

expect(client.chronik.ws).toHaveBeenCalledTimes(2)
const newEndpoint = endpoints[1]
expect(client.chronikWSEndpoint).toBe(newEndpoint)
expect(newEndpoint.subscribeToBlocks).toHaveBeenCalled()
expect(newEndpoint.subscribeToAddress).toHaveBeenCalledWith(subscribedAddresses[0])
expect(newEndpoint.waitForOpen).toHaveBeenCalled()
})

it('keeps reconnecting on every subsequent end', async () => {
configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)
configs[1].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)

expect(client.chronik.ws).toHaveBeenCalledTimes(3)
})

it('ignores ends from endpoints that were already replaced', async () => {
configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)
configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS)

expect(client.chronik.ws).toHaveBeenCalledTimes(2)
})

it('does not reconnect after closeWs (shutdown)', async () => {
client.closeWs()
expect(endpoints[0].close).toHaveBeenCalled()
configs[0].onEnd({ type: 'close' })
await jest.advanceTimersByTimeAsync(WS_BASE_DELAY_MS * 10)

expect(client.chronik.ws).toHaveBeenCalledTimes(1)
})

it('keeps retrying the connection instead of giving up after a fixed number of attempts', async () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
const endpoint = mkEndpoint()
let failures = 0
endpoint.waitForOpen.mockImplementation(async () => {
if (failures < 15) {
failures += 1
throw new Error('Error connecting to known Chronik websockets')
}
})
const generation = client.wsGeneration
const done = client.connectWsWithRetry(endpoint, generation)
await jest.advanceTimersByTimeAsync(60000 * 16)
await done

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